instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I would like to start a small part time business other than my full time programming job. Have you guys done that before? I know programmers who teach in evening schools after work. But then again, that is not business. What would you recommend to get another income stream going?</p>
<p>I have a full time programming day job, and I just started a small software enterprise this year.</p> <p>My advice would be to start small, and make sure you have the time &amp; energy to work on something after your day job is done. If possible, choose a business in which the code you write will be different from the code you write at work. A different language is a good start, but different types of problems would be a much better goal. If you end up working on the same thing 12 hours a day (8 at work, and 4 on the side-job), you will go absolutely crazy in less than two weeks.</p> <p>As for what type of business to start, take a few things into consideration:</p> <ol> <li> What kind of project would you enjoy working on? <li> What skills do you have, or can you learn in order to get this done? <li> How much time do you have available? <li> How much money is your time worth? </ol> <p>Once you have this figured out, you will know which projects make sense for you.</p> <p>The only other piece of advice I can think of is to specialize. If you are a one-man operation, you can't compete with Microsoft. Choose a market in which you offer something really good to a small group of people. These little niche markets are the best place for small software companies to thrive.</p> <p>Good luck and have fun!</p>
<p>I did some work on an opensource project (DotNetNuke) as a developer and made some good contacts through that and became a consultant doing DNN work for various clients.</p> <p>You obvisouly have to make the investment to learn whatever the OSS project is that you're working on, but on the other hand, there's a good chance you could carve out a pretty nice niche for yourself.</p>
40,417
<p>Our graphics person uses Adobe Illustrator and we'd like to use her images inside our WPF application as paths. Is there a way to do this?</p>
<p>You can go from AI to SVG to XAML.</p> <ol> <li><p>From Adobe Illustrator: File -> Save As -> *.SVG.</p> <ul> <li><p>SVG "Profile 1.1" seems to be sufficient.</p></li> <li><p>Note that to preserve path/group names in XAML you should enable "Preserve Illustrator Editing Capabilities" (or at least as it's called in CS4).</p></li> </ul></li> <li><p><a href="https://sharpvectors.codeplex.com/" rel="nofollow noreferrer">SharpVectors</a> can convert SVG data to XAML data. This will produce a fragment of XAML with root <code>&lt;DrawingGroup&gt;</code>.</p></li> <li><p>Do what you need to do to copy-paste and otherwise use the XAML, such as placing it into an Image like below. Named objects or groups in the AI file should still have their names in the XAML i.e. via <code>x:Name="..."</code>.</p></li> </ol> <pre><code>&lt;Image&gt; &lt;Image.Source&gt; &lt;DrawingImage&gt; &lt;DrawingImage.Drawing&gt; &lt;DrawingGroup ... the output from step #2 ...&gt;...&lt;/DrawingGroup&gt; &lt;/DrawingImage.Drawing&gt; &lt;/DrawingImage&gt; &lt;/Image.Source&gt; &lt;/Image&gt; </code></pre> <ol start="4"> <li>Coordinate systems can be a pain if you want to be animating things. There are some other posts such as <a href="https://graphicdesign.stackexchange.com/questions/15401/change-viewbox-attribute-in-svg-exported-by-illustrator">this</a> which may have insights.</li> </ol>
<p>Get her to export the illustrations as some other format (recent versions of Illustrator support SVG) that you can use or convert to something that will work.</p>
18,568
<p>As far as I know, Flash has to pass info off to another external process in order to save files - POSTing to PHP or talking to an executable, right? But every once in a while I hear rumors that Flash is able to open a file, make changes, then save/write those changes, all on its own - is it possible?</p>
<p>This will be available in Flash Player 10:</p> <p>Reading and Writing Local Files in Flash Player 10</p> <p><a href="http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/" rel="noreferrer">http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/</a></p> <p>Otherwise you need to use Adobe AIR, or bounce it off the server.</p> <p>mike chambers</p> <p>mesh@adobe.com</p>
<p>There is something called Local Shared Object, also known as "Flash Cookie" that allows you to store a limited amount of data locally at a user's computer.</p> <p>A little googling turned up a few links:</p> <ul> <li><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html" rel="nofollow noreferrer">Documentation on the SharedObject class</a></li> <li><a href="http://www.aboutflex.net/flex/local-sharedobject/" rel="nofollow noreferrer">A tutorial</a></li> </ul> <p>And I'm sure a little creative googling can turn up even more</p>
13,319
<p>I could write this, but before I do, I wanted to check to see if there are existing solutions out there since it seems a lot of websites already do this, so I was wondering if there was a quick way to do this.</p> <p>Also, I am talking about "popout" windows, not "popup" windows. All JavaScript libraries support "popup" windows, but I want ones where they originally open as "popup" windows in the same browser window, but there is also a link to open them up in a brand new browser window.</p>
<p>Check out Cappuccino, it's more of a windowing framework than a web 2.0 framework. It's based off of Apples Cocoa, and uses a Superset of Javascript called Objective-J. Superset meaning that any JS is valid, but it extends on the language with additional syntax that is similar to Cocoa and Objetive-C.</p> <p><a href="http://cappuccino.org" rel="nofollow noreferrer">http://cappuccino.org</a></p>
<p>I don"t know a framework to do that for you. But the JS code to do that might be simple. </p> <p>For the in-page-popup part, just open an absolute div. If you want the div to become a real popup, open a popup window then remove your div content from the main document and append it to the popup window document (you way have to clone it because JS may not like passing around DOM nodes between different documents).</p>
21,104
<p>I am writing a program that will be emailing reports out many (~100) clients which I want to test before I spam everyone.</p> <p>I want to do a test run against my production data and actually send the messages to a SMTP server, but I don't want the SMTP server to actually deliver the messages. I want the server to act like a real SMTP server from the perspective of my application, but instead of delivering messages, I just want it to store the messages, and log what happened.</p> <p>Is there a SMTP server specifically designed for testing purposes?</p> <p>Does anyone know of a way to configure exim or postfix to behave like I have described above</p> <p>What do you use to test a mass-email delivery?</p>
<p>In java you can use <a href="http://quintanasoft.com/dumbster/" rel="noreferrer">dumbster</a></p> <p>Its easy to use and you can validate every aspect of the email you are intercepting.</p> <p>It's a Java SMTP server implementation meant for unit testing. (Just make sure you redirect your email to the machine running dumbster...)</p> <hr> <p>I just found another alternative that do almost the same: <a href="http://www.icegreen.com/greenmail/" rel="noreferrer">Greenmail</a></p> <p>Greenmail also support POP3, IMAP with SSL so you can test your client against it.</p>
<p>I personally modify the e-mail addresses to test, I send them to a dummy account of mine, that way I can validate not only that they sent, but that they appear in the proper format.</p>
29,864
<p>My Ender 3 LCD display was working ok, I went to turn it on recently but is not showing any signal of life anymore...</p> <p>I have tried unplugging and plugging again, is there a way to test if the screen still works?</p> <p>What is the issue? Or should I just buy and install a new LCD?</p>
<p>There are a few issues that could cause this. Roughness in your z-axis lead screw as pointed out by @TheLamestUsername is a leading contender I would say. I'd also extended that answer to include checking the belts for your X and Y axes as well as making sure that the rods the gantry slide on are smooth since the fault appears to be in about the same X-Y location as well in the one image.</p> <p>However, there are a few alternatives as well. Check/confirm that the material that you're using doesn't have a lot of absorbed moisture in it. This can cause little bits of steam to 'pop' when they're extruded causing some bubbles</p> <p>Because of how the material is folding at the location in the &quot;updated&quot; image this looks to be an issue with the starting and stopping. All of the layer's problems appear to be happening when the gantry moves up to the next layer. Essentially more material is coming out of the nozzle there (I think) than is what should be. Confirming material diameter with some calipers can help if there's just an offset (not too unlikely I don't think).</p> <p>If the diameters are dead on I'd suggest reducing the nozzle temperature by a few degrees. The sensors used to measure the temperature aren't usually all that accurate, though their precision is often pretty good. While you may have it set at 200C that might not be the actual temperature. Calibration of the thermal sensors can drift over time, so while it might have been good on the last roll it may have drifted slightly. Or the material might be of slightly different composition. Try lowering the nozzle temp by 2-5 degrees and see if that has any effect.</p> <p>You may also have a retraction setting that can be modified. Pulling the material back ever so slightly when it finishes the one layer as it moves to the next could alos reduce some of the extra material that's coming out.</p>
<p>The fact that the bumps were in the same spots on multiple occasions points to z-axis problems. Turn your printer off and manually turn the z-axis all the way from bottom to top. If there are any tight spots, there is some <em>z-axis binding</em>. If there are no tight spots, skip to the last paragraph.</p> <p>Try taking off the z-axis by removing the set screws (pictured below). Remember which side was pointing up for a later step.</p> <p><a href="https://i.stack.imgur.com/GnC4r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GnC4r.jpg" alt="enter image description here" /></a></p> <p>Once you do that, clean the screw thoroughly with a brush, cloth, solution, or a combination of those. Put the screw back in the opposite way this time.</p> <p>If you get no bumps, then it was indeed the z-axis</p> <p>If the bumps are still there, try lowering your temperature some more(200 is still a little high compared to what I do for PLA), and <a href="https://all3dp.com/2/extruder-calibration-6-easy-steps-2/" rel="nofollow noreferrer">calibrate your e-steps</a> if you haven't already.</p>
1,689
<p>I have a web service that uses Python's SimpleJSON to serialize JSON, and a javascript/ client that uses Google's Visualization <a href="http://code.google.com/apis/visualization/documentation/reference.html" rel="nofollow noreferrer">API</a>. When I try to read in the JSON response using Google Data Table's Query method, I am getting a "invalid label" error. </p> <p>I noticed that Google spreadsheet outputs JSON without quotes around the object keys. I tried reading in JSON without the quotes and that works. I was wondering what was the best way to get SimpleJSON output to be read into Google datable using </p> <p><code>query = new google.visualization.Query("http://www.myuri.com/api/")</code>. </p> <p>I could use a regex to remove the quotes, but that seems sloppy. The javascript JSON parsing libraries I've tried won't read in JSON syntax without quotes around the object keys.</p> <p>Here's some good background reading re: quotes around object keys: </p> <p><a href="http://simonwillison.net/2006/Oct/11/json/" rel="nofollow noreferrer">http://simonwillison.net/2006/Oct/11/json/</a>.</p>
<p>Are you certain the Google API is expecting JSON? In my experience Google's APIs tend not to be massively broken in a manner you're describing -- it could be that they're actually expecting a different format that merely resembles JSON.</p> <hr> <p>Further poking around reveals instructions for retrieving data in the format Google expects:</p> <blockquote> <p>For example, to get the dataSourceUrl from a Google Spreadsheet, do the following:</p> <ol> <li>In your spreadsheet, select the range of cells.</li> <li>Select 'Insert' and then 'Gadget' from the menu.</li> <li>Open the gadget's menu by clicking on the top-right selector.</li> <li>Select menu option 'Get data source URL'.</li> </ol> </blockquote> <p>I did this and opened the URL in my browser. The data it was returning was certainly not JSON:</p> <pre><code>google.visualization.Query.setResponse( {requestId:'0',status:'ok',signature:'1464883469881501252', table:{cols: [{id:'A',label:'',type:'t',pattern:''}, {id:'B',label:'',type:'t',pattern:''}], rows: [[{v:'a'},{v:'h'}],[{v:'b'},{v:'i'}],[{v:'c'},{v:'j'}],[{v:'d'},{v:'k'}],[{v:'e'},{v:'l'}],[{v:'f'},{v:'m'}],[{v:'g'},{v:'n'}]]}}); </code></pre> <p>It looks like the result is intended to be directly executed by the browser. Try modifying your code to do something like this:</p> <pre><code># old return simplejson.dumps ({"requestId": 1, "status": "ok", ...}) # new json = simplejson.dumps ({"requestId": 1, "status": "ok", ...}) return "google.visualization.Query.setResponse(%r);" % json </code></pre>
<p>As it turns out <strong>:mod:json</strong> would also choke at strings in single quotes. This will sort things out though:</p> <h1>Parse JavaScript object as JSON in python:</h1> <h2>solution:</h2> <pre><code>&gt;&gt;&gt; from re import sub &gt;&gt;&gt; import json &gt;&gt;&gt; js = "{ a: 'a' }" &gt;&gt;&gt; json.loads(sub("'", '"', sub('\s(\w+):', r' "\1":', js))) {u'a': u'a'} </code></pre> <p><strong>Edit:</strong> (edge cases reviewed)</p> <p>So it was brought up that the suggested solution would not cope with all cases and specifically with something like</p> <blockquote> <p>e.g. {foo: "a sentence: right here!"} will get changed to {"foo": "a "sentence": right here!"}<br> – Jason S Apr 12 at 18:03</p> </blockquote> <p>To resolve that we simply need to ensure that we are in fact working with a key and not simply a colon in a string so we do a little look behind magic to hint at a comma(,) or a curly brace({) presence to ensure we have it proper, like so:</p> <h2>colon in string:</h2> <pre><code>&gt;&gt;&gt; js = "{foo: 'a sentence: right here!'}" &gt;&gt;&gt; json.loads(sub("'", '"', sub('(?&lt;={|,)\s*(\w+):', r' "\1":', js))) {u'foo': u'a sentence: right here!'} </code></pre> <p>Which of course is the same as doing:</p> <pre><code>&gt;&gt;&gt; js = "{foo: 'a sentence: right here!'}" &gt;&gt;&gt; json.loads(sub('(?&lt;={|,)\s*(\w+):', r' "\1":', js).replace("'",'"')) {u'foo': u'a sentence: right here!'} </code></pre> <p>But then I pointed out that this is not the only flaw because what about quotes:</p> <p>If we are also concerned about escaped quotes we will have to be slightly more specific as to what constitutes a string. The first quote will follow either a curly brace({) a space(\s) or a colon(:) while the last matching quote will come before either a comma(,) or a closing curly brace(}) then we can consider everything in between as part of the same string, like so:</p> <h2>additional quotes in string:</h2> <pre><code>&gt;&gt;&gt; js = "{foo: 'a sentence: it\'s right here!'}" &gt;&gt;&gt; json.loads( ... sub("(?&lt;=\s|{|:)'(.*?)'(?=,|})", ... r'"\1"', ... sub('(?&lt;={|,)\s*(\w+):', r' "\1":', js)) ... ) {u'foo': u"a sentence: it's right here!"} </code></pre> <p>Watch this space as more edge cases are revealed and solved. Can you spot another? </p> <p>Or for something more complex perhaps, a real world example as returned by <code>npm view</code>:</p> <h2>From:</h2> <blockquote class="spoiler"> <p> <pre>{ name: 'chuck', description: 'Chuck Norris joke dispenser.', 'dist-tags': { latest: '0.0.3' }, versions: '0.0.3', maintainers: 'qard ', time: { '0.0.3': '2011-08-19T22:00:54.744Z' }, author: 'Stephen Belanger ', repository: { type: 'git', url: 'git://github.com/qard/chuck.git' }, version: '0.0.3', dependencies: { 'coffee-script': '>= 1.1.1' }, keywords: [ 'chuck', 'norris', 'jokes', 'funny', 'fun' ], bin: { chuck: './bin/chuck' }, main: 'index', engines: { node: '>= 0.4.1 &lt; 0.5.0' }, devDependencies: {}, dist: { shasum: '3af700056794400218f99b7da1170a4343f355ec', tarball: '<a href="http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz" rel="nofollow">http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz</a>' }, scripts: {}, directories: {}, optionalDependencies: {} }</pre></p> </blockquote> <h2>To:</h2> <blockquote class="spoiler"> <p> <pre>{u'author': u'Stephen Belanger ', u'bin': {u'chuck': u'./bin/chuck'}, u'dependencies': {u'coffee-script': u'>= 1.1.1'}, u'description': u'Chuck Norris joke dispenser.', u'devDependencies': {}, u'directories': {}, u'dist': {u'shasum': u'3af700056794400218f99b7da1170a4343f355ec', u'tarball': u'<a href="http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz" rel="nofollow">http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz</a>'}, u'dist-tags': {u'latest': u'0.0.3'}, u'engines': {u'node': u'>= 0.4.1 &lt; 0.5.0'}, u'keywords': [u'chuck', u'norris', u'jokes', u'funny', u'fun'], u'main': u'index', u'maintainers': u'qard ', u'name': u'chuck', u'optionalDependencies': {}, u'repository': {u'type': u'git', u'url': u'git://github.com/qard/chuck.git'}, u'scripts': {}, u'time': {u'0.0.3': u'2011-08-19T22:00:54.744Z'}, u'version': u'0.0.3', u'versions': u'0.0.3'}</pre></p> </blockquote> <p>Works for me =)</p> <p>nJoy!</p>
21,287
<p>I have need to select a number of 'master' rows from a table, also returning for each result a number of detail rows from another table. What is a good way of achieving this without multiple queries (one for the master rows and one per result to get the detail rows).</p> <p>For example, with a database structure like below:</p> <pre><code>MasterTable: - MasterId BIGINT - Name NVARCHAR(100) DetailTable: - DetailId BIGINT - MasterId BIGINT - Amount MONEY </code></pre> <p>How would I most efficiently populate the <code>data</code> object below?</p> <pre><code>IList&lt;MasterDetail&gt; data; public class Master { private readonly List&lt;Detail&gt; _details = new List&lt;Detail&gt;(); public long MasterId { get; set; } public string Name { get; set; } public IList&lt;Detail&gt; Details { get { return _details; } } } public class Detail { public long DetailId { get; set; } public decimal Amount { get; set; } } </code></pre>
<p>Normally, I'd go for the two grids approach - however, you might also want to look at FOR XML - it is fairly easy (in SQL Server 2005 and above) to shape the parent/child data as xml, and load it from there.</p> <pre><code>SELECT parent.*, (SELECT * FROM child WHERE child.parentid = parent.id FOR XML PATH('child'), TYPE) FROM parent FOR XML PATH('parent') </code></pre> <p>Also - LINQ-to-SQL supports this type of model, but you need to tell it which data you want ahead of time. Via <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx" rel="nofollow noreferrer">DataLoadOptions.LoadWith</a>:</p> <pre><code>// sample from MSDN Northwnd db = new Northwnd(@"c:\northwnd.mdf"); DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith&lt;Customer&gt;(c =&gt; c.Orders); db.LoadOptions = dlo; var londonCustomers = from cust in db.Customers where cust.City == "London" select cust; foreach (var custObj in londonCustomers) { Console.WriteLine(custObj.CustomerID); } </code></pre> <p>If you don't use <code>LoadWith</code>, you will get n+1 queries - one master, and one child list per master row.</p>
<p>select &lt; columns > from master</p> <p>select &lt; columns > from master M join Child C on M.Id = C.MasterID</p>
40,936
<p>I have a class declared as follows:</p> <pre><code>Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T) </code></pre> <p>I have classes that inherit this class.</p> <p>I have another class that I must pass instances in this method:</p> <pre><code>Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T)) </code></pre> <p>I need to store the passed in object in a global variable, but i can't simply declare it:</p> <pre><code>Private _Container as Collection(Of BaseClass) </code></pre> <p>What is the syntax to declare this object?</p>
<p>Sorry haven't got time to expand on this right now, but I think <a href="http://rasor.wordpress.com/2008/08/19/cast-a-generic-list-c/" rel="nofollow noreferrer">this link</a> describes your underlying problem and a solution.</p> <p>(You might also find <a href="http://blogs.msdn.com/lucian/archive/2008/10/02/co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx" rel="nofollow noreferrer">this</a> interesting.)</p>
<p>It cannot be a global variable. Container is an idea, not a thing.</p> <p>As you have it designed, that idea is only formed into an actual thing inside LoadCollection(). You need to convey the information outside of that method.</p>
16,312
<p>This question deals with concurrency issues, for suggestions on how to display a busy icon see this question: <a href="https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click">Javascript - loading/busy indicator or transparent div over page on event click</a></p> <p>When a user initiates an AJAX request on a page it's useful to show some kind of "working" or busy icon or progress indicator. If there is only one long-running process this can be handled in a relatively straightforward way:</p> <pre><code>function do_action() { show_busy_icon(); long_running_asynchronous_process(function() { // Callback function run when process finishes hide_busy_icon(); }); } </code></pre> <p>However, if multiple asynchronous processes are running on the page, using on/off methods wouldn't work. The first process to finish switches off the icon even though there are additional processes running.</p> <p>So, <strong>how do you handle displaying an indicator, on a web page, that is on when there are one or more processes running, and off when there are no processes running?</strong></p> <p>I imagine it would be possible to maintain a count of the number of processes running. <code>hide_busy_icon()</code> only hides the icon if the process count is 0. That seems kinda prone to failure. Perhaps there's a better/simpler way that I'm not seeing.</p> <p>Thanks for your ideas and suggestions!</p> <p>Edit: After working with the solution in the marked answer for a while, I'm happy to say it works very well. The only issue I've run into are cases where my own scripts call functions of scripts I don't control. Unless those functions allow callbacks to be supplied there's no way to update the process-count when they begin and end.</p> <p>An example of where this can occurs is adding a set of markers to a Google map. Once my script calls the Google maps function the busy icon disappears, while the markers are still being loaded.</p> <p>I'm not sure of a good way to handle this. </p>
<p>If you want the same busy indicator for all actions, then use a counter.</p> <p>Instead of "show_busy_icon()", do a "increment_busy_count()", which calls "show_busy_icon()" if busy count goes from 0 to 1. Instead of "hide_busy_icon()", do a "decrement_busy_count()", which calls "hide_busy_icon()" if busy count goes from 1 to 0.</p>
<p>Please see my answer here: </p> <p><a href="https://stackoverflow.com/questions/244183/how-to-display-a-loading-screen-while-site-content-loads#244190">How to display a loading screen while site content loads</a></p> <p>I give a small, working JavaScript example of how to do exactly this, hope it helps.</p>
46,079
<p>Is there a way to get a detailed failure information from <code>QObjet::connect</code> in case of its failure?</p> <p>Returned boolean value doesn't give any information about reason of failure.</p> <p>I wish exception were so widely used in C++ as they are in Java.</p>
<p>In addition to the other answers, you can install your own function that is called for Qt debug, warning, or fatal messages. Our program has this, and for debug builds, we pop up a dialog detailing the problem if it is a warning or fatal message. I believe most of the missed slot connections appear as warning messages, which details what it is trying to connect. Many times, I look at what it shows and it is a bit different than what I thought I was connecting.</p>
<p>If I remember correctly, the debug build will output a more detailled error message to the debugger. Helped me more than once to fix a bug.</p>
21,440
<p>I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:</p> <pre><code>bool isNull = (i == null); </code></pre> <p>or</p> <pre><code>bool isNull = !i.HasValue; </code></pre> <p>Also when assigning to a non-null type is this:</p> <pre><code>long? i = 1; long j = (long)i; </code></pre> <p>better than:</p> <pre><code>long? i = 1; long j = i.Value; </code></pre>
<p>Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay.</p> <p>What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience.</p> <p>Note that in terms of performance, both forms compile down to the same IL, ie:</p> <pre><code>int? i = 1; bool isINull = i == null; int j = (int)i; </code></pre> <p>Ends up like this after the C# compiler has got to it:</p> <pre><code>int? i = 1; bool isINull = !i.HasValue; int j = i.Value; </code></pre>
<p>They're both the same, but I would use the former version on both, since it's more common in the language: comparison to null and casting to a type.</p>
32,419
<p>My co-founder is currently asking on our blog for an embeddable code widget.</p> <p><a href="http://devver.net/blog/2008/10/someone-please-build-an-awesome-embeddable-code-widget/" rel="nofollow noreferrer">http://devver.net/blog/2008/10/someone-please-build-an-awesome-embeddable-code-widget/</a></p> <p>Basically we want something like <a href="http://pastie.org/" rel="nofollow noreferrer">http://pastie.org/</a> or <a href="http://codepad.org/" rel="nofollow noreferrer">http://codepad.org/</a> but we really want to embed the code section in our blog. We know there are plugins for common blogs and server side solutions, but it would be great to be able to just embed a little javascript and have nicely formatted code anywhere...</p> <p>Does something like this exist? Have we just missed it?</p>
<p>I think you want a javascript syntax highlighter</p> <ul> <li><p><a href="http://code.google.com/p/syntaxhighlighter/" rel="nofollow noreferrer">http://code.google.com/p/syntaxhighlighter/</a></p></li> <li><p><a href="http://shjs.sourceforge.net/" rel="nofollow noreferrer">http://shjs.sourceforge.net/</a></p></li> <li><p><a href="http://www.google.com/search?q=javascript+syntax+highlighter" rel="nofollow noreferrer">http://www.google.com/search?q=javascript+syntax+highlighter</a></p></li> </ul> <p>Sometimes you just keep thinking in the wrong keywords ;-)</p>
<p>Check out <a href="http://coderay.rubychan.de/" rel="nofollow noreferrer">CodeRay</a> and <a href="http://ultraviolet.rubyforge.org/" rel="nofollow noreferrer">UltraViolet</a>. They're both quite good and easy to use.</p>
31,286
<p>I'm writing code to generate character-based pagination. I have articles in my site that I want to split up based on length.</p> <p>The code I have so far is working albeit two issues:</p> <ol> <li>It's splitting pages in the middle of words and HTML tags; I want it to only split after a complete word, tag, or a punctuation mark. </li> <li>In the pagination bar, it's generating the wrong number of pages.</li> </ol> <p>In the pagination bar, it's generating the wrong number of pages.</p> <p>Need help addressing these two issues. Code follows:</p> <pre><code>$text = file_get_contents($View); $ArticleLength = strlen($text); $CharsPerPage = 5000; $NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage); $CurrentPage = $this-&gt;ReturnNeededObject('pagenumber'); $Page = (isset($CurrentPage) &amp;&amp; '' !== $CurrentPage) ? $CurrentPage : '1'; $PageText = substr($text, $CharsPerPage*($Page-1), $CharsPerPage); echo $PageText, '&lt;p&gt;'; for ($i=1; $i&lt;$NoOfPages+1; $i++) { if ($i == $CurrentPage) { echo '&lt;strong&gt;', $i, '&lt;/strong&gt;'; } else { echo '&lt;a href="', $i, '"&gt;', $i, '&lt;/a&gt;'; } echo ' | '; } echo '&lt;/p&gt;'; </code></pre> <p>What am I doing wrong?</p>
<p>Thanks, guys. I put in the fix for the 1st point and it worked beautifully.</p> <p>Hm. I guess it is messy to do the second point. I've found some regex on-line. Will think, write, and get back to you when I make some progress.</p> <p>Thanks again.</p>
<pre><code>$NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage); </code></pre> <p>That should use ceil instead of round - if you use round, 4.2 pages will only show 1-4 - you need a 5th page to show the last .2 of a page.</p> <p>The other part is harder ... its common to use some sort of marker in the file to indicate where the page breaks go as no matter how clever your code, it can't appreciate where is a good break in then same way a human can.</p> <p>If you insist on doing it suggest some logic that first works forwards/backwards to the nearest space when a page break is created, which isn't too tricky. More tricky is deciding when you are within a tag or not .... think you'll either need some fairly heavy regex, or else an HTML parsing tool.</p>
46,824
<p>I have data from a table in a database (string) that contain text and price. I extract the price from the data but my problem is that sometime I can Convert it to float and sometime not.</p> <p>I have noticed that :</p> <pre><code>Convert.ToSingle(m.Groups[1].Value); </code></pre> <p>It works but not always because sometime the period is the problem (it requires a comma). What can I do? I have try to replace the ".", by "," but sometime on other PC it's a period that it's required!</p>
<p>You have this problem because the conversion check the language of your PC. You will need to do something like :</p> <pre><code>Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat); </code></pre> <p>This ways, it won't check the language of the PC. You can find more information about <a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx" rel="noreferrer">InvariantCulture</a> from MSDN. I have something similar in a project and my conversion works.</p>
<p>As others have said:</p> <pre><code>Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture); </code></pre> <p>You must also make sure that you use the <code>InvariantCulture</code> when <strong>writing</strong> to the database. (It would be even better if you saved the data to a column with its native data type, but I digress...)</p>
46,860
<p>Unlike many of the ASP.NET documentation and examples, I'm doing a gridview list on one page, and it links to a 2nd page to do the edit/update view, sending the ID for the record in the GET string.</p> <p>On my edit/update view, I'm using an ASP:DetailsView for viewing, editing and inserting records. All of this works fine. </p> <p>On the <code>detailsView</code> page, I have it autogenerating a <code>new record</code> link that uses postback to show the blank insert form to be filled out.</p> <p>The only problem is, I have no idea how to link to the <code>insert</code> view of the <code>DetailsView</code> from an external page. Am I missing something?</p>
<p>I could have misunderstood your question but.... </p> <p>I don't believe you can 'link to the insert view', but what you can do is programmatically change the mode of the DetailsView once the page has loaded. Remember to check that the passed in ID has a value first.</p> <p>For example: </p> <pre><code>If Not idValue Is Nothing Then yourDetailsViewName.ChangeMode(DetailsViewMode.Insert) End If </code></pre> <p>Check out the MSDN page for more info:<br> <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.changemode.aspx" rel="nofollow noreferrer">DetailsView.ChangeMode Method </a></p>
<p>I just wanted to follow up and say that, even though I did not find a way to link to a specific page state, I did discover the dataview's DefaultMode parameter, that at least allows you to pick an initial state.</p> <p>Thus: DefaultMode="Insert"</p> <p>At least lets you choose insert mode as the default.</p>
46,138
<p>I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:</p> <pre> wordone wordtwo wordthree </pre> <p>become</p> <pre> able:"wordone" able:"wordtwo" able:"wordthree" </pre> <p>How can I do this?</p>
<p>Assuming alphanumeric words, you can use:</p> <pre><code>Search = ^([A-Za-z0-9]+)$ Replace = able:"\1" </code></pre> <p>Or, if you just want to highlight the lines and use "Replace All" &amp; "In Selection" (with the same replace):</p> <pre><code>Search = ^(.+)$ </code></pre> <p><code>^</code> points to the start of the line.<br> <code>$</code> points to the end of the line.</p> <p><code>\1</code> will be the source match within the parentheses.</p>
<p>In visual studio code i found that simple regex as ^ worked.</p>
35,964
<p>Assuming a Cartesian printer with a belt and smooth rod design in which one axis moves another (i.e. the X-axis rails 'sit' on the Y-axis rails), what are the main considerations in sizing the rods and belts? For example, given a base design using 8 mm diameter rods and 6 mm belts (assume these are the limiting factors of the printer and that the frame, etc. can handle whatever you throw at it), what is roughly the maximum load, print speed and build size that this should be expected to support? If you were to increase the rod diameters to 10 mm or even 12 mm on one or both axes (assume the steppers could handle the increased load), what would the increased rigidity buy you in terms of maximum speed and/or build size and would 6 mm belts still be appropriate? Ballpark calculations or rules of thumb are fine as I understand the variables are likely not trivial and am looking more for a rough range of guidance to understand the trade-offs involved.</p>
<p>8 mm rods and 6 mm GT2 belts are generally accepted as a good tradeoff between price and performance, an exact calculation is possible but might not be very relevant if another part is flexing. Also, generally speaking, the smaller the part the sooner it will wear out of specification. Thus your service interval might be higher compared to an over-engineered printer.</p> <p>In short, it depends on what your goal is, if you desire low maintenance and accurate machine, you might be better off with heavier gauge parts. Obviously, this will also affect the speed of printing. A 6 mm GT2 belt might have a higher stretch factor compared to a 10 mm belt, but can be mitigated by adjusting the acceleration. In addition, a 10 mm belt has a larger pulley reducing the number of steps per mm, lowering precision. As such you might be better of using two 6 mm belts.</p> <p>Increased rod size for the print bed will not affect printing speed much but might help with accuracy since the bending modulus is lower. Play around with the calculators below to get an idea of the force your beam will have to withstand. That said, there are a lot of other factors that will flex under load, for example, the bed leveling springs. You can replace them with solid spacers, but that might warp the bed when it heats up.</p> <p><a href="https://www.engineering.com/calculators/beams.htm" rel="nofollow noreferrer">https://www.engineering.com/calculators/beams.htm</a></p> <p><a href="https://www.omnicalculator.com/physics/acceleration" rel="nofollow noreferrer">https://www.omnicalculator.com/physics/acceleration</a></p> <p>To conclude, I would use the calculators to figure out if the 8 mm rods are within tolerance for the intended speeds and load, but don't forget to look at the overall picture. The quality of parts you choose is one such thing.</p>
<p>The 3D printing revolution started out with the idea/community project to build self-replicating machines:</p> <blockquote> <p>RepRap was the first of the low-cost 3D printers, and the RepRap Project started the open-source 3D printer revolution. It has become the most widely-used 3D printer among the global members of the Maker Community. <em>(From RepRap.org)</em></p> </blockquote> <p>The main aspects for this project was to build self-replicating machines from cheap and &quot;simple&quot; available materials and making them freely available for the benefit of everyone. The rod solution is a simple and affordable solution for linear motion with fair tolerances.</p> <p>As far as the rigidity of the X carriage, rods aren't the best solution, increasing rod diameter will surely increase the stiffness, but it will be smaller than a design that uses a (quality) linear rail, these are much stiffer. Note that instead of steel, carbon rods can be used, these are stiff and light and reduce the weight of the carriage, allowing for higher acceleration and speed. The solution of using rods is mainly based on availability and being a cheap solution.</p> <p>Do note that rods flex much more than linear rails, even when you increase the diameter, this will limit the length of the X-axis.</p> <p><a href="https://m.all3dp.com/2/linear-rail-3d-printer-really-better-or-just-a-hype/" rel="nofollow noreferrer">From all3Dp</a>:</p> <blockquote> <p>Any decent rail will have far less give. In terms of 3D printing, this leads to greatly reduced backlash and ringing artifacts, yielding cleaner print surfaces and edges.</p> </blockquote> <p>Belts allow the rotational motion to be transferred into a linear motion. Belt width depends on the force (carriage weight) you need to move. Same as for rods, an increased height will allow for a larger load to be driven/moved, but for a fixed load, the increasing height allows for less stretch and thus less printing defects. Note the different <a href="https://3dprinting.stackexchange.com/a/6714">types of belts</a> are available, all having their own stiffness and load bearing capacity.</p>
1,771
<p>I have a VB6 class with a method which raises an error:</p> <pre><code>Public Sub DoSomething ... err.Raise 12345, description:="Error message" ... End Sub </code></pre> <p>This method is called from a form:</p> <pre><code>Public Sub ErrTest() On Error Goto err1 obj.DoSomething Exit Sub err1: MsgBox err.Description End Sub </code></pre> <p>This works fine at runtime, but at design time the error handling does not work. Instead the VB6 IDE displays its standard message box from where I can go into debug mode or end the program.</p> <p>Why does this happen? Can I prevent it?</p>
<p>In the VB IDE, go to Tools, Option, General tab, Error trapping frame. I'm guessing you have it set to 'Break on All Errors', whereas you probably want 'Break on Unhandled Errors'.</p> <p>Your <code>Err.Raise</code> statement gives a compile error for me; try removing the braces.</p> <p>Also, you may want to use </p> <pre><code>Err.Raise vbObjectError + 12345, Description:="Error message" </code></pre> <p>i.e. offset your error code from the VB constant vbObjectError to be sure you don't get clashes.</p>
<p>You can also change the error trapping options by right-clicking in the code window. The following options are available from the "Toggle" sub-menu:</p> <p>Break on All Errors<br/> Break in Class Module<br/> Break on Unhandled Errors</p> <p>I find this much easier than popping up the Options dialog...</p>
43,670
<p>How should I load files into my Java application?</p>
<p><strong>The short answer</strong></p> <p>Use one of these two methods:</p> <ul> <li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)" rel="noreferrer"><code>Class.getResource(String)</code></a></li> <li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)" rel="noreferrer"><code>Class.getResourceAsStream(String)</code></a></li> </ul> <p>For example:</p> <pre><code>InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg"); </code></pre> <p>--</p> <p><strong>The long answer</strong></p> <p>Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:</p> <pre><code>File file = new File("C:\\Users\\Joe\\image.jpg"); </code></pre> <p>This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.</p> <p>Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).</p> <p>Instead, use the <code>getResource()</code> methods in the <code>Class</code> class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.</p>
<pre><code>public static String loadTextFile(File f) { try { BufferedReader r = new BufferedReader(new FileReader(f)); StringWriter w = new StringWriter(); try { String line = reader.readLine(); while (null != line) { w.append(line).append("\n"); line = r.readLine(); } return w.toString(); } finally { r.close(); w.close(); } } catch (Exception ex) { ex.printStackTrace(); return ""; } } </code></pre>
2,837
<p>Does anyone have a copy of MSIINV.EXE (The MSI Inventory tool)? The site where it used to be available is down(<a href="http://www.huydao.net/" rel="nofollow noreferrer">http://www.huydao.net/</a>). I'm trying to uninstall some components in order to force the Visual Studio Setup to reinstall them. I apologize as this is not strictly a programming question but I figured anyone that has installed some of the Visual Studio beta stuff may have run into this problem as well.</p>
<p>I've created a GitHub repository with both the original source and a copy of the .exe for MsiInv.exe. I am the original author.</p> <p><a href="https://github.com/ZisBoom/MsiInv.exe" rel="noreferrer">https://github.com/ZisBoom/MsiInv.exe</a></p> <p>My most common usage is <code>msiinv.exe -p</code> to list all installed products, or <code>msiinv.exe -p | findstr /i &lt;pattern&gt;</code> to find a specific product. <code>msiinv.exe -p &lt;leading match&gt;</code> requires you to know the "startswith" name of the product, whereas findstr is useful for substring.</p> <p>Command line options:</p> <pre><code>msiinv.exe -? Usage: msiinv.exe [option [option]] -p [product] Product list -f Feature state by product. (includes -p) -q Component count by product (includes -p) -# Component count and features states by product (-p -f -q) -x Orphaned components. -m Shared components. -c Evaluate components (-x -m). -l List of log files. -t Elapsed time for run. (Benchmarking) -s Reduced output.(-p -#) -n Normal output. (default) -v Verbose output. (default + feature and component lists) </code></pre>
<p>The tool msiinv.exe what it really does is just list the GUI of all your installed MSI packages. You can use a file as an output.</p> <p>Then the MSI Inventory tool will provide the needed GUI in order to run "msiexec.exe /x {B3A02601-8FE9-4108-8E95-D94171A2F8C8}" and uninstall the desired package.</p> <p>Thanks.</p> <p>Faith.</p>
29,601
<p>So I'm writing a page which does some reporting and it's pretty dynamic, the user has the ability to group data and sort columns. I've been able to get my dynamic grouping down and then the sorting except now my generated linq-to-sql sql order by statement is backwards from what I want it to be. I think I need to figure out how to get at the Result returned from the LinqDataSource when the Sorting event is fired in the ListView so that I can then append my grouping order by clauses.</p> <p>Currently I'm overriding the LinqDataSource selecting event to provide it's result and do the dynamic grouping there, but then the Result is modified by the Sort on the listview and I was thinking there must be some way to get at that result during the Sorting or Sorted event.</p> <p>Any insight would be appreciated, in the meantime I will be attempting to figure this out myself.</p>
<p>I've used the <a href="http://sourceforge.net/project/showfiles.php?group_id=56262&amp;package_id=63621" rel="nofollow noreferrer">PMD NetBeans plugin</a>, and <a href="http://pmd.sourceforge.net/integrations.html#netbeans" rel="nofollow noreferrer">here</a> are the installation instructions (may be a little outdated, due to the speed of NetBeans development, but I got them to work).</p> <p>Here's a list of <a href="http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#Java_2" rel="nofollow noreferrer">tools for static analyisis</a>. Maybe you can cross-check for others that offer NetBeans support.</p> <p><strong>EDIT:</strong> Those instruction are a little bit old, so I put a more up-to-date set <a href="http://www.billthelizard.com/2008/11/netbeans-pmd-plugin.html" rel="nofollow noreferrer">here</a> (links to my blog).</p>
<p>I found the <a href="https://sqe.dev.java.net/" rel="nofollow noreferrer">SQE Plugin</a>, it integrates FindBugs, CheckStyle and PMD into one convenient Plugin. </p> <p>CheckStyle configuration was not complete yet, but the functionality is there in full.</p>
34,296
<p>Using data binding, how do you bind a new object that uses value types? </p> <p>Simple example:</p> <pre><code>public class Person() { private string _firstName; private DateTime _birthdate; private int _favoriteNumber; //Properties } </code></pre> <p>If I create a new Person() and bind it to a form with text boxes. Birth Date displays as 01/01/0001 and Favorite Number as 0. These fields are required, but I would like these boxes to be empty and have the user fill them in.</p> <p>The solution also needs to be able to default fields. In our example, I may want the Favorite Number to default to 42.</p> <p>I'm specifically asking about Silverlight, but I assume WPF and WinForms probably have the same issue.</p> <p><b>EDIT:</b></p> <p>I thought of Nullable types, however we are currently using the same domain objects on client and server and I don't want to have required fields be Nullable. I'm hoping the databinding engine exposes a way to know it is binding a new object?</p>
<p>Perhaps you can try Nullable types?</p> <pre><code>public class Person() { private string? _firstName; private DateTime? _birthdate; private int? _favoriteNumber; //Properties } </code></pre> <p>or </p> <pre><code>public class Person() { private Nullable&lt;string&gt; _firstName; private Nullable&lt;DateTime&gt; _birthdate; private Nullable&lt;int&gt; _favoriteNumber; //Properties } </code></pre> <p>which is actually the same.</p> <p>Now, the default values are null, and you can force the properties to have a value by setting them.</p> <p>More about Nullable types:</p> <p><a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx</a></p>
<p>I'd rewrite the Person class to looks something more like this...</p> <pre><code>public class Person { private int _favoriteNumber = 0; public string FavoriteNumber { get { return _favoriteNumber &gt; 0 ? _favoriteNumber.ToString() : string.Empty; } set { _favoriteNumber = Convert.ToInt32(value); } } private DateTime _birthDate = DateTime.MinValue; private string BirthDate { get { return _birthDate == DateTime.MinValue ? string.Empty : _birthDate.ToString(); //or _birthDate.ToShortDateString() etc etc } set { _birthDate = DateTime.Parse(value); } } } </code></pre>
28,972
<p>I'm looking for a <strong>subversion web client</strong> ala <a href="http://search.cpan.org/dist/SVN-Web/" rel="nofollow noreferrer">SVN::Web</a> but with a very specific feature I've always thought would be quite useful.</p> <p>What I want is the ability to find <strong>which revision was responsible for a certain line</strong> (or lines) in a text file. A way to do this via the web would be fantastic.</p> <p>Anybody know of such a tool?</p>
<p>I use <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a>, you can use <em>svn blame</em> from there, and you see who and when added or modified each line of code in a file...</p> <p><strong>Edit:</strong> Here are a pair of screenshots, so you can get an idea: </p> <p><img src="https://i.stack.imgur.com/eG0ag.jpg" alt="1">, <img src="https://i.stack.imgur.com/9cck2.jpg" alt="2"></p>
<p>I thought that SVN had the 'blame' function that could do something similar to that. I am taking a stab in the dark though. Hold on while I take a quick look through the interwebs.</p> <p>You bet. Check <a href="http://svnbook.red-bean.com/en/1.0/re02.html" rel="nofollow noreferrer">this</a> out. (I use subclipse btw)</p> <p>This implies that most web SVN interfaces will have this feature because it is not anything really special.</p>
23,922
<p>I just purchased an <a href="https://www.anycubic.com/products/anycubic-photon-3d-printer" rel="nofollow noreferrer">Anycubic Photon 3S</a> LCD-based SLA 3D printer. I understand the need for cleaning and curing parts after printing. While the device is in transit, I'm looking to set up a workstation to use it with.</p> <p>Are there any recommendations for accessories to buy?: Particular containers to store materials in, particular products for cleaning prints (or cleaning the machine), particular lamps for curing, etc.</p> <p>I'm trying to avoid gotchas, and I've got time to visit hardware stores or make further online purchases before it arrives. I'm not asking about software or computing hardware, just things that I'll want to have "on the bench".</p>
<h1>Safety Gear</h1> <p>Gloves, you want to wear them whenever handling any resin. Single-use gloves are best - dispose of them after use. Consider them contaminated after touching anything in contact with resin and toss them before handling anything that shall not get in contact with resin. That includes door handles.</p> <p>A good idea is to also wear eye protection, as resin in the eyes could destroy them.</p> <p>While a dust mask might not be strictly necessary, it could reduce your exposure to the fumes of resin. Some resin fumes are known to create hypersensitivity.</p> <p>It is also a good idea to put the printer into a dedicated workspace that is well ventilated and not your primary living space. I strongly recommend reading both <a href="https://3dprinting.stackexchange.com/questions/8594/best-way-to-deal-with-resin-printers-in-your-living-space">Best way to deal with Resin Printers in your living space</a> and <a href="https://3dprinting.stackexchange.com/questions/7305/safe-way-of-disposing-resin/7307#7307">Safe way of disposing resin</a></p> <h1>Post-Processing Station</h1> <p>You may want to build a post-processing station. Most pieces can be sourced in any home depot store or made from household items, so I don't recommend specific brands but the requirements.</p> <h3>Washing Station</h3> <p>A typical post-processing station consists of at least 2 vats large enough to submerge your print volume in, so you can wash off your print in the first and then wash it with fresh liquid in the second. The typical liquids for cleaning are isopropyl alcohol and sometimes technical alcohol. Some resins demand special liquids that are specific to the type of resin. Best, the washing vats have securely sealing lids. Glass is preferably as it is easy to clean.</p> <p>To use the least amount of cleaning liquid, you might want to have a pair of <a href="https://www.google.com/search?q=needle%20spray%20bottle" rel="nofollow noreferrer">needle spray bottles</a> - one for each bath. Label them!</p> <p>To avoid spillage and ruining tables, a plastic table cloth can be a good addition. Fold it with the contaminated side onto itself for storage. A different solution would be to put the cleaning station onto a ceramic or steel surface, which can be easily cleaned after use.</p> <h3>Curing Station/Chamber</h3> <p>The next step is curing the print under direct exposure to a UV light source, somewhat akin to how gel nails are hardened. Sometimes the sun is enough.</p> <p>Since the resin residue from washing is now in the isopropyl alcohol (or other washing liquid), treat it as chemical waste. To reduce the waste of material, flock out the resin in it by exposing the liquid to the UV light and filter the result. The result is Isopropyl Alcohol with some remaining contaminants, which can be used again for the first rinsing step.</p> <h1>Other Tools</h1> <p>Besides cleaning and curing the print, you need to remove the print from the plate, so you need a spatula or scraper, which is reserved only for your SLA printer. Never use it on the build platform of your FDM printers and consider it contaminated with uncured resin after use. Best cure residue on it in the UV chamber and then physically chip off the hardened resin before handling it without gloves again.</p> <p>Similarly, a tool to stir the resin and remove flakes is often used, and some makers have special spatulas to clean the vat. Clean them well after use.</p> <p>You will want to have some nice snippets to remove the support structures at some spots and some pliers to break them free - safety first.</p> <p>Needle files and sanding paper for cleanup where the support stuck are a given.</p> <h1>Resin Recovery</h1> <p>Since the resin in the trays might harden over time, you'll want to have some sort of rig to hold the vat at a tilted angle upside down so it can flow out, back into the resin bottle. A cover might also help to reduce exposure and allow short time storage in the machine. <a href="https://www.thingiverse.com/search?q=resin%20vat&amp;dwh=475d8d188363603" rel="nofollow noreferrer">Thingieverse has a couple of solutions</a> for lids, pouring and filtering stations as well as other accessories. Look for those that fit your printer.</p> <p>The Resin should be stored in airtight and light-blocking bottles. As an extra security measure, you should store the resin in a closed cupboard to prevent light exposure through not totally opaque bottles.</p> <p>More on Re-using resin can be found <a href="https://3dprinting.stackexchange.com/questions/14497/left-over-photopolymer-resins/14500#14500">here</a></p> <h2>Further Reading/watching</h2> <ul> <li><a href="https://www.youtube.com/watch?v=7kHcsTG9QsM" rel="nofollow noreferrer">Angus/Makers Muse on 3D printing safety</a></li> <li><a href="https://www.wargaming3d.com/2018/12/31/the-complete-and-utter-idiots-guide-to-3d-printing-in-resin-for-wargamers/" rel="nofollow noreferrer">A rather good guide regarding Resin 3D printing</a></li> </ul>
<p>I would recommend a tub for cleaning the print, some funnels to get leftover resin back into the bottel, gloves, since you really don't want to get any uncured resin on your skin and a strong UV light for finishing the curing process after the cleaning</p>
1,474
<p>I am building Windows apps for a few clients. I read Joel on Software and took the Joel Test and realized I don't quite measure up. One place I am lacking is automated builds. What should I use to have automated builds? I have Windows apps that use .NET 1.1, 2.0, and 3.5. Also, I need to be able to build my .vdproj to create MSI's. I am looking for something that is free and would work well for a one-man team.</p>
<p>TeamCity Professional Edition from JetBrains. <a href="http://www.jetbrains.com/teamcity/" rel="noreferrer">http://www.jetbrains.com/teamcity/</a></p>
<p>I've used both CruiseControl and TeamCity extensively. For a one man shop, TeamCity is far easier to setup and configure than CruiseControl. </p> <p>For your build scripts, you can't go wrong with MsBuild or NAnt. I've also been considering Powershell for this but I have not attempted it yet.</p>
28,016
<p>I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.</p>
<p>We are using an action filter for this. </p> <p>...</p> <pre><code> public override void OnActionExecuting(ActionExecutingContext filterContext) { var controller = (Controller) filterContext.Controller; Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText); controller.ViewData.Add(breadcrumbs); } </code></pre> <p>before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options. IBreadcrumbManager looks like this:</p> <pre><code>public interface IBreadcrumbManager { Breadcrumb[] PushBreadcrumb(string linkText); } </code></pre> <p>The implementation puts Breadcrumb objects into the Session. The Url is <code>HttpContext.Current.Request.RawUrl</code></p>
<p>@Chris: something like this:</p> <pre><code> &lt;% foreach (var item in ViewData.Get&lt;Breadcrumb[]&gt;()) { %&gt; &lt;a href="&lt;%= Server.HtmlEncode(item.Url) %&gt;"&gt;&lt;%= item.LinkText %&gt;&lt;/a&gt; &amp;raquo; &lt;% } %&gt; </code></pre>
9,168
<p>In a review for a certain filament I read that somebody recommended &quot;<a href="https://www.amazon.de/gp/customer-reviews/RVMUN4CW9ZLKX/ref=cm_cr_arp_d_rvw_ttl?ie=UTF8&amp;ASIN=B01080YND6" rel="nofollow noreferrer">a feeding rate of 105%</a>&quot;.</p> <p>What does he mean, and how could I set this in Cura?</p> <p>When I search for &quot;<em>feed</em>&quot; in the print settings properties of Cura, nothing is found, so I suspect he means &quot;<em>speed</em>&quot;.</p> <p>When I search for speed, multiple speed settings turn up, not only one.</p> <p>How could I do what he recommended?</p> <p>Thank you!</p> <p><a href="https://i.stack.imgur.com/DoQ2L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DoQ2L.png" alt="enter image description here" /></a></p>
<h2>[Extruder] feed rate [modifier] is used synonymous to extrusion multiplier</h2> <p>The feed rate of the extruder is the rate at which filament is pushed (fed) into the hotend. An overwrite value that modifies that rate from the normal rate is in most slicers called &quot;extrusion multiplier&quot;.</p> <p>It is a <em>quickfix</em> to manipulate print behavior, especially addressing under extrusion due to various problems, such as mis-sized filament or to compensate for deformability of it compared to the filament the extruder is calibrated for.</p> <p>It is however not a permanent fix. See also <a href="https://3dprinting.stackexchange.com/questions/11074/why-and-how-am-i-supposed-to-change-the-extrusion-multiplier?noredirect=1&amp;lq=1">here</a>, <a href="https://3dprinting.stackexchange.com/questions/6968/slicer-line-width-vs-extrusion-multiplier-for-layer-adhesion?noredirect=1&amp;lq=1">here</a> and <a href="https://3dprinting.stackexchange.com/questions/8382/isnt-using-the-extrusion-multiplier-like-cheating/8384#8384">here.</a></p>
<p>In the context of the linked source (in German <em>&quot;Die Feeding Rate sollte mit 105 % eingestellt werden&quot;</em>), with <em>&quot;a feeding rate of 105 %&quot;</em> is meant the extrusion multiplier (there is no reference in the source to Cura). This is explained in <a href="https://3dprinting.stackexchange.com/a/20006">this answer</a>. The answer is correct for the translation, but should have warned for the incorrect wording. Technically, <em>feed rate</em> is <strong>not</strong> a synonym for <em>extrusion multiplier</em>.</p> <p>The source is wrongly using the term <em>&quot;feeding rate&quot;</em>, feeding rate is the rate at which all steppers are scaled, not solely the E (extruder) stepper.</p> <p>In G-code this is found to be the <code>F</code> parameter, e.g. in <code>G1 F1200 X76.468 Y148.947 E0.0264</code> the feed rate of 1200 mm/min is applied on all steppers, in this example X, Y and E. Changing the feed rate changes all speeds for all steppers simultaneously. This is found in G-code <a href="https://marlinfw.org/docs/gcode/M220.html" rel="nofollow noreferrer"><code>M220</code></a>.</p> <p>The extrusion multiplier (or known as <em>&quot;Flow Percentage&quot;</em>) only acts on the E stepper motor, this is not reflected in the G-code, but adjusted in the firmware planner. The G-code to adjust the flow percentage is <a href="https://marlinfw.org/docs/gcode/M221.html" rel="nofollow noreferrer"><code>M221</code></a></p>
2,211
<p>I'd like to use regex with Java.</p> <p>What I want to do is find the first integer in a string.</p> <p>Example:</p> <pre><code>String = "the 14 dogs ate 12 bones" </code></pre> <p>Would return 14.</p> <pre><code>String = "djakld;asjl14ajdka;sdj" </code></pre> <p>Would also return 14.</p> <p>This is what I have so far.</p> <pre><code>Pattern intsOnly = Pattern.compile("\\d*"); Matcher makeMatch = intsOnly.matcher("dadsad14 dssaf jfdkasl;fj"); makeMatch.find(); String inputInt = makeMatch.group(); System.out.println(inputInt); </code></pre> <p>What am I doing wrong?</p>
<p>You're asking for 0 or more digits. You need to ask for 1 or more:</p> <pre><code>"\\d+" </code></pre>
<p>Heres a handy one I made for C# with generics. It will match based on your regular expression and return the types you need:</p> <pre><code>public T[] GetMatches&lt;T&gt;(string Input, string MatchPattern) where T : IConvertible { List&lt;T&gt; MatchedValues = new List&lt;T&gt;(); Regex MatchInt = new Regex(MatchPattern); MatchCollection Matches = MatchInt.Matches(Input); foreach (Match m in Matches) MatchedValues.Add((T)Convert.ChangeType(m.Value, typeof(T))); return MatchedValues.ToArray&lt;T&gt;(); } </code></pre> <p>then if you wanted to grab only the numbers and return them in an string[] array:</p> <pre><code>string Test = "22$data44abc"; string[] Matches = this.GetMatches&lt;string&gt;(Test, "\\d+"); </code></pre> <p>Hopefully this is useful to someone...</p>
48,643
<p>I have some custom SharePoint site definitions that are deployed via SharePoint wsp solution packages. They appear to work fine. I can deploy them fine via the stsadm command line, and my C# code running in some features can also deploy sites based on them. My <code>webtemp.*.xml</code> files appear to be correctly placed in the <code>12\1033\XML</code> folder when my solutions are deployed. My problem is that they just don't show up in the central admin app when I try to <code>Create Site Collection.</code> Why not? I don't even know where to look for this.</p> <hr> <p><strong>EDIT:</strong></p> <p>Hmmm.. About an hour later I happened to go back to the create site collection page and my templates were there. I'm not sure what was up... weird caching somewhere or something. </p> <p>I also should have been more clear that these solution packages had been successfully deployed many times on my dev box, so I didn't expect there to be a problem (with the deployment aspect anyway) on this other server.</p>
<p>Many tasks in SharePoint are queued and then executed via timer job. An IISReset causes the web applicationt to be reloaded into memory and for configuration information for example the web.config to be reloaded. </p> <p>To give SharePoint a "nudge" and cause jobs to execute you might try: </p> <pre><code>stsadm -o execadmsvcjobs </code></pre>
<p>Do you have the publishing feature enabled? I read that content types can't be saved in templates, so they don't allow publishing sites to be made into templates. This is perhaps linked to why they won't show you the ones you already made. </p> <p>Although I don't have access to a central admin to verify, this is the case from within my site collection.</p>
23,458
<p>I'm having trouble deciding if I want a project of mine to be web-based (as in a web-app), desktop-based (a desktop application), or a desktop application that can sync or connect to the cloud.</p> <p>I don't know if anyone else would have an interest in this application, and it's only going to be for me, so I'm leaning toward desktop application. If, for some reason, I finish it, release it, and people actually like it, I might see about making it sync to the cloud as well (think v2). But I'm not sure how hard it is to make such a radical change, and I don't want to end up with something good that is useless because I made a poor choice before I even started the project.</p> <p>Is there any sort of guidance for this? Any rules of thumb or best practices? Any personal experiences?</p> <p>If the language matters, I'm thinking about Java simply because I'm most comfortable with it, and it would easily allow me to share it with my friends for testing and if I get stuck and need help from someone else in person.</p>
<p>I generally ask a few questions:</p> <ul> <li>Can it even be done on the web? Something I did not too long ago involved an image editing component, and had to be a web app. It involved much pain to get this work, and a desktop app would have been a far better way to go.</li> <li>Will I need to access it from anywhere? Yeah you could load it up on a thumb drive, but the web is far more feasible in this case.</li> <li>Will there be multiple users? This could go either way, but "long tail" stuff usually means web.</li> <li>What tech do you want to use? The latest and greatest WPF based UI? Desktop (yeah yeah, silverlight, let's not go there ok?). The brain dead stupid easy user management of Django or others? Web.</li> <li>If it were a web app, will you need to worry about common attack vectors like SQL Injection, XSS, etc? A desktop app has its own issues here too, but tend to have less exposure.</li> <li>How resource intensive is it? Will 10 users kill performance of a web server?</li> <li>Versioning on the desktop can be a pain, whereas with a webapp everyone is on the same version. This can bite you though, see the New Facebook user pushback.</li> </ul> <p>EDIT:</p> <ul> <li>Cost can be a factor too. A web app with a database backend typically means a web server. If you want to stick with, say, the Microsoft Stack, you'll need licenses for SQL Server which can get pricey. Open source is cheaper, but may not be an option in all cases. "Serving" a desktop app is generally cheaper.</li> </ul>
<p>Previously you'd have written a desktop application, as tool were better for that and you'd have written it faster. People used to want web apps, but always ended up with desktop.</p> <p>Nowadays things are different, you can write a webservice just as quickly and easily so there's no reason not to go web-based.</p> <p>The advantages of web-based are flexibility, scalability and ease of deployment. It won't be as responsive as a desktop app could be, but that's not so much of an issue if you think about your design.</p>
19,814
<p>I'm working on a database that tracks files and dependencies in projects. Briefly, I have two main tables; the PROJECTS table lists project names and other properties, the FILES table lists files. Every file entry points to a project as a foreign key set to CASCADE, so if I delete a project record from the database, all the file records disappear as well. So far, so good.</p> <p>Now I have an additional DEPENDENCIES table. Each record in the dependency table is two files, specifying that the first file depends on the second. Again these are foreign keys, the first is set to CASCADE (so if I delete a file entry, this record is deleted), but the second is set to RESTRICT (so I am not allowed to delete a file entry if any other files depend on it). Again, everything seems good.</p> <p>Unfortunately it seems I can no longer delete a project with a single SQL delete statement! The delete tries to cascade-delete the files, but if any of these appear in the DEPENDENCIES table, the RESTRICT foreign key prevents the delete (even though that record in the dependencies table will be removed because the other column is CASCADE). The only workaround I have is to calculate an exact order to delete the files so none of the dependency record constraints are violated, and remove the file records one at a time before attempting to remove the project.</p> <p>Is there any way to set up my database schema so a single SQL delete from the projects table will correctly cascade the other deletes? I'm using Firebird 2.1, but I don't know if that makes any difference - it seems like there ought to be a way to make this work?</p>
<p>You can't control the order of deletion through a cascading foreign key, but you may be able to design a trigger on <code>PROJECTS</code> to delete rows in <code>FILES</code> that belong to this project and are also listed in <code>DEPENDENCIES</code> as dependent on other <code>FILES</code>. Make it a <code>BEFORE DELETE</code> trigger, so it should execute before the cascading effects.</p> <p>Something like this:</p> <pre><code>CREATE TRIGGER Del_Child_Files FOR PROJECTS BEFORE INSERT AS BEGIN FOR SELECT F.FILE_ID FROM FILES F JOIN DEPENDENCIES D ON F.FILE_ID = D.CHILD_ID WHERE F.PROJECT_ID = OLD.PROJECT_ID INTO :file_id DO DELETE FROM FILES WHERE FILE_ID = :file_id; DONE END </code></pre> <p>So when you delete a project, this deletes all the "child" files of a project that are dependent on other files, and this cascades to delete rows in <code>DEPENDENCIES</code> so all the remaining files are free of dependencies. Your deletion of the project can now cascade to delete these files.</p> <p>I haven't tested this and my Firebird syntax may be rusty, but perhaps it'll get you started.</p> <p>Obviously, please test this on a copy of your data, not the live data!</p>
<p>Does the system support deferred constraints, in which the constraint check can be deferred until a commit point?</p> <p>Maybe that's just an Oracle thing though.</p>
46,088
<p>Do you have idea how many sucessful projects used Velocity framework for developing their UI ?.The reason I am asking is Velocity is replaced in most of the cases by JSP tags, but in our product we still use Velocity frmaework.</p>
<p>Usually it's the other way around. People replace JSPs with Velocity. (Because of a better <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow noreferrer">separation of concerns</a>) The list of projects using Velocity is too long to list here. A big site that I know is using velocity is <a href="http://www.joost.com/" rel="nofollow noreferrer">joost.com</a>.</p>
<p>This <a href="http://wiki.apache.org/velocity/PoweredByVelocity" rel="nofollow noreferrer">Powered By Velocity WIKI Page</a> should give you an idea of just a "few" projects that use Velocity in a way or another.</p>
42,161
<p>I am getting the following error in an MS Access ADP when trying to add a record on a form linked to a MS SQL Server 2000 table:</p> <blockquote> <p>Run-time error '31004':</p> <p>The value of an (AutoNumber) field cannot be retrived prior to being saved.</p> <p>Please save the record that contains the (AutoNumber) field prior to performing this action. note: <em>retrieved</em> is actually spelled wrong in the error.</p> </blockquote> <p>Does anyone know what this means?</p> <p>I've done a web search and was only able to find the answer at a certain site that only experts have access to.</p>
<p>First of all, if you are going to look at experts-exchange - do it in FireFox, you'll see the unblocked answers at the bottom of the page.</p> <p>Second, do you have a subform on that form that's using the autonumber/key field on the master form? Do you require the data that's on that subform to be saved (i.e., having its own key) before the main form is saved. You could be into a deadlock of A and B requiring each other to be saved first.</p> <p>Other than that, you must somehow be accessing that autonumber field whenyou are saving it. The best I can suggest is to step through the code line by line.</p>
<p>Are you trying to assign the value of an Identity field to a variable or something else before you have saved the record?</p> <p>For whatever reason, your app is trying to read the value of the identity field before the record has been saved, which is what generates that identity field. In other words, no value exists for the Autonumber field until the row is saved.</p> <p>I think we'd need to see more code or know more about the steps that lead up to this error to resolve it in more detail.</p>
8,452
<p>I'm a PHP developer and I've made something I want to push live.</p> <p>It requires memcache, and I'm expecting a fair amount of traffic, at least at launch, so I'd like it to be fast.</p> <p>I'm really awesome at programming, but when it comes to getting hosting stuff set-up (other than run-of-the-mill shared hosting) I lack experience.</p>
<p><a href="http://joyent.com/accelerator/pricing/" rel="nofollow noreferrer">Joyent</a> might be a good solution for you. Honestly adding memcache to a LAMP stack is ridiculously easy and you should be able to do it with relative ease. Find a good VPS provider (linode and slicehost are so good I'll recommend them without my referral code) and you should be able to just apt-get install memcache.</p> <p>To get a more specific answer though, you really need to quantify how much a 'fair amount of traffic' will be. For some people a hit a second is a massive, for some people 300 h/s is cake.</p> <p>If you need a hand, email me, I'd be happy to help</p>
<p>I'd definitely look into using a linode.</p>
39,643
<p>I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later.</p> <p>The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shuts down and restarts I won't be able to retrieve my password any more. How can I store passwords in a file and retrieve them later?</p> <pre><code>public class EncyptDecrypt { static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider { get { keyProv.Key = new byte[] { /* redacted with prejudice */ }; return keyProv; } } public static string Encrypt(string text, SymmetricAlgorithm key) { if (text.Equals(string.Empty)) return text; // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string // to the stream. StreamWriter sw = new StreamWriter(encStream); // Write the plaintext to the stream. sw.WriteLine(text); // Close the StreamWriter and CryptoStream. sw.Close(); encStream.Close(); // Get an array of bytes that represents // the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return System.Convert.ToBase64String(buffer); } // Decrypt the byte array. public static string Decrypt(string cypherText, SymmetricAlgorithm key) { if (cypherText.Equals(string.Empty)) return cypherText; string val; try { // Create a memory stream to the passed buffer. MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText)); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); // Create a StreamReader for reading the stream. StreamReader sr = new StreamReader(encStream); // Read the stream as a string. val = sr.ReadLine(); // Close the streams. sr.Close(); encStream.Close(); ms.Close(); } catch (System.Exception) { return string.Empty; } return val; } } </code></pre>
<p>I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it should no longer differ.</p> <p>Edit: You can do this in your 'keyProvider' by setting the IV property.</p>
<p>According to the docs of CreateEncryptor:</p> <blockquote> <p>If the current IV property is a null reference (Nothing in Visual Basic), the GenerateIV method is called to create a new random IV.</p> </blockquote> <p>This will make the ciphertext different every time.</p> <p>Note: a way around this is discussed <a href="https://stackoverflow.com/questions/65879/should-i-use-an-initialization-vector-iv-along-with-my-encryption#66259">here</a> where I suggest you can prepend the plaintext with a mac ... then the first block of ciphertext is effectively the IV, but it's all repeatable</p>
14,438
<p>I've found an <a href="http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx" rel="noreferrer">article</a> on how to elevate a COM object written in C++ by calling <code>CoCreateInstanceAsAdmin</code>. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the <a href="http://msdn.microsoft.com/en-us/library/bb756990.aspx" rel="noreferrer">admin COM object model</a>.</p> <p>I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the <a href="http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html" rel="noreferrer">post from Daniel Moth</a>, but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it.</p> <p>Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the <code>CoCreateInstanceAsAdmin</code> API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs.</p> <p>Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines:</p> <pre><code>// in a dedicated assembly, marked with the following attributes: [assembly: ComVisible (true)] [assembly: Guid ("....")] public class ElevatedClass { public void X() { /* do something */ } } </code></pre> <p>and then have my main application just instanciate <code>ElevatedClass</code> through the <code>CoCreateInstanceAsAdmin</code> call. But maybe I am just dreaming.</p>
<p>Look at <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433&amp;DisplayLang=en" rel="noreferrer">Windows Vista UAC Demo Sample Code</a></p> <p>(You also need the <a href="http://msdn.microsoft.com/en-us/library/ms756482.aspx" rel="noreferrer">Vista Bridge</a> sample for UnsafeNativeMethods.CoGetObject method)</p> <p>Which gives you C# code that shows a few different ways to elevate, including a COM object</p> <p><em>(Incomplete code sample - grab the files above)</em></p> <pre><code>[return: MarshalAs(UnmanagedType.Interface)] static internal object LaunchElevatedCOMObject(Guid Clsid, Guid InterfaceID) { string CLSID = Clsid.ToString("B"); // B formatting directive: returns {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string monikerName = "Elevation:Administrator!new:" + CLSID; NativeMethods.BIND_OPTS3 bo = new NativeMethods.BIND_OPTS3(); bo.cbStruct = (uint)Marshal.SizeOf(bo); bo.hwnd = IntPtr.Zero; bo.dwClassContext = (int)NativeMethods.CLSCTX.CLSCTX_ALL; object retVal = UnsafeNativeMethods.CoGetObject(monikerName, ref bo, InterfaceID); return (retVal); } </code></pre>
<p>The elements of elevation are processes. So, if I understand your question correctly, and you want a way to elevate a COM object in your process, than the answer is you can't. The entire point of CoCreateInstanceAsAdmin is to NOT run it in your process.</p>
15,461
<p>Can I do it with reflection or something like that?</p>
<p>I have been searching for a while and there seems to be different approaches, here is a summary:</p> <ol> <li><p><strong><a href="https://github.com/ronmamo/reflections" rel="noreferrer">reflections</a></strong> library is pretty popular if u don't mind adding the dependency. It would look like this:</p> <pre><code>Reflections reflections = new Reflections("firstdeveloper.examples.reflections"); Set&lt;Class&lt;? extends Pet&gt;&gt; classes = reflections.getSubTypesOf(Pet.class); </code></pre></li> <li><p><strong>ServiceLoader</strong> (as per erickson answer) and it would look like this:</p> <pre><code>ServiceLoader&lt;Pet&gt; loader = ServiceLoader.load(Pet.class); for (Pet implClass : loader) { System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat } </code></pre> <p>Note that for this to work you need to define <code>Pet</code>as a ServiceProviderInterface (SPI) and declare its implementations. you do that by creating a file in <code>resources/META-INF/services</code> with the name <code>examples.reflections.Pet</code> and declare all implementations of <code>Pet</code> in it </p> <pre><code>examples.reflections.Dog examples.reflections.Cat </code></pre></li> <li><p><strong>package-level annotation</strong>. here is an example:</p> <pre><code>Package[] packages = Package.getPackages(); for (Package p : packages) { MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class); if (annotation != null) { Class&lt;?&gt;[] implementations = annotation.implementationsOfPet(); for (Class&lt;?&gt; impl : implementations) { System.out.println(impl.getSimpleName()); } } } </code></pre> <p>and the annotation definition:</p> <pre><code>@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) public @interface MyPackageAnnotation { Class&lt;?&gt;[] implementationsOfPet() default {}; } </code></pre> <p>and you must declare the package-level annotation in a file named <code>package-info.java</code> inside that package. here are sample contents:</p> <pre><code>@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class}) package examples.reflections; </code></pre> <p>Note that only packages that are known to the ClassLoader at that time will be loaded by a call to <code>Package.getPackages()</code>.</p></li> </ol> <p>In addition, there are other approaches based on URLClassLoader that will always be limited to classes that have been already loaded, Unless you do a directory-based search. </p>
<p>Also, if you are writing an IDE plugin (where what you are trying to do is relatively common), then the IDE typically offers you more efficient ways to access the class hierarchy of the current state of the user code. </p>
45,181
<p>I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function</p> <pre><code>window.clipboardData.getData(&quot;Text&quot;) </code></pre> <p>Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?</p>
<p>Safari supports reading the clipboard during <code>onpaste</code> events:</p> <p><a href="http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/CopyAndPaste.html#//apple_ref/doc/uid/30001234-176911" rel="noreferrer">Information</a></p> <p>You want to do something like:</p> <pre><code>someDomNode.onpaste = function(e) { var paste = e.clipboardData &amp;&amp; e.clipboardData.getData ? e.clipboardData.getData('text/plain') : // Standard window.clipboardData &amp;&amp; window.clipboardData.getData ? window.clipboardData.getData('Text') : // MS false; if(paste) { // ... } }; </code></pre>
<p>I believe people use a hidden Flash element to read the clipboard data from the browsers you mentioned.</p>
28,929
<p>I am looking to automate the conversion of an excel sheet into a pdf document (I do not want to manually print the report generated in excel as a pdf document every morning). For now, I would like to create a button in excel that will run the macro to automatically generate the pdf document, but this button will eventually not be used.</p> <p>Im also new to VB, but have read up on the AcroEXch SDK. Seems like I should be using AcroEXch.PDDoc.Create, but this is not quite right (because I cannot specify an input file to be printed/created as a new pdf document). </p> <p>Any ideas on how I can create a brand new pdf file? Thanks in advance.</p>
<p>I think i found the answer. Here is one solution someone at work suggested (if anyone finds it useful, then great).</p> <p>There is no available method in the AcroEXch class (or set of methods that I know of) to <i>convert</i> a non-pdf file to a pdf file. Instead, you have to use the pdf Distiller to first convert the file to postscript and then you can write to pdf, using the PDFDistiller class. Here's a snippet of the code:</p> <p>'1. open excel being converted to pdf:<br> xlReport.activate xlReport.range("a1").select</p> <p>dim PdfFilePath PdfFilePath = ""</p> <p>dim PsFilePath PsFilePath = ""</p> <p>'2. Print Excel file to postscript file xlBook.activesheet.PrintOut , , 1, , "Adobe PDF on Ne01:" ,TRUE, , PsFilePath</p> <p>Dim oDistiller Set oDistiller = CreateObject("PDFDistiller.PDFDistiller.1")</p> <p>oDistiller.FileToPDF sPsFilePath, sPdfFilePath, ""</p> <p>' Close Excel - do not save. 'COMMENTED OUT BELOW 3 LINES FOR DEBUG xlApp.displayalerts=false xlApp.quit set xlApp=nothing</p>
<p>Have you considered CuteFTP or PDFCreator, both are free. I have sucessfully used PDFCreator with VBA and I have heard that CuteFTP is good.</p>
27,060
<p>I'm looking for a variation on the <code>#save</code> method that will only save attributes that do not have errors attached to them. So a model can be updated without being valid overall, and this will still prevent saving invalid data to the database.</p> <p>By "valid attributes", I mean those attributes that give nil when calling @model_instance.errors.on(:attribute)</p> <p>Anyone have an idea of how to accomplish this?</p> <p>So far, I have the following:</p> <pre><code>def save_valid_attributes valid? update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m} end </code></pre> <p>This works if there's no processing done on assignment, which in my case there is. For example, I have a database column "start_date", and two methods defined:</p> <pre><code>def nice_start_date=(startdate) self.start_date = Chronic.parse(startdate) || startdate end def nice_start_date self.start_date.to_s end </code></pre> <p>These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:</p> <pre><code>def save_valid_attributes(attrib) valid? attrib.each{|(k,v)| send("${k}=", v); save; reload) end </code></pre> <p>The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.</p> <p>Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge.</p>
<p>Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.</p> <p>(Maybe you can even link the native code straight into your .NET executable? Not sure about that.)</p>
<p>Take a look at BouncyCastle <a href="http://www.bouncycastle.org/csharp/" rel="nofollow noreferrer">http://www.bouncycastle.org/csharp/</a></p>
10,528
<p>I have been working with T-SQL in MS SQL for some time now and somehow whenever I have to insert data into a table I tend to use syntax:</p> <pre><code>INSERT INTO myTable &lt;something here&gt; </code></pre> <p>I understand that keyword <code>INTO</code> is optional here and I do not have to use it but somehow it grew into habit in my case.</p> <p>My question is: </p> <ul> <li>Are there any implications of using <code>INSERT</code> syntax versus <code>INSERT INTO</code>?</li> <li>Which one complies fully with the standard?</li> <li>Are they both valid in other implementations of SQL standard?</li> </ul>
<p><code>INSERT INTO</code> is the standard. Even though <code>INTO</code> is optional in most implementations, it's required in a few, so it's a good idea to include it to ensure that your code is portable.</p> <p>You can find links to several versions of the SQL standard <a href="http://en.wikipedia.org/wiki/SQL#Standardization" rel="noreferrer">here</a>. I found an HTML version of an older standard <a href="http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt" rel="noreferrer">here</a>.</p>
<p>I prefer using it. It maintains the same syntax delineation feel and readability as other parts of the SQL language, like <code>group BY</code>, <code>order BY</code>.</p>
28,957
<p>I'm new to PHP and I'm trying to do something that may be bad practise and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do.</p> <p>I have one webpage with a form that collects data. That is submited to a PHP script that does a bunch of processing - but doesn't actually display anything important. What I want is that once the processing is done, the script then tells the browser to open another page, where the results are displayed. </p> <p>I know I can use <em>header('Location: page.php');</em> but I can't work out how to provide POST data with this. How can I do that? Alternatively, is there another way to tell the browser to open another page?</p> <p>EDIT: What I'm taking from the responses is that it's <em>possible</em> to do this using various hacks but I'd be better off to just have the processing and the display code in one file. I'm happy with that; this was an experiment more than anything.</p>
<p>You could store that data in the session e.g. in the first file that handles the post</p> <pre><code>session_start(); $_SESSION['formdata'] = $_POST; //or whatever </code></pre> <p>then you can read it on the next page like</p> <pre><code>session_start(); print_r($_SESSION['formdata']); </code></pre> <p>or you could pass it through GET: (but as per comments this is a bad idea)</p> <pre><code>header('Location: page.php?' . http_build_query($_POST)); </code></pre> <p>If you do that make sure you do additional processing/validation on page.php as a malicious user could change the variables. also you may not need the whole post transmitted to the next page</p> <p><strong>Edit</strong></p> <p>I should make clear that I think the second option is possibly worse, as you are limited by the size of data you can send through get and it is possibly less secure as users can more obviously manipulate the data. </p>
<p>I hope i got your qestion right. You might try this:</p> <ol> <li>Adjust your form to look like this:</li> </ol> <p> form method="POST" action="process_data.php" </p> <p>2. Then you create the file process_data.php, wich surprisingly processes the data.<br> And in this file you use header:<br> For example:<br></p> <p> $head = sprintf("page.php?data1=%d?data2=%d",$data1,$data2);<br> header($head); </p> <p>I hope i could help.</p>
40,110
<p>One of my goals is to be able to deploy a new version of a web application that runs side by side the old version. The catch is that everything shares a database. A database that in the new version tends to include significant refactoring to database tables. I would like to be rollout the new version of the application to users over time and to be able to switch them back to the old version if I need to. </p> <p>Oren had a good <a href="http://ayende.com/Blog/archive/2007/11/24/A-vision-of-enterprise-platform-Hot-amp-Distributed-Deployment.aspx" rel="nofollow noreferrer" title="A vision of enterprise platform: Hot &amp; Distributed Deployment">post</a> setting up the issue, but it ended with:</p> <p>"We are still in somewhat muddy water with regards to deploying to production with regards to changes that affects the entire system, to wit, breaking database changes. I am going to discuss that in the next installment, this one got just a tad out of hand, I am afraid."</p> <p>The follow-on post never came ;-). How would you go about managing the migration of breaking database changes to a database shared by old version of the same application. How would you keep the data synced up?</p>
<p>If the old version has to be maintained, the changes simply can't be breaking. That also helps when deploying a new version of a web app - if you need to roll back, it <em>really</em> helps if you can leave the database as it is.</p> <p>Obviously this comes with significant architectural handicaps, and you will almost certainly end up with a database which shows its lineage, so to speak - but the deployment benefits are usually worth the headaches, in my experience.</p> <p>It helps if you have a solid collection of integration tests for each old version involved . You should be able to run them against your migrated test database for every version which is still deemed to be "possibly live" - which may well be "every version ever" in some cases. If you're able to control deployment reasonably strictly you may get away with only having compatibility for three or four versions - in which case you can plan phasing out obsolete tables/columns etc if there's a real need. Just bear in mind the complexity of such planning against the benefits accrued.</p>
<p>Assuming only 2 versions of your client, I'd only keep one copy of the data in the new tables.</p> <p>You can maintain the contract between the old and new apps behind views on top of the new tables. Use before/instead of triggers to handle writes into the "old" views that actually write into the new tables.</p> <p>You are maintaining 2 versions of code and must still develop your old app but it is unavoidable.</p> <p>This way, there are no synchronisation issues, effectively you'd have to deal with replication conflicts between "old" and "new" schemas.</p> <p>More than 2 versions becomes complicated as mentioned...</p>
32,070
<p>What is the <strong>complete</strong> and correct syntax for the SQL Case expression?</p>
<p>The <strong>complete</strong> syntax depends on the database engine you're working with:</p> <p>For SQL Server:</p> <pre><code>CASE case-expression WHEN when-expression-1 THEN value-1 [ WHEN when-expression-n THEN value-n ... ] [ ELSE else-value ] END </code></pre> <p>or:</p> <pre><code>CASE WHEN boolean-when-expression-1 THEN value-1 [ WHEN boolean-when-expression-n THEN value-n ... ] [ ELSE else-value ] END </code></pre> <p>expressions, etc:</p> <pre><code>case-expression - something that produces a value when-expression-x - something that is compared against the case-expression value-1 - the result of the CASE statement if: the when-expression == case-expression OR the boolean-when-expression == TRUE boolean-when-exp.. - something that produces a TRUE/FALSE answer </code></pre> <p>Link: <a href="http://msdn.microsoft.com/en-us/library/ms181765.aspx" rel="noreferrer">CASE (Transact-SQL)</a></p> <p>Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and <strong>the first one that matches is used</strong>.</p> <p><strong>Note</strong>: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be <em>NULL</em>.</p>
<p>Case statement syntax in SQL SERVER:</p> <pre><code>CASE column WHEN value1 THEN 1 WHEN value3 THEN 2 WHEN value3 THEN 3 WHEN value1 THEN 4 ELSE '' END </code></pre> <p>And we can use like below also:</p> <pre><code>CASE WHEN column=value1 THEN 1 WHEN column=value3 THEN 2 WHEN column=value3 THEN 3 WHEN column=value1 THEN 4 ELSE '' END </code></pre>
2,661
<p>There are a number of other questions related to this topic:</p> <ol> <li><s><a href="https://stackoverflow.com/questions/5214/whats-a-good-standard-code-layout-for-a-php-application">Whats a good standard code layout for a php application</a></s> (deleted)</li> <li><a href="https://stackoverflow.com/questions/7596/how-to-structure-a-java-application-in-other-words-where-do-i-put-my-classes">How to structure a java application, in other words: where do I put my classes?</a></li> <li><a href="https://stackoverflow.com/questions/41513/recommended-source-control-directory-structure">Recommended Source Control Directory Structure?</a> </li> <li><a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">Structure of Projects in Version Control</a></li> </ol> <p>I could not find any specific to VSTF, which has some capabilities like Team Build, integrated Unit Testing, etc. I'm wondering if these capabilities lead to a slightly different source layout recommendation.</p> <p>Please post example of high level directory structures that you have had good luck with an explain why you like them. I'll let people vote on a "best" approach and I'll award the answer in a few days.</p>
<p>Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for.</p> <p><a href="http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html" rel="noreferrer">http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html</a></p> <p>They provide online geocoding (via JavaScript):</p> <p><a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding" rel="noreferrer">http://code.google.com/apis/maps/documentation/services.html#Geocoding</a></p> <p>Or backend geocoding (via an HTTP request):</p> <p><a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct" rel="noreferrer">http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct</a></p> <p>The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality)</p>
<p>The <a href="https://webgis.usc.edu" rel="nofollow noreferrer">USC WebGIS Geocoder</a> is free and offers several API's, or you can upload a database for online batch processing.</p>
12,384
<p>Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.</p> <p>The target language is C++.</p> <p>I am interested in what you have personally used.</p>
<p>I've found the following quite useful:</p> <pre><code>#ifdef PROFILING # define PROFILE_CALL(x) do{ \ const DWORD t1 = timeGetTime(); \ x; \ const DWORD t2 = timeGetTime(); \ std::cout &lt;&lt; "Call to '" &lt;&lt; #x &lt;&lt; "' took " &lt;&lt; (t2 - t1) &lt;&lt; " ms.\n"; \ }while(false) #else # define PROFILE_CALL(x) x #endif </code></pre> <p>Which can be used in the calling function as such:</p> <pre><code>PROFILE_CALL(renderSlow(world)); int r = 0; PROFILE_CALL(r = readPacketSize()); </code></pre>
<p>I would use the 80/20 rule and put timers around hotspots or interesting call paths. You should have a general idea where the bottlenecks will be (or at least a majority of the execution paths) and use the appropriate platform dependent high resolution timer (QueryPerformanceCounters, gettimeofday, etc.).</p> <p>I usually don't bother with anything at startup or shutdown (unless needed) and will have well defined "choke points", usually message passing or some sort of algorithmic calculation. I've generally found that message sinks/srcs (sinks moreso), queues, mutexes, and just plain mess-ups (algorithms, loops) usually account for most of the latency in an execution path.</p>
36,285
<p>Should links on a web page ALWAYS be underlined?<br /> I do not believe this should be a hard and fast RULE!<br /> I wrote a comment on my <a href="http://dotnetbob.blogspot.com/2007/11/links-and-usability.html" rel="nofollow noreferrer">blog</a> awhile back about this after another developer complained that I was not following web standards. It is coming up again, and I want to know what you think. Her argument was that for consistency and usability, ALL links had to be underlined ALL the time. My manager agreed, so I changed two lines in a CSS, and it was done. I did not mind doing the work, but I think the usability of the site is less now. There are way too many things screaming for your attention.<br /><br /> I should mention that this is a web site with many pages of data entry. The links in question were navigation links to the left of the page in a box that was titled "Menu". The underline did appear when you hovered over the link already, and the background colour changed when the user hovered over the link. I really could not believe I was even having the discussion. I was even more shocked when my manager agreed.<br /><br /> Am I wrong? What other arguments should I have made? Thanks! :)</p>
<p>I think all links need to be <em>distinguishable</em> from normal text, but not necessarily underlined. Menus and navigation bars are pretty standard on websites, and are usually recognisable as such, so I think they are being a little too dogmatic.</p>
<p>I agree, I don't think that underline should be used for anything that is not a link.</p> <p>There are certain things that need not be underlined. Page navigation, items in menus, prev/next links, especially if they have arrows are just some examples. I would still suggest that giving them an underline on hover be mandatory.</p>
26,937
<p>Does anyone know of a way to declare a date constant that is compatible with international dates?</p> <p>I've tried:</p> <pre><code>' not international compatible public const ADate as Date = #12/31/04# ' breaking change if you have an optional parameter that defaults to this value ' because it isnt constant. public shared readonly ADate As New Date(12, 31, 04) </code></pre>
<p>If you look at the IL generated by the statement</p> <pre><code>public const ADate as Date = #12/31/04# </code></pre> <p>You'll see this:</p> <pre><code>.field public static initonly valuetype [mscorlib]System.DateTime ADate .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 ) </code></pre> <p>Notice that the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.datetimeconstantattribute.aspx" rel="noreferrer">DateTimeConstantAttribute</a> is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization.</p>
<p>OK, I am unsure what you are trying to do here:</p> <ul> <li>The code you are posting is <strong>NOT</strong> .NET, are you trying to port?</li> <li>DateTime's cannot be declared as constants.</li> <li>DateTime's are a data type, so once init'ed, the format that they were init'ed from is irrelevant.</li> <li>If you need a constant value, then just create a method to always return the same DateTime.</li> </ul> <p>For example:</p> <pre><code>public static DateTime SadDayForAll() { return new DateTime(2001, 09, 11); } </code></pre> <h3>Update</h3> <p>Where the hell are you getting all that from?!</p> <ul> <li>There <strong>are</strong> differences between C# and VB.NET, and this highlights one of them.</li> <li><strong>Date</strong> is not a <a href="http://www.ondotnet.com/pub/a/dotnet/2001/07/30/vb7.html" rel="nofollow noreferrer">.NET data type</a> - <strong>DateTime</strong> is.</li> <li>It looks like you can create DateTime constants in VB.NET but there are limitations</li> <li>The method was there to try and help you, since you cannot create a const from a <strong>variable</strong> (i.e. optional param). That doesn't even make sense.</li> </ul>
8,174
<p>Is there any function that converts an escaped Url string to its unescaped form? <code>System.Web.HttpUtility.UrlDecode()</code> can do that job but I don't want to add a reference to <code>System.Web.dll</code>. Since my app is not a web application, I don't want to add a dependency for only using a function in an assembly.</p> <p><strong>UPDATE:</strong> Check <a href="http://www.west-wind.com/weblog/posts/617930.aspx" rel="noreferrer">Rick Strahl's blog post</a> about the same issue.</p>
<p><strong>EDIT:</strong> Use the static method <strong><code>Uri.UnescapeDataString()</code></strong> to decode your URLs:</p> <p><em>Encoded:</em> <code>http%3a%2f%2fwww.google.com%2fsearch%3fhl%3den%26q%3dsomething%20%2323%26btnG%3dGoogle%2bSearch%26aq%3df%26oq%3d</code></p> <p><em>Decoded:</em> <code>http://www.google.com/search?hl=en&amp;q=something #23&amp;btnG=Google+Search&amp;aq=f&amp;oq=</code></p>
<p><code>System.Net.WebUtility.HtmlDecode</code> is also working on .NET 4.0 Client Profile.</p>
29,647
<p>This is driving me nuts so any advice from fellow users would be welcome. I am using Subversion, with a copy of VisualSVN 1.6.1 installed on a Windows server. On my PC I am using a combination of TortoiseSVN and the wonderful AnkhSVN Visual Studio plugin. Everything works like a dream, but now I am trying use the <code>svn:keywords</code> feature so I can include <code>$Id$</code> at the top of all my source files. Now, for existing files I can edit the SVN properties and add this keyword and it all works fine, but I want this done automatically for new files - and I cannot make it work.</p> <p>According to the documentation you need to edit a special Subversion Config file located in your <code>C:\Documents and Settings\&lt;user&gt;\Application Data\Subversion</code> folder. My PC already had a copy of this file, so I changed it to look like this:</p> <pre><code>[miscellany] enable-auto-props = yes [auto-props] *.cpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.hpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rc = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rc2 = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.cc = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.c = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.h = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.wsf = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.js = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.htm = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.html = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.css = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision </code></pre> <p>I then added a new file to an existing Visual Studio project (from within Visual Studio), added <code>$Id$</code> to the top and committed it - but, alas, the <code>svn:keywords</code> property is not being set.</p> <p>Does anyone know how to get this working? I even tried adding settings to the registry (in <code>HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config</code>) but still no joy. I then tried messing with Config files on the SVN server itself, but nothing seems to work.</p> <p>I have obviously missed something blindingly obvious!</p>
<p>It seems that the answer is just some silly quotes around the actual keywords :)</p> <pre><code>[auto-props] *.cpp = svn:eol-style=native;svn:keywords="Author Date Id HeadURL Revision" </code></pre>
<p>This seems to be an issue with AnkhSVN. I did some tests outside of Visual Studio, using TortoiseSVN to add the files, and it started working (using my user config file). I will try the latest AnkhSVN to see if this makes any difference.</p> <p>I'd prefer to have this done at the server end, but this seems to be user-specific.</p> <p>Either way, thanks for the pointers Len and schnaader.</p>
41,870
<p>Is it possible to do a <code>SELECT</code> statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 <strong>and returning them in that order</strong>, based on nothing more than the ID field?</p> <p>Both these statements return them in the same order: </p> <pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) </code></pre> <pre><code>SELECT id FROM table WHERE id in (8,2,5,9,7) </code></pre>
<p>I didn't think this was possible, but found a <a href="http://www.handgestrickt.biz/item/21/" rel="noreferrer">blog entry here</a> that seems to do the type of thing you're after:</p> <pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) ORDER BY FIND_IN_SET(id,"7,2,5,9,8"); </code></pre> <p>will give different results to</p> <pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) ORDER BY FIND_IN_SET(id,"8,2,5,9,7"); </code></pre> <p><code><a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set" rel="noreferrer">FIND_IN_SET</a></code> returns the position of <code>id</code> in the second argument given to it, so for the first case above, <code>id</code> of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like</p> <pre><code>id | FIND_IN_SET ---|----------- 7 | 1 2 | 2 5 | 3 </code></pre> <p>then orders by the results of <code>FIND_IN_SET</code>.</p>
<p>Best I can think of is adding a second Column orderColumn:</p> <pre><code>7 1 2 2 5 3 9 4 8 5 </code></pre> <p>And then just do a ORDER BY orderColumn</p>
16,266
<p>How do I find out what directory my console app is running in with C#?</p>
<p>To get the directory where the .exe file is:</p> <pre><code>AppDomain.CurrentDomain.BaseDirectory </code></pre> <p>To get the current directory:</p> <pre><code>Environment.CurrentDirectory </code></pre>
<p>Use <code>AppContext.BaseDirectory</code> for .net5.</p>
12,278
<p>In MySQL, If I have a list of date ranges (range-start and range-end). e.g.</p> <pre><code>10/06/1983 to 14/06/1983 15/07/1983 to 16/07/1983 18/07/1983 to 18/07/1983 </code></pre> <p>And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?</p> <p>e.g.</p> <pre><code>06/06/1983 to 18/06/1983 = IN LIST 10/06/1983 to 11/06/1983 = IN LIST 14/07/1983 to 14/07/1983 = NOT IN LIST </code></pre>
<p>This is a classical problem, and it's actually easier if you reverse the logic.</p> <p>Let me give you an example.</p> <p>I'll post one period of time here, and all the different variations of other periods that overlap in some way.</p> <pre class="lang-none prettyprint-override"><code> |-------------------| compare to this one |---------| contained within |----------| contained within, equal start |-----------| contained within, equal end |-------------------| contained within, equal start+end |------------| not fully contained, overlaps start |---------------| not fully contained, overlaps end |-------------------------| overlaps start, bigger |-----------------------| overlaps end, bigger |------------------------------| overlaps entire period </code></pre> <p>on the other hand, let me post all those that doesn't overlap:</p> <pre class="lang-none prettyprint-override"><code> |-------------------| compare to this one |---| ends before |---| starts after </code></pre> <p>So if you simple reduce the comparison to:</p> <pre class="lang-none prettyprint-override"><code>starts after end ends before start </code></pre> <p>then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.</p> <p>For your final NOT IN LIST example, you can see that it matches those two rules.</p> <p>You will need to decide wether the following periods are IN or OUTSIDE your ranges:</p> <pre class="lang-none prettyprint-override"><code> |-------------| |-------| equal end with start of comparison period |-----| equal start with end of comparison period </code></pre> <p>If your table has columns called range_end and range_start, here's some simple SQL to retrieve all the matching rows:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM periods WHERE NOT (range_start &gt; @check_period_end OR range_end &lt; @check_period_start) </code></pre> <p>Note the <em>NOT</em> in there. Since the two simple rules finds all the <em>non-matching</em> rows, a simple NOT will reverse it to say: <em>if it's not one of the non-matching rows, it has to be one of the matching ones</em>.</p> <p>Applying simple reversal logic here to get rid of the NOT and you'll end up with:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM periods WHERE range_start &lt;= @check_period_end AND range_end &gt;= @check_period_start </code></pre>
<pre><code>SELECT * FROM tabla a WHERE ( @Fini &lt;= a.dFechaFin AND @Ffin &gt;= a.dFechaIni ) AND ( (@Fini &gt;= a.dFechaIni AND @Ffin &lt;= a.dFechaFin) OR (@Fini &gt;= a.dFechaIni AND @Ffin &gt;= a.dFechaFin) OR (a.dFechaIni&gt;=@Fini AND a.dFechaFin &lt;=@Ffin) OR (a.dFechaIni&gt;=@Fini AND a.dFechaFin &gt;=@Ffin) ) </code></pre>
17,328
<p>I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have <strong>document1</strong>:</p> <pre><code>&lt;mapping&gt; &lt;key value="assigned"&gt; &lt;a/&gt; &lt;/key&gt; &lt;whatever attribute="x"&gt; &lt;k/&gt; &lt;j/&gt; &lt;/whatever&gt; &lt;/mapping&gt; </code></pre> <p>and <strong>document2</strong>:</p> <pre><code>&lt;mapping&gt; &lt;key value="identity"&gt; &lt;a/&gt; &lt;b/&gt; &lt;/key&gt; &lt;/mapping&gt; </code></pre> <p>I want to merge the two like this:</p> <pre><code>&lt;mapping&gt; &lt;key value="identity"&gt; &lt;a/&gt; &lt;b/&gt; &lt;/key&gt; &lt;whatever attribute="x"&gt; &lt;k/&gt; &lt;j/&gt; &lt;/whatever&gt; &lt;/mapping&gt; </code></pre> <p>I prefer <strong>Java</strong> or <strong>XSLT</strong>-based solutions, <strong>ant</strong> will do fine, but if there's an easy way to do that in <strong>Rake</strong>, <strong>Ruby</strong> or <strong>Python</strong> please don't be shy :-)</p> <p><strong>EDIT:</strong> actually I find I'd rather use an automated tool/script, even <a href="http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes" rel="nofollow noreferrer">writing it by myself</a>, because manually merging some 30 XML files is a bit unwieldy... :-(</p>
<p>If you like XSLT, there's a nice merge script I've used before at: <a href="http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/" rel="nofollow noreferrer">Oliver's XSLT page</a></p>
<p>Unsure as to whether you want to do this programatically or not.</p> <p>Edit: Ah, I posted that before the Edit. Don't I look like an idiot now! ;)</p> <p>If you just want to merge two files together, IBM have an <a href="http://www.alphaworks.ibm.com/tech/xmldiffmerge" rel="nofollow noreferrer">XML Diff and Merge Tool</a>, and there's also Altova's <a href="http://www.altova.com/products/diffdog/diff_merge_tool.html" rel="nofollow noreferrer">DiffDog</a>.</p>
10,607
<p>Recently, someone asked about an <a href="https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c">algorithm for reversing a string in place in C</a>. Most of the proposed solutions had troubles when dealing with non single-byte strings. So, I was wondering what could be a good algorithm for dealing specifically with utf-8 strings.</p> <p>I came up with some code, which I'm posting as an answer, but I'd be glad to see other people's ideas or suggestions. I preferred to use actual code, so I've chosen C#, as it seems to be one of the most popular language in this site, but I don't mind if your code is in another language, as long as it could be reasonably understood by anyone who is familiar with an imperative language. And, as this is intended to see how such an algorithm could be implemented at a low-level (by low-level I just mean dealing with bytes), the idea is to avoid using libraries for the core code.</p> <p><strong>Notes:</strong></p> <p>I'm interested in the algorithm itself, its performance and how could it be optimized (I mean algorithm-level optimization, not replacing i++ with ++i and such; I'm not really interested in actual benchmarks either).</p> <p>I don't mean to actually use it in production code or "reinventing the wheel". This is just out of curiosity and as an exercise.</p> <p>I'm using C# byte arrays so I'm assuming you can get the length of the string without running though the string until you find a NUL. That is, I'm not accounting for the complexity of finding the length of the string. But if you're using C, for instance, you could factor that out by using strlen() before calling the core code. </p> <p><strong>Edit:</strong></p> <p>As Mike F points out, my code (and other people's code posted here) is not dealing with composite characters. Some info about those <a href="http://www.unicode.org/faq/char_combmark.html" rel="nofollow noreferrer">here</a>. I'm not familiar with the concept, but if that means that there are "combining characters", i.e., characters / code points that are only valid in combination with other "base" characters / code points, a look-up table of such characters could be used to preserve the order of the "global" character ("base" + "combining" characters) when reversing.</p>
<p>I'd make one pass reversing the bytes, then a second pass that reverses the bytes in any multibyte characters (which are easily detected in UTF8) back to their correct order.</p> <p>You can definitely handle this in line in a single pass, but I wouldn't bother unless the routine became a bottleneck.</p>
<p>The best solution:</p> <ol> <li>Convert to a wide char string</li> <li>Reverse the new string</li> </ol> <p>Never, never, never, never treat single bytes as characters.</p>
24,291
<p>I'm trying to do a simple erase and keep getting errors.</p> <p>Here is the snippet of code for my erase:</p> <pre><code>std::list&lt;Mine*&gt;::iterator iterMines = mines.begin(); for(int i = oldSizeOfMines; i &gt;0 ; i--, iterMines++) { if(player-&gt;distanceFrom(*iterMines) &lt; radiusOfOnScreen) { onScreen.push_back(*iterMines); iterMines = onScreen.erase(iterMines); iterMines--; } } </code></pre> <p>I keep getting a compiler message:</p> <pre><code>1&gt;c:\users\owner\desktop\bosconian\code\bosconian\environment.cpp(158) : error C2664: 'std::list&lt;_Ty&gt;::_Iterator&lt;_Secure_validation&gt; std::list&lt;_Ty&gt;::erase(std::list&lt;_Ty&gt;::_Iterator&lt;_Secure_validation&gt;)' : cannot convert parameter 1 from 'std::list&lt;_Ty&gt;::_Iterator&lt;_Secure_validation&gt;' to 'std::list&lt;_Ty&gt;::_Iterator&lt;_Secure_validation&gt;' 1&gt; with 1&gt; [ 1&gt; _Ty=SpaceObject *, 1&gt; _Secure_validation=true 1&gt; ] 1&gt; and 1&gt; [ 1&gt; _Ty=Mine *, 1&gt; _Secure_validation=true 1&gt; ] 1&gt; and 1&gt; [ 1&gt; _Ty=SpaceObject *, 1&gt; _Secure_validation=true 1&gt; ] 1&gt; No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called </code></pre> <p>I'm puzzled because I believe I'm giving it the correct iterator.</p> <p>Mine is a subclass of SpaceObject (a second generation subclass that is)</p> <p>Does this have anything to do with it? And how would I fix it?</p>
<p>The problem is you are trying to use the iterator of mines as an iterator in the onScreen list. This will not work. </p> <p>Did you mean to call mines.erase(iterMines) instead of onScreen.erase(iterMines)?</p>
<p>more simple method <a href="http://zhgn.vicp.net/boke/200901071529.htm" rel="nofollow noreferrer">List.erase(p)的用法</a></p>
48,845
<p>Tip me plase, how to insert a null value into table using Trolltech Qt 4.x SQL classes? <code>QSqlQuery</code>, I guess, or something else from QtNetwork. As analog of it, in .NET there is the <code>System.DbNull</code> class, which represents sql NULL.</p> <p>And what type should I use for some object's property, that can hold both null-value and <code>QString</code>? In C# I could use <code>System.Object</code>.</p>
<p>From <code>QSqlQuery::addBindValue</code> documentation:</p> <blockquote> <p>To bind a NULL value, use a null QVariant; for example, use QVariant(QVariant::String) if you are binding a string.</p> </blockquote>
<p>The question is for QT 4, but I think it's worth mentioning that in QT 5 you have only to pass a NULL value.</p>
43,988
<p>I am trying to make a combined image of all images added to a modell in django with inline editing and a ForeignKey. Ive got these models (simplified):</p> <pre><code>class Modell(models.Model): title = models.CharField('beskrivelse', max_length=200) slug = models.SlugField() is_public = models.BooleanField('publisert', default=True) def __unicode__(self): return self.title def save(self, **kwargs): super(Modell, self).save(**kwargs) on_modell_saved(self) class Image(models.Model): modell = models.ForeignKey(Modell, related_name="images") image = ThumbnailImageField('bilde', upload_to=get_upload_path_image) class Meta: verbose_name = 'bilde' verbose_name_plural = 'bilder' def __unicode__(self): return str(self.image) </code></pre> <p>Then i add Image to the Modell with AdminInline, so when i save the Modell i save x number of images.</p> <p>But when I try to do something with Modell.images.all in the on_modell_saved function i cant get hold of the objects. Ive got this function that is executed at Modell.save()</p> <pre><code>def on_modell_saved(instance): for img in instance.images.all(): print img </code></pre> <p>This only prints something the second time i save the Modell and not the first time. So anybody know how to call a function after all items that you are adding with AdminInline is saved?</p>
<p><code>Modell</code> and <code>Image</code> are two seperate models connected with a <code>ForeignKey</code>. Even though they both seem to be saved <em>together</em>, they don't. They are saved one by one (first the <code>Modell</code> or first the <code>Image</code>s).</p> <p>Now logically <code>Image</code>s are saved <strong>after</strong> <code>Modell</code>. Because they have a <code>ForeignKey</code> pointing to <code>Modell</code> and if you try to save them first, because there's no <code>Modell</code> yes, they would point to nothing (which is possible with <code>null=True</code>).</p> <p>So by the time <code>Modell.save()</code> is called <code>Image</code>s don't exist.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/signals/#topics-signals" rel="nofollow noreferrer">Solution</a> depends on what you want to do? I suppose the aim here is not just printing out the <code>Image</code>s.</p>
<p>I dit solve it somehow, but it is farm from optimal, I did the modell_on_save function on Image save, this works, but the bad thing that if there are 5 images related and saved to the modell, there will be 5 calls to the function, and that is bad. I would like it to only happen after the last one...</p>
45,109
<p>I have got a table in MS Access 2007 with 4 fields.</p> <ul> <li>Labour Cost</li> <li>Labour Hours</li> <li>Vat</li> <li>Total</li> </ul> <p>How do I multiply 'Labour Hours' by 'Labour Cost' add the 'VAT' and display the answer in 'Total'</p> <p>Where would I put any formulas?, in a form or query or table ?</p>
<p>There is also the dummies (ie not SQL) way to do it: First delete your total column from your table and for this exercise pretend that the name of your table is "Labour" .</p> <p>Now create a new query and view it in design view, add all the fields from your Labour table (so you can check that everything is working), select an empty field, right click and select "Build" from the drop down list. You should now have an Expression Builder window. </p> <p>Type in the name for your calculated field, e.g. labourTotal, follow it with a colon ":" and then select the field names you want to add from Tables at the bottom left of the Expression Builder window and double-click on each. Each field will appear in the expression builder following the "Total:". Now replace each "«Expr»" with a "+". You should see this in the expression builder: "labourTotal: [Labour]![Labour Cost] + [Labour]![Labour Hours] + [Labour]![Vat] ". Click OK and run the query - if all is well the total column will display the results. </p>
<p>You could put it in as a calculated field, in the query or on the form. Wherever makes sense, is simple and has the right level of re-usability. If the calculation is specific a form or view of the data, do it there or in the query.</p> <p>In this case, you can foresee that the total will be an oft used value and logically applied to the row, so making it a calculated field is appropriate. Calculated fields have the advantage that (in most systems, not sure about MSAccess) they can be set to only re-calculate when the data changes.</p> <p>If you were working out say the ratio of the quantity vs delivery lead time, that would be more something I would put in the query for the specific form/report as it's never going to be re-used and may be a more hefty calculation.</p> <p>I would usually choose to do a calculation in the query, unless it relies on the result of another calculation, then doing it in the query could get kinda messy, so do it in the form/code.</p> <p>So in summary, wherever appropriate for that calc.</p>
38,148
<p>The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?</p> <pre><code>static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){ PyObject *o; //generic object PyObject* pyDB = NULL; //this has to be a py file object if (!PyArg_ParseTuple(args, "O", &amp;pyDB)){ return NULL; } else { Py_INCREF(pyDB); if (!PyFile_Check(pyDB)){ Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle"); return NULL; } } FILE *fhDB = PyFile_AsFile(pyDB); long offset = 0; DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER)); fseek(fhDB,offset,SEEK_SET); //at the beginning fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB ); if (ferror(fhDB)){ fclose(fhDB); Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "failed reading database header"); return NULL; } Py_DECREF(pyDB); PyObject *pyDBHeader = PyDict_New(); Py_INCREF(pyDBHeader); o=PyInt_FromLong(pdbHeader-&gt;version_number); PyDict_SetItemString(pyDBHeader, "version", o); Py_DECREF(o); PyObject *pyTimeList = PyList_New(0); Py_INCREF(pyTimeList); int i; for (i=0; i&lt;NUM_DRAWERS; i++){ //epochs o=PyInt_FromLong(pdbHeader-&gt;last_good_test[i]); PyList_Append(pyTimeList, o); Py_DECREF(o); } PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList); Py_DECREF(pyTimeList); o=PyInt_FromLong(pdbHeader-&gt;temp); PyDict_SetItemString(pyDBHeader, "temp", o); Py_DECREF(o); free(pdbHeader); return (pyDBHeader); } </code></pre> <p>Thanks for taking a look,</p> <p>LarsenMTL</p>
<p><code>PyDict_New()</code> returns a new reference, check the <a href="http://docs.python.org/c-api/dict.html" rel="noreferrer">docs</a> for <code>PyDict</code>. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways.</p> <p>You also don't need to incref <code>pyTimeList</code>. It's yours when you create it. However, you need to decref it, but you only decref it once, so it's leaked as well.</p> <p>You also don't need to call <code>Py_INCREF</code> on <code>pyDB</code>. It's a borrowed reference and it won't go away as long as your function does not return, because it's still referenced in a lower stack frame. </p> <p>Only if you want to keep the reference in another structure somewhere, you need to increse the refcount.</p> <p>Cf. the <a href="http://docs.python.org/c-api/arg.html" rel="noreferrer">API docs</a></p>
<p>I don't know about Python-C. However, My experience with COM reference counting says that a newly created reference-counted object has a reference count of <strong>1</strong>. So your Py_INCREF(pyDB) after PyArg_ParseTuple(args, "O", &amp;pyDB) and PyObject *pyDBHeader = PyDict_New(); are the culprit. Their reference counts are already 2.</p>
45,646
<p>I'm already using <a href="http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/" rel="nofollow noreferrer">salted hashing</a> to store passwords in my database, which means that I should be immune to <a href="https://en.wikipedia.org/wiki/Rainbow_table" rel="nofollow noreferrer">rainbow table</a> attacks.</p> <p>I had a thought, though: what if someone does get hold of my database? It contains the users' email addresses. I can't really hash these, because I'll be using them to send notification emails, etc..</p> <p>Should I encrypt them?</p>
<p>Bruce Schneier has a good response to this kind of problem.</p> <blockquote> <p>Cryptography is not the solution to your security problems. It might be part of the solution, or it might be part of the problem. In many situations, cryptography starts out by making the problem worse, and it isn't at all clear that using cryptography is an improvement.</p> </blockquote> <p>Essentially encrypting your emails in the database 'just in case' is not really making the database more secure. Where are the keys stored for the database? What file permissions are used for these keys? Is the database accesable publically? Why? What kind of account restrictions are in place for these accounts? Where is the machine stored, who has physical access to this box? What about remote login/ssh access etc. etc. etc.</p> <p>So I guess you can encrypt the emails if you want, but if that is the extent of the security of the system then it really isn't doing much, and would actually make the job of maintaining the database harder.</p> <p>Of course this could be part of an extensive security policy for your system - if so then great!</p> <p>I'm not saying that it is a bad idea - But why have a lock on the door from Deadlocks'R'us which cost $5000 when they can cut through the plywood around the door? Or come in through the window which you left open? Or even worse they find the key which was left under the doormat. Security of a system is only as good as the weakest link. If they have root access then they can pretty much do what they want.</p> <p><a href="https://stackoverflow.com/questions/70450/is-it-worth-encrypting-email-addresses-in-the-database#70484">Steve Morgan</a> makes a good point that even if they cannot understand the email addresses, they can still do a lot of harm (which could be mitigated if they only had SELECT access)</p> <p>Its also important to know what your reasons are for storing the email address at all. I might have gone a bit overboard with <a href="https://stackoverflow.com/questions/767276/what-is-the-best-and-safest-way-to-store-user-email-addresses-in-the-database">this answer</a>, but my point is do you really need to store an email address for an account? The most secure data is data that doesn't exist.</p>
<p>You really have to weigh your worst case senario of someone obtaining those email addresses, the likelihood of someone obtaining them, and your extra effort/time needed to impliement the change.</p>
9,583
<p>I mistakenly added files to Git using the command:</p> <pre><code>git add myfile.txt </code></pre> <p>I have not yet run <code>git commit</code>. How do I undo this so that these changes will not be included in the commit?</p>
<p>Undo <code>git add</code> for uncommitted changes with:</p> <pre><code>git reset &lt;file&gt; </code></pre> <p>That will remove the file from the current index (the &quot;about to be committed&quot; list) without changing anything else.</p> <hr /> <p>To unstage all changes for all files:</p> <pre><code>git reset </code></pre> <hr /> <p>In old versions of Git, the above commands are equivalent to <code>git reset HEAD &lt;file&gt;</code> and <code>git reset HEAD</code> respectively, and will fail if <code>HEAD</code> is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called <code>HEAD</code>, which is a stupid thing that you shouldn't do). This <a href="https://git.kernel.org/cgit/git/git.git/tree/Documentation/RelNotes/1.8.2.txt#n179" rel="noreferrer">was changed in Git 1.8.2</a>, though, so in modern versions of Git you can use the commands above even prior to making your first commit:</p> <blockquote> <p>&quot;git reset&quot; (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).</p> </blockquote> <p>Documentation: <a href="https://git-scm.com/docs/git-reset" rel="noreferrer"><strong>git reset</strong></a></p>
<p>The first time I had this problem, I found <a href="https://stackoverflow.com/questions/348170/how-do-i-undo-git-add-before-commit?page=1&amp;tab=votes#tab-top">this post</a> here and from the first answer I learned that I should just do <code>git reset &lt;filename&gt;</code>. It worked fine.</p> <p>Eventually, I happened to have a few subfolders inside my main git folder. I found it easy to just do <code>git add .</code> to add all files inside the subfolders and then <code>git reset</code> the few files that I did not want to add.</p> <p>Nowadays I have lots of files and subfolders. It is tedious to <code>git reset</code> one-by-one but still easier to just <code>git add .</code> first, then reset the few heavy/unwanted but useful files and folders.</p> <p>I've found the following method (which is not recorded <a href="https://stackoverflow.com/questions/348170/how-do-i-undo-git-add-before-commit?page=1&amp;tab=votes#tab-top">here</a> or <a href="https://stackoverflow.com/questions/18424943/undo-multiple-file-and-folder-git-add">here</a>) relatively easy. I hope it will be helpful:</p> <p>Let's say that you have the following situation:</p> <pre><code>Folder/SubFolder1/file1.txt Folder/SubFolder2/fig1.png Folder/SubFolderX/fig.svg Folder/SubFolder3/&lt;manyfiles&gt; Folder/SubFolder4/&lt;file1.py, file2.py, ..., file60.py, ...&gt; </code></pre> <p>You want to add all folders and files but not <code>fig1.png</code>, and not <code>SubFolderX</code>, and not <code>file60.py</code> and the list keeps growing ...</p> <p>First, make/create a <code>bash shell script</code> and give it a name. Say, <code>git_add.sh</code>:</p> <p>Then add all the paths to all folders and files you want to <code>git reset</code> preceded by <code>git reset -- </code>. You can easily copy-paste the paths into the script <code>git_add.sh</code> as your list of files grows. The <code>git_add.sh</code> script should look like this:</p> <pre><code>#!/bin/bash git add . git reset -- Folder/SubFolder2/fig1.png git reset -- Folder/SubFolderX git reset -- Folder/SubFolder4/file60.py </code></pre> <p><code>#!/bin/bash</code> is important. Then do <code>source git_add.sh</code> to run it. After that, you can do <code>git commit -m &quot;some comment&quot;</code>, and then <code>git push -u origin master</code> if you have already set up Bitbucket/Github.</p> <p>Disclaimer: I've only tested this in Linux.</p> <hr /> <p>If you have lots of files and folders that you always retain in your local git repository but you don't want git to track changes when you do <code>git add .</code>, say video and data files, <strong>you must learn how to use <code>.gitignore</code></strong>. Maybe from <a href="https://www.atlassian.com/git/tutorials/saving-changes/gitignore" rel="nofollow noreferrer">here</a>.</p>
45,303
<p>I'm looking for recommendations on books about MVC on the desktop. If they use Java, that is a bonus.</p> <p>Some background: I'm writing a desktop application in Java. It's an audio application that has a number of views and a central model called a Library with playlists, effects lists and a folder structure to organize them. In this application I'd like to have menus, context-menus and drag and drop support for various user actions. I've been struggling with how to achieve this using MVC.</p> <p>I started with all the logic/controllers in the main class but have started to separate them out into their own classes. Now I need to start using listeners and observers to handle messages between the views and the controller. This led to me creating a number of interfaces and looping through my listeners in several places to fire off various messages. But that loop code keeps getting repeated (not DRY), so I'm assuming that now I should create different types of Event classes, create those events in my views and use a single method within the view to fire it off to the various listeners.</p> <p><strong>Update:</strong> Arguabley it shouldn't matter much but I'm using SWT, not Swing.</p>
<p>I've had the same problem: it really takes a lot of discipline to write a (non trivial) swing app, because all the listeners and events and asynchronous processing make up really fast for a big pile of unmaintainable code. </p> <p>I found that classic MVC isn't enough, you have to look into more specific patterns like <a href="http://martinfowler.com/eaaDev/PresentationModel.html" rel="noreferrer">Presentation Model</a> and such. The only book I found covering this patterns when applied to desktop applications is <a href="http://www.sourcebeat.com/books/desktopjavalive.html" rel="noreferrer">Desktop Java Live</a>, by Scott Delap. While the majority of swing books deal with techniques to solve specific problems (how to make a gridless jtable, how to implement a round button, ...), Delap's book will help you architect a medium-sized swing application, best practices, etc.</p>
<p>Don't forget the Swing Tutorials; for instance the <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/index.html" rel="nofollow noreferrer">Swing Events tutorial</a>.</p> <p>And please bear in mind the SwingWorker, or handling events in a separate worker thread. I'm no expert on Swing by any means but I do know that a lot of the perceived slowness of Java Desktop applications is due to the work done in the event thread. If such work takes some time the entire GUI is unresponsive. Hard to fix afterward, not all that hard to do right if you keep it in mind.</p> <p>As for books, I found the Core Java series by Cay Horstmann and Gary Cornell very nice to read. It is however about Java (including Swing) and not about MVC.</p>
20,365
<p>Is there a catch or hidden problem in using a <a href="http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/" rel="nofollow noreferrer">DisposableBase base class</a> instead of recoding the Dispose pattern on every class?</p> <p>Why aren't everyone using such a <strong>relevant</strong> class?</p> <p><strong>Edits</strong>:</p> <ol> <li><p>I naturally only meant classes that implement IDisposable</p></li> <li><p>I know it uses up the option for inheritance, but I'm willing to pay the price (at least when I can and it doesn't hurt me otherwise).</p></li> <li><p>When I can seal the class, I do - but I have some cases where I want the base of an inheritance hierarchy to be Disposable.</p></li> </ol>
<p>You don't need to implement Dispose() on <em>every</em> class - just those with something that needs deterministic cleanup. Re a Disposable base-class, I'm not entirely sure it provides a whole lot - <code>IDisposable</code> isn't a complex interface. The main time it might be useful is if you are handling unmanaged resources and want a finalizer, but even then it isn't much code.</p> <p>Personally, I wouldn't bother with such a base class. In particular, inheritance (in a single-inheritance world) gets restrictive very quickly. But more to the point, overriding a method isn't much different to simply providing a public Dispose() method.</p> <p>Again: you only need a finalizer etc if you are handling unmanaged objects.</p> <p>If I had a lot of these (unmanaged resouces), I might see whether I could get <a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a> to do the work for me. I don't know if one already exists, but it <em>might</em> be possible to create an aspect that handles (in particular) the finalizer etc. Who knows...</p>
<p>As Marc Gravell said, you only need a finalizer if you are handling unmanaged objects. Introducing an unnecessary finalizer in a base class is a bad idea, as per the reasons in section 1.1.4 of the <a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae" rel="nofollow noreferrer">Dispose, Finalization, and Resource Management</a> guidelines:</p> <blockquote> <p>There is a real cost associated with instances with finalizers, both from a performance and code complexity standpoint. ... Finalization increases the cost and duration of your object’s lifetime as each finalizable object must be placed on a special finalizer registration queue when allocated, essentially creating an extra pointer-sized field to refer to your object. Moreover, objects in this queue get walked during GC, processed, and eventually promoted to yet another queue that the GC uses to execute finalizers. Increasing the number of finalizable objects directly correlates to more objects being promoted to higher generations, and an increased amount of time spent by the GC walking queues, moving pointers around, and executing finalizers. Also, by keeping your object’s state around longer, you tend to use memory for a longer period of time, which leads to an increase in working set.</p> </blockquote> <p>If you use <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx" rel="nofollow noreferrer">SafeHandle</a> (and related classes), it's unlikely that any classes that derive from DisposableBase would ever need to be finalized.</p>
35,061
<p>I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.</p> <p>The idea is to write a small C# app that will harvest the URLs and do the comparing. </p> <p>TIA</p>
<p>It is possible to do this in a very hacky and prone to breakage way using the Win32 API function FindWindow.</p> <p>The following C++ example that finds a running instance of the windows Calculator and gets the value of the edit field in it. You should be able to do something similar in C#. Disclaimer: I haven't actually checked to make sure this code compiles, sorry. :)</p> <pre><code>float GetCalcResult(void) { float retval = 0.0f; HWND calc= FindWindow("SciCalc", "Calculator"); if (calc == NULL) { calc= FindWindow("Calc", "Calculator"); } if (calc == NULL) { MessageBox(NULL, "calculator not found", "Error", MB_OK); return 0.0f; } HWND calcEdit = FindWindowEx(calc, 0, "Edit", NULL); if (calcEdit == NULL) { MessageBox(NULL, "error finding calc edit box", "Error", MB_OK); return 0.0f; } long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1; char* temp = (char*) malloc(len); SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp); retval = atof(temp); free(temp); return retval; } </code></pre> <p>In order to find out the right parameters to use in FindWindow and FindWindowEx, use the Visual Studio tool Spy++ to inspect a running instance of your browser window. Sorry, I don't have a code sample for web browsers on-hand, but it should be possible. Note that your solution will be Windows OS specific, and also changes to the UI architecture in future versions of the web browsers could cause your solution to stop working.</p> <p>Using this method to lift the URL right out of the address bar obviously only works for the current tab. I can't see how this would work for all tabs unless you did something really tricky like simulating user input to cycle through the tabs. That would be very intrusive and a user could easily mess up your application by interrupting it with input of their own, but it might work if you're writing something that runs unattended, like an automated test script. If that is the case, you may want to look into other tools like <a href="http://www.autoitscript.com/autoit3/" rel="nofollow noreferrer">AutoIt</a>.</p> <p>This advice is all paraphrased from a <a href="http://www.elenkist.com/bushido_burrito/blog/?p=15" rel="nofollow noreferrer">blog post</a> I once wrote. Good luck!</p>
<p>Just off the top of my head, you might consider using the built-in Firefox language (no idea what it's called). I'm sure it provides a mechanism to do exactally what you talking about. Otherwise those plugin's written for delicious, etc, wouldn't work.</p> <p>As for IE, you're going to need to either do it in C++ or find some managed wrapper for this. I'm not sure how to make an IE plugin, but if you dig deep enough, you should be able to find something.</p> <p>Cheers!</p>
25,335
<p>I'm having an issue where the first layer of my support structures isn't sticking on the edges and causing the print to (eventually) fail. Any ideas on how I can fix it?</p> <p>I'm using Slic3r.</p> <p><a href="https://i.stack.imgur.com/XD4AX.jpg" rel="nofollow noreferrer" title="Photograph of first printed layer"><img src="https://i.stack.imgur.com/XD4AX.jpg" alt="Photograph of first printed layer" title="Photograph of first printed layer"></a></p>
<p>There are many things you'll need to check and/or confirm to ensure that you will have a good bond to the bed. The first is to confirm that you are using a genuine Prusa printer as it appears in the photo. Having built one recently makes it easier for me to guess that is the case.</p> <p>Have you performed the bed calibration sequence? The manual provides a series of steps which results in a zig-zag pattern of filament being placed on the bed, while the z-height is adjusted from the panel. You want to have a filament trace that is only slightly squished onto the bed, not flattened so much that it's cutting into the PEI and not so high that it's nearly cylindrical.</p> <p>The bed must be of the correct temperature for the filament selected. If in doubt, raise it five to ten degrees C. I recently assisted with the aforementioned printer that had a peeling problem and the bed temperature had to be raised to 70°C from the "standard" 55°C generated by Slic3r.</p> <p>It is critical that the bed be clean as well. Denatured alcohol is recommended, with application of a clean cloth.</p> <p>Your photo is somewhat out of focus, making it difficult to determine if the brim is being created at an excessively high z-level, which will cause peeling. The main body of the print, also out of focus appears to be heavily flattened, but that could be an artifact of the photo.</p> <p>The reflections on the bed appear to indicate that some gouges in the surface exist. If your PEI is damaged, you will have the problem you described. I've seen videos in which the bed is not quite as gouged and was refreshed with very light sandpaper or very light steel wool or both. Of course, after using such material, clean the surface thoroughly.</p> <p>I understand the PEI that is applied by the manufacturer is quite thin and can be further damaged if too much pressure is applied while refreshing. It is far better to apply too little pressure if you plan to perform this task.</p> <p>Consider to read through the manual and address all of the calibration aspects of the printer to establish a base point for the problem you are experiencing.</p>
<p>I had a similar issue where slic3r generated supports that attach directly to the bed, but didn't put enough material around the thin supports on the first layer, so they didn't stick to the bed.</p> <p>To solve this I added a brim, see "skirt and brim" under "print settings". This puts more material around both the part and also the supports on the first layer.</p> <p>I didn't need the brim round the whole part as it was sticking to the bed just fine anyway, but this was the only way I could find to give the thin supports the wide base they need to stick to the bed. I used a 5mm brim, but I am sure it would work with less than this.</p>
578
<p>Given an HTML page that has a complex table-based layout and many tags that are duplicated and wasteful, e.g.:</p> <pre><code>td align="left" class="tableformat" width="65%" style="border-bottom:1px solid #ff9600; border-right:1px solid #ff9600; background-color:#FDD69E" nowrap etc. </code></pre> <p>Are there tools to aide the task of refactoring the page into a more compact form? For instance, a tool that automatically generates CSS styles and selectors? That converts tables into div layouts? </p> <p>Just to give a sense of the order of the problem, the page I'm looking at is >8000 lines of HTML and JavaScript, which is 500Kb <em>not counting</em> images! </p> <hr> <p>Update: In re. "give up and start from scratch" comments. What does that mean, in the real world? Print out the page, scan it, set it as the background image in Dreamweaver, and start with that? Seriously? Would that really be more efficient than refactoring? </p> <hr> <p>Update: I'm not denigrating "trace it from scratch" nor did I mean to imply that Dreamweaver is by any means my tool of choice. I'm just very surprised that refactoring a layout is considered to be an intractable problem. </p>
<p>I agree with <a href="https://stackoverflow.com/questions/151369/tools-for-refactoring-table-based-html-layouts-to-css#151466">TimB</a> in that automated tools are going to have trouble doing this, in particular making the relational jumps to combine and abstract CSS in the most efficient way.</p> <p>If you are presenting tabular data, it <strong>may</strong> be reasonable to attempt to refactor the inline CSS to reusable classes.</p> <p>If you have a lot of similar tables with inline styles you can gradually refactor the CSS by simple search and replace. This will give you lots of classes that match a subset of similar tables and lots of somewhat similar classes. Breaking this up into layout and presentation would be a good start, then overriding these with specific classes for each theme or semantically related item.</p> <p>I would still recommend <strong>starting from scratch</strong>, it's probably going to be quicker, and you can recreate only what you need to present the page, and can reuse elements or collections of elements at a later date.</p> <p>The time spent will also pay off <strong>significantly</strong> if the page is ever needed to be modified again. </p> <p>But that's <strong>not at all</strong> likely is it? :D</p>
<p>You denigrate this approach in your question, but I'd recommend taking a screen shot of your page in the browser whose rendering you like the best, declare that to be your reference, and start trying to recreate it. It's easier than you think. I've had to take skanky old table-based layouts and turn them into CMS templates done with modern techniques and it's not that bad a job.</p>
18,246
<p>I am at the point where I need to add keys to my app. What are some of the possible solutions you guys used? I've looked at an earlier <a href="https://stackoverflow.com/questions/118031/best-activation-key-software-for-net-application">post</a> so far, anything else before I decide. My 2 influential factors are:</p> <ol> <li>Price</li> <li>Ease of use</li> </ol> <p>Thanks</p>
<p>If you are talking about software protection, take a minute to reconsider it.</p> <p>Protection schemes are mostly a waste of time. If .NET is similar in this regard to Java, decompiling the code and removing any kind of protection is trivial. The only more or less robust solutions are network based- and these can be very annoying because you are introducing a new point of failure to your application- what happens if your authentication server is down or they lose internet connectivity?</p> <p>I know that "The Powers That Be" like this stuff, but please, analyze the situation carefully.</p>
<p><a href="http://www.aladdin.com/" rel="nofollow noreferrer" title="Aladdin HASP">Aladdin</a></p> <p><a href="http://www.aladdin.com/hasp/protection-keys-benefits-models.aspx" rel="nofollow noreferrer" title="Software and Hardware Comparison">Aladdin's Software and Hardware Solution Comparison Chart</a></p> <p>We purchase these keys and they are very easy to use with sample code generated for you from their utility. Added to this is they are a very professional company (no I don't work for them but have used their products in 2 different companies)</p> <p>The basic hardware keys themselves cost around $30per in small qty but you must purchase the "Master" set which is more expensive (at this time I can't recall the cost).</p>
29,716
<p>Many people string together find and sed, or perl, or any number of other unix commands to find and replace across multiple files. But, there's a simple command that can do it for you without the hassle? </p> <p>Edit: The Digital Ninja points out that it's rpl. </p> <p>However this is not a built in command but, for debian based distros like Ubuntu you can simply install it with sudo apt-get install rpl</p> <p>I would guess that it's available through most package managers in other *nix OSs. OS X Users can download a binary at <a href="http://www.laffeycomputer.com/rpl.html" rel="nofollow noreferrer">http://www.laffeycomputer.com/rpl.html</a></p>
<p>I belive you are thinking of 'rpl' <a href="http://www.linux.org/apps/AppId_2684.html" rel="nofollow noreferrer">http://www.linux.org/apps/AppId_2684.html</a></p>
<p>I think some variation of the following would work :</p> <pre>find . -name *.extension | perl -pi.bak -e "s/text_to_be_replaced/replacement/"</pre>
39,838
<p>So I was writing some code today that basically looks like this:</p> <pre><code>string returnString = s.Replace("!", " ") .Replace("@", " ") .Replace("#", " ") .Replace("$", " ") .Replace("%", " ") .Replace("^", " ") .Replace("*", " ") .Replace("_", " ") .Replace("+", " ") .Replace("=", " ") .Replace("\", " ") </code></pre> <p>Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the <code>Replace()</code> function?</p>
<p>You can use <strong>Regex.Replace()</strong>. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.</p> <pre><code>var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," "); </code></pre>
<pre><code>s/[!@#$%^*_+=\]/ / </code></pre> <p>Would be the regex for it... in c# you should be able to use</p> <pre><code>Regex.Replace(yourstring, "[!@#$%^*_+=\]", "" ); </code></pre> <p>Though my C# is rusty..</p>
14,400
<p>I'm trying to find out the 'correct' windows API for finding out the localized name of 'special' folders, specifically the Recycle Bin. I want to be able to prompt the user with a suitably localized dialog box asking them if they want to send files to the recycle bin or delete them directly.</p> <p>I've found lots on the internet (and on Stackoverflow) about how to do the actual deletion, and it seems simple enough, I just really want to be able to have the text localized.</p>
<p>Read this article for code samples and usage:</p> <p><a href="http://www.codeproject.com/KB/winsdk/SpecialFolders.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/winsdk/SpecialFolders.aspx</a></p> <p>Also there is an article on MSDN that helps you <a href="http://msdn.microsoft.com/en-us/library/aa140088(office.10).aspx" rel="nofollow noreferrer">Identify the Location of Special Folders with API Calls</a></p>
<p>I actually didn't find the CodeProject article terribly helpful, so I thought I'd answer this question with the actual code that I used to retrieve the localized name of the recycle bin.</p> <p>This sample also tries to behave correctly with regard to freeing resources. Any comments are welcome, especially if you spot an error with my resource management!</p> <pre><code>public static string GetLocalizedRecycleBinName() { IntPtr relative_pidl, parent_ptr, absolute_pidl; PInvoke.SHGetFolderLocation(IntPtr.Zero, PInvoke.CSIDL.BitBucket, IntPtr.Zero, 0, out absolute_pidl); try { PInvoke.SHBindToParent(absolute_pidl, ref PInvoke.Guids.IID_IShellFolder, out parent_ptr, out relative_pidl); PInvoke.IShellFolder shell_folder = Marshal.GetObjectForIUnknown(parent_ptr) as PInvoke.IShellFolder; // Release() for this object is called at finalization if (shell_folder == null) return Strings.RecycleBin; PInvoke.STRRET strret = new PInvoke.STRRET(); StringBuilder sb = new StringBuilder(260); shell_folder.GetDisplayNameOf(relative_pidl, PInvoke.SHGNO.Normal, out strret); PInvoke.StrRetToBuf(ref strret, relative_pidl, sb, 260); string name = sb.ToString(); return String.IsNullOrEmpty(name) ? Strings.RecycleBin : name; } finally { PInvoke.ILFree(absolute_pidl); } } static class PInvoke { [DllImport("shell32.dll")] public static extern int SHGetFolderLocation(IntPtr hwndOwner, CSIDL nFolder, IntPtr hToken, uint dwReserved, out IntPtr ppidl); [DllImport("shell32.dll")] public static extern int SHBindToParent(IntPtr lpifq, [In] ref Guid riid, out IntPtr ppv, out IntPtr pidlLast); [DllImport("shlwapi.dll")] public static extern Int32 StrRetToBuf(ref STRRET pstr, IntPtr pidl, StringBuilder pszBuf, uint cchBuf); [DllImport("shell32.dll")] public static extern void ILFree([In] IntPtr pidl); [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214E6-0000-0000-C000-000000000046")] public interface IShellFolder { [PreserveSig] Int32 CompareIDs(Int32 lParam, IntPtr pidl1, IntPtr pidl2); void ParseDisplayName(IntPtr hwnd, IntPtr pbc, String pszDisplayName, UInt32 pchEaten, out IntPtr ppidl, UInt32 pdwAttributes); void EnumObjects(IntPtr hwnd, int grfFlags, out IntPtr ppenumIDList); void BindToObject(IntPtr pidl, IntPtr pbc, [In] ref Guid riid, out IntPtr ppv); void BindToStorage(IntPtr pidl, IntPtr pbc, [In] ref Guid riid, out IntPtr ppv); void CreateViewObject(IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); void GetAttributesOf(UInt32 cidl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IntPtr[] apidl, ref uint rgfInOut); void GetUIObjectOf(IntPtr hwndOwner, UInt32 cidl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] IntPtr[] apidl, [In] ref Guid riid, UInt32 rgfReserved, out IntPtr ppv); void GetDisplayNameOf(IntPtr pidl, SHGNO uFlags, out STRRET pName); void SetNameOf(IntPtr hwnd, IntPtr pidl, string pszName, int uFlags, out IntPtr ppidlOut); } public enum CSIDL { BitBucket = 0x000a, } public enum SHGNO { Normal = 0x0000, ForParsing = 0x8000, } [StructLayout(LayoutKind.Explicit, Size = 520)] public struct STRRETinternal { [FieldOffset(0)] public IntPtr pOleStr; [FieldOffset(0)] public IntPtr pStr; [FieldOffset(0)] public uint uOffset; } [StructLayout(LayoutKind.Sequential)] public struct STRRET { public uint uType; public STRRETinternal data; } public class Guids { public static Guid IID_IShellFolder = new Guid("{000214E6-0000-0000-C000-000000000046}"); } } </code></pre>
5,770
<p>In SQL Server 2005, we can create temp tables one of two ways:</p> <pre><code>declare @tmp table (Col1 int, Col2 int); </code></pre> <p>or</p> <pre><code>create table #tmp (Col1 int, Col2 int); </code></pre> <p>What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory. </p> <p>In which scenarios does one out-perform the other? </p>
<p>There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.</p> <p>As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)</p> <p>Some points to consider when choosing between them: </p> <ul> <li><p>Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.</p></li> <li><p>Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) <a href="https://stackoverflow.com/questions/886050/sql-server-creating-an-index-on-a-table-variable/17385085#17385085">SQL 2014 has non-unique indexes too</a>.</p></li> <li><p>Table variables don't participate in transactions and <code>SELECT</code>s are implicitly with <code>NOLOCK</code>. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!</p></li> <li><p>Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.</p></li> <li><p>You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront. </p></li> <li><p>You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).</p></li> <li><p>Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.</p></li> <li><p>Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (<a href="https://learn.microsoft.com/sql/t-sql/language-elements/declare-local-variable-transact-sql" rel="noreferrer">ref</a>). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.</p></li> <li><p>Global Temp Tables (##tmp) are another type of temp table available to all sessions and users. </p></li> </ul> <p>Some further reading:</p> <ul> <li><p><a href="https://dba.stackexchange.com/a/16386">Martin Smith's great answer</a> on dba.stackexchange.com</p></li> <li><p>MSDN FAQ on difference between the two: <a href="https://support.microsoft.com/en-gb/kb/305977" rel="noreferrer">https://support.microsoft.com/en-gb/kb/305977</a></p></li> <li><p>MDSN blog article: <a href="https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table" rel="noreferrer">https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table</a></p></li> <li><p>Article: <a href="https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables" rel="noreferrer">https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables</a></p></li> <li><p>Unexpected behaviors and performance implications of temp tables and temp variables: <a href="https://sql.kiwi/2012/08/temporary-tables-in-stored-procedures.html" rel="noreferrer">Paul White on SQLblog.com</a></p></li> </ul>
<p>In SQL the Temporary tables are stored in the TempDB and the local temporary tables are only visible in the current session and it will not be visible in another session. This can be shared between nested stored procedure calls. The Global temporary tables are visible to all other sessions and they are destroyed when the last connection referencing table is closed. For Example,</p> <pre><code>Select Dept.DeptName, Dept.DeptId, COUNT(*) as TotalEmployees into #TempEmpCount from Tbl_EmpDetails Emp join Tbl_Dept Dept on Emp.DeptId = Dept.DeptId group by DeptName, Dept.DeptId </code></pre> <p>Table variables are similar to tempTables, a table variable is also created in TempDB. The scope of a table variable is the batch, stored procedure, or statement block in which it is declared. They can be passed as parameters between procedures. The same query can be written using Table variable by</p> <pre><code>Declare @tblEmployeeCount table (DeptName nvarchar(20),DeptId int, TotalEmployees int) Insert @tblEmployeeCount Select DeptName, Tbl_Dept.DeptId, COUNT(*) as TotalEmployees from Tbl_EmpDetails join Tbl_Dept on Tbl_EmpDetails.DeptId = Tbl_Dept.DeptId group by DeptName, Tbl_Dept.DeptId </code></pre>
4,755
<p>What web based interface for browsing <strong>Subversion</strong> repositories do you like the most? We have tried <strong>Viewvc</strong>, but the installation seemed too complex for us.</p> <p>This is no poll. I'd really love to allow people at the office to be able to access the data at the repositories with their web browsers and see who modified each file and when.</p> <p><strong>Subversion</strong> provides web browsing, but is very poor, and <a href="http://upload.wikimedia.org/wikipedia/en/6/63/ViewCVS.png" rel="nofollow noreferrer">Viewvc</a> looks nice but is too hard to install. </p> <p>I am not talking about <strong>Subversion</strong> clients, but just a web showing the commit history, like at <a href="http://media.bitbucket.org/img/promo/ss1.png" rel="nofollow noreferrer">bitbucket</a>. Also, a direct link for a ZIP file for each revision would be awesome.</p>
<p>I love Fisheye from Atlassian (née Cenqua). It might have too many functions for you taste (searching, auditing and code review support are all part of the package these days), but it has the best interface for browsing SVN (or any VC-system, actually) I have yet encountered. On the downside, it's commercial (if you're commercial, that is. They provide free instances for OSS-projects) and hardly inexpensive.</p> <p>You can have a look at their demo-instance at <a href="http://fisheye3.cenqua.com" rel="nofollow noreferrer">http://fisheye3.cenqua.com</a>,</p>
<p>If you are looking for simplicity, you can browse the repository by just pointing your browser to the repository URL.</p>
39,886
<p>A follow up to an earlier question, showing the part that fails when I try to get the error message from my target library:</p> <pre><code>require 'gt4r' @@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini" @@normal_user = "BMCHARGUE" describe Gt4r do it 'initializes' do rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment Gt4r.gTD_get_error_message rv, @msg @msg.should == "" rv.should == 0 end end </code></pre> <p>I expect the error message to be returned in @msg, but when run I get the following:</p> <pre><code>Gt4r (eval):5: [BUG] Segmentation fault ruby 1.8.6 (2008-08-11) [i386-mswin32] This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. </code></pre> <p>And this if I use a symbol (:msg) instead:</p> <pre><code>C:\code\GraphTalk\gt4r_dl&gt;spec -fs -rgt4r gt4r_spec.rb Gt4r - initializes (ERROR - 1) 1) NoMethodError in 'Gt4r initializes' undefined method `to_ptr' for :msg:Symbol (eval):5:in `call' (eval):5:in `gTD_get_error_message' ./gt4r_spec.rb:9: Finished in 0.046 seconds 1 example, 1 failure </code></pre> <p>Clearly I am missing something about passing parameters between ruby and C. What kind of ruby variable do I need to get my value returned? </p>
<p>Which bit fails? I'm guessing it's this:</p> <pre><code>Gt4r.gTD_get_error_message rv, @msg </code></pre> <p>How is the method implemented? What's the C signature of the method? (*char)?</p> <p>Btw: at the risk of sounding like broken record, it's MUCH easier to write a C extension than trying to shoehorn things into DL. AFAIK, no one uses DL, apart from maybe one-off hacks to map single functions. You mentioned FFI doesn't work under Windows, you may want to have a look at RubyInline (<a href="http://www.zenspider.com/ZSS/Products/RubyInline/" rel="nofollow noreferrer">http://www.zenspider.com/ZSS/Products/RubyInline/</a>), or just use a plain C extension (if you know C well enough to use DL, you know C well enough to write an extension)</p>
<p>Is @msg even initialized at this point: </p> <pre><code>Gt4r.gTD_get_error_message rv, @msg </code></pre> <p>If @msg is nil, DL will probably cast it to a null pointer which crashes when your lib tries to dereference it.</p>
38,686
<p>Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely.</p> <p>Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT?</p> <p><strong>Basically, I want to do this without modifying any code, just changing compiler or Windows options.</strong></p> <p>Thanks!</p> <p><a href="http://img519.imageshack.us/img519/853/snapshotbu1.png" rel="nofollow noreferrer" title="Microsoft Visual C++ Debug Library ASSERT">Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png</a></p>
<p>From MSDN about the ASSERT macro:</p> <p>In an MFC ISAPI application, an assertion in debug mode will bring up a modal dialog box (ASSERT dialog boxes are now modal by default); this will interrupt or hang the execution. To suppress modal assertion dialogs, add the following lines to your project source file (projectname.cpp):</p> <pre><code>// For custom assert and trace handling with WebDbg #ifdef _DEBUG CDebugReportHook g_ReportHook; #endif </code></pre> <p>Once you have done this, you can use the WebDbg tool (WebDbg.exe) to see the assertions. </p>
<p>In a unit-test context, it is often good to convert ASSERTs (actually <code>_CrtDbgReport</code> calls) into some exception, typically a std::exception, that contains some informative text. This tends to wend its way out to the unit test's output log as a fail. That's just what you want: A failed ASSERT should be a failed unit test.</p> <p>Do that by throwing in your report-hook function, as specified using: <code>_CrtSetReportHook()</code></p>
19,761
<p>I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution.</p> <p>I am developing an application with the database file included and I want to enable users to move the database file and modify connection strings.</p> <p>Does anyone know what's the best practice for the deployment of the application with the database file?</p>
<p>It should work, provided that you use the exact same connection string setting in your DB access DLL's Settings.settings file and in your application's config file.</p> <p>An example that works well for me:</p> <pre><code> &lt;connectionStrings&gt; &lt;add name="YourApp.Properties.Settings.DatabaseConnectionString" connectionString="Data Source=localhost;Initial Catalog=xxx;Integrated Security=True;" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>When entered appropriately in both locations (ie. the dll's Settings.settings and the exe's App.config files), this does allow me to change the database connection in YourApp.exe.config before the app runs.</p> <p>(I assume you already know that you need to change the application's config file, as DLL's do not support the app.config mechanism directly.)</p>
<p>did you make sure to remove the settings default values? These are compiled and fetched from the dll and not from the config file.</p>
29,285
<p>What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called <code>printer</code>, and this class also stores information on output trays, you could have:</p> <pre><code>class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray; </code></pre> <p>Alternatively:</p> <pre><code>class printer { public: std::string name_; ... }; enum PRINTER_TYPE { PRINTER_TYPE_LOCAL, PRINTER_TYPE_NETWORK, }; class output_tray { ... }; printer prn; PRINTER_TYPE type; output_tray tray; </code></pre> <p>I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split - it seems to be more of a style choice.</p> <p>So, which do you prefer and why?</p>
<h2>Nested classes</h2> <p>There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).</p> <p>Let's imagine the following code :</p> <pre><code>class A { public : class B { /* etc. */ } ; // etc. } ; </code></pre> <p>Or even:</p> <pre><code>class A { public : class B ; // etc. } ; class A::B { public : // etc. } ; </code></pre> <p>So:</p> <ul> <li><b>Privilegied Access:</b> A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation</li> <li><b>A's scope is candidate for symbol lookup:</b> code from inside B will see <b>all</b> symbols from A as possible candidates for a symbol lookup, which can confuse the code</li> <li><b>forward-declaration:</b> There is no way to forward-declare A::B without giving a full declaration of A</li> <li><b>Extensibility:</b> It is impossible to add another class A::C unless you are owner of A</li> <li><b>Code verbosity:</b> putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings.</li> </ul> <p>As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages.</p> <p>Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces.</p> <p>On the pro-side, you isolate this code, and if private, make it unusable but from the &quot;outside&quot; class...</p> <h2>Nested enums</h2> <p>Pros: Everything.</p> <p>Con: Nothing.</p> <p>The fact is enum items will pollute the global scope:</p> <pre><code>// collision enum Value { empty = 7, undefined, defined } ; enum Glass { empty = 42, half, full } ; // empty is from Value or Glass? </code></pre> <p>Ony by putting each enum in a different namespace/class will enable you to avoid this collision:</p> <pre><code>namespace Value { enum type { empty = 7, undefined, defined } ; } namespace Glass { enum type { empty = 42, half, full } ; } // Value::type e = Value::empty ; // Glass::type f = Glass::empty ; </code></pre> <p>Note that C++0x defined the class enum:</p> <pre><code>enum class Value { empty, undefined, defined } ; enum class Glass { empty, half, full } ; // Value e = Value::empty ; // Glass f = Glass::empty ; </code></pre> <p>exactly for this kind of problems.</p>
<p>Only problem with nested classes that I bumped into yet was that C++ does not let us refer to the object of the enclosing class, in the nested class functions. We cannot say "Enclosing::this"</p> <p>(But maybe there's a way?)</p>
26,640
<p>A while back, I had worked on building a <a href="https://biber-boote.ch/yostwerks/SeaCruiser.html" rel="nofollow noreferrer">Yostwerks Sea Cruiser</a>. Now I'm thinking of trying to create a 3D printable (or 3D millable) version of the plans.</p> <p>The original design uses cross-sections cut from a half-inch thick HDPE sheet. However, I am considering changing this out for one of the easier to print materials, but I cannot find any comparative information about stiffness HDPE versus other 3D printing materials.</p> <p>Can I get a suggestion for a alternative to HDPE that is as stiff or stiffer as well as same density or lighter. The Kayak frame is expected to be compressing the cross-sections.</p> <p>An example set of cross-sections is as below: <img src="https://biber-boote.ch/yostwerks/images/NewSections.jpg" alt="Kayak Frame Cross sections"></p> <p>Please note that I have also considering changing the shape of the cross-sections to make stiffer yet lighter cross sections, but that will require some trade-off between portable sized cross-sections versus the stiffness of the cross-sections.</p>
<p>According to <a href="https://omnexus.specialchem.com/polymer-properties/properties/stiffness" rel="nofollow noreferrer">the chart on this page</a> HDPE has a flexural modulus of between 0.75 and 1.575 Gpa; meanwhile PETG has a flexural modulus of 2.20 Gpa, meaning PETG is the stiffer material.</p> <p>HDPE, by definition, has a density greater than 0.941g/cc. PETG has a density of about 1.25g/cc.</p> <p>So while PETG may be denser (depending on the HDPE used), it is more rigid, while not being too rigid.</p> <p>PETG is quite printable using FDM. If you were printing at a higher temperature and high % infill, I could see it holding up well enough. I've printed heavy duty parts with it using a 0.8mm nozzle.</p>
<p>Because of the inherent nature of FDM, material properties will most certainly be always lower than casted/extruded sheet material. Furthermore, your question implies to use the same geometry of the ribs, I doubt whether there will be a filament that is able to get close to your requirements regarding strength and stiffness (for the same geometry). Your best choice for filament would be a high strength filament type like PC, certain co-polyester and ABS. But, I'm more inclined to say that this whole question is more of a design issues rather than material selection issue. For that reason I struggled to vote to close as being off topic for this site. In aerospace engineering t-stiffeners are used to make panels, e.g. wing or hull sections, more stiff by riveting T-profile shaped aluminium stiffeners onto the panels, this is something you could consider (bolt on aluminium profiles), as well as incorporating these stiff ridges directly printed in your design, but that would change the shape of the ribs.</p>
1,080
<p>I finished a 3D object for 4 wheels, but something seems wrong with the final scene to me:</p> <p>The nearer wheels (#1 and #2) appear smaller than the far one (#3 and #4), and the distance between wheel #3 an #4 seems longer than between (1) and (2), like you can see in this picture:</p> <p><a href="https://i.stack.imgur.com/8YdzP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8YdzP.png" alt="4 wheels"></a></p> <p>I want to achieve the scene like this:</p> <p><a href="https://i.stack.imgur.com/RkHkU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RkHkU.png" alt="Example of a wanted render"></a></p> <p>How to do that in FreeCAD?</p>
<p>CAD programs uses parallel view not perspective view. So the length of 2 objects with the same length are displayed as 2 objects with the same length on the screen. This is better for constructing stuff. </p>
<p>CAD programs uses parallel view not perspective view. So the length of 2 objects with the same length are displayed as 2 objects with the same length on the screen. This is better for constructing stuff. </p>
1,044
<p>This is a question for a WSS/SharePoint guru. </p> <p>Consider this scenario: I have an ASP.Net web service which links our corporate CRM system and WSS-based intranet together. What I am trying to do is provision a new WSS site collection whenever a new client is added to the CRM system. In order to make this work, I need to programmatically add the managed path to the new site collection. I know that this is possible via the Object Model, but when I try it in my own web service, it fails. Sample code extract below:</p> <pre><code> Dim _ClientSiteUrl As String = "http://myintranet/clients/sampleclient" Using _RootWeb As SPSite = New SPSite("http://myintranet") Dim _ManagedPaths As SPPrefixCollection = _RootWeb.WebApplication.Prefixes If Not (_ManagedPaths.Contains(_ClientSiteUrl)) Then _ManagedPaths.Add(_ClientSiteUrl, SPPrefixType.ExplicitInclusion) End If End Using </code> </pre> <p>This code fails with a NullReferenceException on SPUtility.ValidateFormDigest(). Research suggested that this may be due to insufficient privileges, I tried running the code within an elevated privileges block using SPSecurity.RunWithElevatedPrivileges(AddressOf AddManagedPath), where AddManagedPath is a Sub procedure containing the above code sample.</p> <p>This then fails with an InvalidOperationException, "Operation is not valid due to the current state of the object."</p> <p>Where am I going wrong?</p> <p>One workaround I have managed to do is to call out to STSADM.EXE via Process.Start(), supplying the requisite parameters, and this works.</p> <p><strong>Update:</strong> whilst developing the web service, I am running it using the built-in Visual Studio 2005 web server - what security context will this be running under? Can I change the security context by putting entries in web.config?</p> <p><strong>Update:</strong> I think the problem is definitely to do with not running the web service within the correct SharePoint security context. I decided to go with the workaround I suggested and shell out to STSADM, although to do this, the application pool identity that the web service runs under must be a member of the SharePoint administrators.</p>
<p><strong>Update</strong> I think you have proved that the issue is not with the code.</p> <p>SPSecurity.RunWithElevatedPrivileges: Normally the code in the SharePoint web application executes with the privileges of the user taking the action. The RunWithElevatedPrivileges runs the code in the context of the SharePoint web application pools account (i think) The description on <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx" rel="nofollow noreferrer">MSDN</a> could go into the details a tiny bit more.</p> <p>The issue with the call may be that the web service is not actually running the code within a SharePoint process, so explaining why it cannot elevate (wild guess alert). </p> <p>Have a crack at changing the user of your web services application pool and see if that gives any joy.</p> <hr> <p>It is likely to be a permissions issue. Maybe try:</p> <pre><code>Dim clientSiteUrl As String = "http://myintranet/clients/sampleclient" Using SPSite = new SPSite(clientSiteUrl) webApp As SPWebApplication = SPWebApplication.Lookup(new Uri(clientSiteUrl)); If Not (webApp.Prefixes.Contains(clientSiteUrl)) Then webApp.Prefixes.Add(clientSiteUrl, SPPrefixType.ExplicitInclusion) End If End Using </code></pre> <p>This is not exact code.</p>
<p>If you want to create a managed path (explicit) and a site collection at that path, do the following:</p> <pre><code>using (SPSite site = new SPSite("http://dev-moss07-eric")) { SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://dev-moss07-eric")); if (webApp.Prefixes.Contains("ManagedPathHere")) { // } else { webApp.Prefixes.Add("ManagedPathHere", SPPrefixType.ExplicitInclusion); } using (SPWeb web = site.OpenWeb()) { SPWebApplication webApplication = web.Site.WebApplication; try { webApplication.Sites.Add("ManagedPathHere","Site Title Here","This site is used for hosting styling assets.", 1033, "STS#1", "6scdev\\eric.schrader", "Eric Schrader", "eric.schrader@6sc.com"); } catch (Exception ex) { //ex.ToString; } } } </code></pre>
45,878
<p>What's the most appropriate type used to store the duration time information of a video in sql server?</p>
<p>There are <a href="http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server" rel="nofollow noreferrer">several options</a>, including using the builtin DateTime or Time data type with offset from a particular fixed zero (which will allow you to use the built-in date/time function to get hours, minutes and seconds, etc.</p> <p>If you were on pre-SQL Server 2005, you could combine it with a <a href="http://weblogs.sqlteam.com/jeffs/archive/2004/12/02/2959.aspx" rel="nofollow noreferrer">user-defined data type technique</a> (if your spans are less than 24 hours) to constrain the date part to be guaranteed not to wander.</p>
<p>I would store it as an INT representing the number of seconds, but I suppose it all depends what you need to do with the information in your database (you wouldn't want to have to convert it to HH:MM:SS or something else in your DB)</p>
31,738
<p>I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:</p> <pre><code>&lt;table&gt;&lt;tr&gt;&lt;td class="case"&gt;123456&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).</p> <p>So I'd like that "123456" to be changed to a link of this form:</p> <pre><code>&lt;a href="http://bugs.example.com/fogbugz/default.php?123456"&gt;123456&lt;/a&gt; </code></pre> <p>Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.</p>
<p>Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..</p> <pre><code>function makeCasesClickable(){ var cells = document.getElementsByTagName('td') for (var i = 0, cell; cell = cells[i]; i++){ if (cell.className != 'case') continue var caseId = cell.innerHTML cell.innerHTML = '' var link = document.createElement('a') link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId link.appendChild(document.createTextNode(caseId)) cell.appendChild(link) } } </code></pre> <p>You can apply it with something like <code>onload = makeCasesClickable</code>, or simply include it right at the end of the page.</p>
<p>I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:</p> <p>Here's a php function called 'linker();'that enables a fake CSS attribute </p> <blockquote> <p>connect: 'url.com';</p> </blockquote> <p>for an #id defined item. just let the php call this on every item of HTML you deem link worthy. the inputs are the .css file <strong>as a string</strong>, using: </p> <blockquote> <p>$style_cont = file_get_contents($style_path);</p> </blockquote> <p>and the #id of the corresponding item. Heres the whole thing:</p> <pre><code> function linker($style_cont, $id_html){ if (strpos($style_cont,'connect:') !== false) { $url; $id_final; $id_outer = '#'.$id_html; $id_loc = strpos($style_cont,$id_outer); $connect_loc = strpos($style_cont,'connect:', $id_loc); $next_single_quote = stripos($style_cont,"'", $connect_loc); $next_double_quote = stripos($style_cont,'"', $connect_loc); if($connect_loc &lt; $next_single_quote) { $link_start = $next_single_quote +1; $last_single_quote = stripos($style_cont, "'", $link_start); $link_end = $last_single_quote; $link_size = $link_end - $link_start; $url = substr($style_cont, $link_start, $link_size); } else { $link_start = $next_double_quote +1; $last_double_quote = stripos($style_cont, '"', $link_start); $link_end = $last_double_quote; $link_size = $link_end - $link_start; $url = substr($style_cont, $link_start, $link_size); //link! } $connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1; $id_start = strrpos($style_cont, '#', $connect_loc_rev); $id_end = strpos($style_cont,'{', $id_start); $id_size = $id_end - $id_start; $id_raw = substr($style_cont, $id_start, $id_size); $id_clean = rtrim($id_raw); //id! if (strpos($url,'http://') !== false) { $url_clean = $url; } else { $url_clean = 'http://'.$url; }; if($id_clean[0] == '#') { $id_final = $id_clean; if($id_outer == $id_final) { echo '&lt;a href="'; echo $url_clean; echo '" target="_blank"&gt;'; }; }; }; }; </code></pre> <p>this could probably be improved/shortened using commands like .wrap() or getelementbyID() because it only generates the <code>&lt;a href='blah'&gt;</code> portion, but seeing as <code>&lt;/a&gt;</code> disappears anyway without a opening clause it still works if you just add them everywhere :D</p>
19,953
<p>Some prints take a long time and, as I'm not in a workshop, I need to pause the print sometimes.</p> <p>Are there any special considerations I should take when pausing, or can I literally just click pause, leave it for twelve hours or so, and it'll continue without any ill effects?</p> <p>I'm using PLA at present.</p>
<p>If you keep the head hot during the pause, and over the print, you will melt the material already deposited.</p> <p>If you move to X0 Y0 (like on a layer change) and pause there, you can cool off the head (or not), but will want to prime (advance) some material before resuming your print - or risk an initial void, as the heated material will expand and drip to some extent.</p> <p>If you move to X0 Y0, retract, and cool off for your pause, you should be able to heat up, advance, and resume with few issues. You will probably still need to some manual cleaning where the resume was, as there is likely to be some buildup.</p> <p>Also, if you let the bed cool during your pause, your print may become unstuck from the bed.</p>
<p>It is not recommended to pause prints a considerable amount of time as the printed model will shrink and might warp during the pause. Also, layer bonding between the old and the new art after resuming will be weak, but this can be used to induce planned breaking layers.</p> <p>On the other hand, <strong>if</strong> you have set up your printer properly, it is quite safe to leave the room even during the print:</p> <ul> <li>Maxtemp and Thermal Runaway Protection need to be set</li> <li>a smoke detector over the printer should be installed</li> <li>the printer should be placed in a way that no flammable objects can get in contact with it</li> </ul>
1,136
<p>I have somehow misconfigured fingers. This leads to a very annoying situation.</p> <ol> <li>I select a block of text to copy;</li> <li>I move the cursor the place where I want to paste the code;</li> <li>I accidentally press Ctrl+C again instead of Ctrl+V;</li> <li>My block of copied text is replaced by an empty block;</li> <li>I have to go back and do it all over again. Grrrrr.</li> </ol> <p>Is there any way to disable this behavior, that is to disable copy of empty blocks of text in Visual Studio 2005+?</p>
<p>It's not copying an empty block, it's copying the blank line. You can change this setting in Tools > Options > Text Editor > All Languages > 'Apply Cut or Copy Commands to blank lines when there is no selection'</p>
<p>Go to Tools > Options > Text Editor > All Languages > General</p> <p>The option on that page is "Apply Cut or Copy commands to blank lines when there is no selection"</p>
9,971
<p>I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?</p> <p>I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. </p>
<p>I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?</p> <p>If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:</p> <pre><code>public void sendHttpRequest(byte[] requestData, Socket connection) { long startTime = System.nanoTime(); writeYourRequestData(connection.getOutputStream(), requestData); byte[] responseData = readYourResponseData(connection.getInputStream()); long elapsedTime = System.nanoTime() - startTime; System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime); } </code></pre> <p>This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented).</p>
<p>Use AOP to intercept calls to the socket and measure the response time.</p>
9,444
<p>I got the following class :</p> <pre><code>class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet </code></pre> <p>What the heck ?</p> <p>And the worst is that I can't try super() since Exception are old based class...</p> <p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p> <p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
<p>Both <code>Exception</code> and <code>dict</code> are implemented in C.</p> <p>I think you can test this the follwing way:</p> <pre><code>&gt;&gt;&gt; class C(object): pass ... &gt;&gt;&gt; '__module__' in C.__dict__ True &gt;&gt;&gt; '__module__' in dict.__dict__ False &gt;&gt;&gt; '__module__' in Exception.__dict__ False </code></pre> <p>Since <code>Exception</code> and <code>dict</code> have different ideas of how to store their data internally, they are not compatible and thus you cannot inherit from both at the same time.</p> <p>In later versions of Python you should get an Exception the moment you try to define the class:</p> <pre><code>&gt;&gt;&gt; class foo(dict, Exception): ... pass ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict </code></pre>
<p>I am almost certain that with 2.4 problem is caused by exceptions being old style classes.</p> <pre><code>$ python2.4 Python 2.4.4 (#1, Feb 19 2009, 09:13:34) &gt;&gt;&gt; type(dict) &lt;type 'type'&gt; &gt;&gt;&gt; type(Exception) &lt;type 'classobj'&gt; &gt;&gt;&gt; type(Exception()) &lt;type 'instance'&gt; $ python2.5 Python 2.5.4 (r254:67916, Feb 17 2009, 23:11:16) &gt;&gt;&gt; type(Exception) &lt;type 'type'&gt; &gt;&gt;&gt; type(Exception()) &lt;type 'exceptions.Exception'&gt; </code></pre> <p>In both versions as the message says exceptions can be classes, instances (of old style classes) or strings (deprecated).</p> <p>From version 2.5 exception hierarchy is based on new style classes finally. And instances of new style classes which inherit from BaseException are now allowed too. But in 2.4 multiple inheritance from Exception (old style class) and dict (new style class) results in new style class which is not allowed as exception (mixing old and new style classes is probably bad anyway).</p>
39,829
<p>I've recently found out about protocol buffers and was wondering if they could be applied to my specific problem.</p> <p>Basically I have some CSV data that I need to convert to a more compact format for storage as some of the files are several gig. </p> <p>Each field in the CSV has a header, and there are only two types, strings and decimals (because sometimes there are alot of significant digits and I need to handle all numbers the same way). But each file will have different column names for each field.</p> <p>As well as capturing the original CSV data I need to be able to add extra information to the file before saving. And I was hoping to make this future proof by handling different file versions.</p> <p>So, is it possible to use protocol buffers to capture a random number of randomly named columns of data, like a CSV file?</p>
<p>Well, it's certainly representable. Something like:</p> <pre><code>message CsvFile { repeated CsvHeader header = 1; repeated CsvRow row = 2; } message CsvHeader { require string name = 1; require ColumnType type = 2; } enum ColumnType { DECIMAL = 1; STRING = 2; } message CsvRow { repeated CsvValue value = 1; } // Note that the column is implicit based on position within row message CsvValue { optional string string_value = 1; optional Decimal decimal_value = 2; } message Decimal { // However you want to represent it (there are various options here) } </code></pre> <p>I'm not sure how much benefit it will provide, mind you... You can certainly add more information (add to the CsvFile message) and future proofing is in the "normal PB way" - only add optional fields, etc.</p>
<p>Well, protobuf-net (my version) is based on regular .NET types, so no (since it won't cope with different schemas all the time). But Jon's version might allow dynamic types. Personally, I'd just use CSV and run it through GZipStream - I expect that will be fine for the purpose.</p> <hr> <p>Edit: actually, I forgot: protobuf-net does support extensible objects, but you need to be a bit careful... it would depend on the full context, I expect.</p> <p>Plus Jon's approach of nested data would probably work too.</p>
48,537
<p>I have a repeater that is bound to some data.</p> <p>I bind to the <strong>ItemDataBound</strong> event, and I am attempting to <strong>programmatically</strong> create a <strong>UserControl</strong>:</p> <p>In a nutshell:</p> <pre><code>void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e) { CCTask task = (CCTask)e.Item.DataItem; if (task is ExecTask) { ExecTaskControl foo = new ExecTaskControl(); e.Item.Controls.Add(foo); } } </code></pre> <p>The problem is that while the binding works, the user control is not rendered to the main page.</p>
<p>Eh, figured out one way to do it:</p> <pre><code>ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\ExecTaskControl.ascx"); </code></pre> <p>It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.</p>
<p>I think that @Craig is on the right track depending on the details of the problem you are solving. Add it to the repeater and remove it or set Visible="false" to hide it where needed. Viewstate gets tricky with dynamically created controls/user controls, so google that or check <a href="http://www.aspnet4you.com/articles.aspx?articleid=5032" rel="nofollow noreferrer">here</a> if you must add dynamically. The article referenced also shows an alternative way to load dynamically:</p> <blockquote> <p>Control ctrl=this.LoadControl(Request.ApplicationPath +"/Controls/" +ControlName);</p> </blockquote>
4,874
<p>What is the difference between <code>ref</code> and <code>out</code> parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?</p>
<p>They're pretty much the same - the only difference is that a variable you pass as an <code>out</code> parameter doesn't need to be initialized but passing it as a <code>ref</code> parameter it has to be set to something.</p> <pre><code>int x; Foo(out x); // OK int y; Foo(ref y); // Error: y should be initialized before calling the method </code></pre> <p><code>Ref</code> parameters are for data that might be modified, <code>out</code> parameters are for data that's an additional output for the function (eg <code>int.TryParse</code>) that are already using the return value for something.</p>
<p>ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, since it's returning a new object.</p>
16,378
<p>I'm encountering some peculiarities with LINQ to SQL.</p> <p>With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this:</p> <pre><code> var list = dataContext.MyLists.Single(x =&gt; x.ID == myId); var items = from i in list.MyItems select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query:</p> <pre><code> var items = from i in dataContext.MyLists select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>The first one runs fine, yet the second query yields a: </p> <p><em>Could not translate expression '...' into SQL and could not treat it as a local expression.</em></p> <p>If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values.</p> <p>Any ideas?</p> <p>Anthony</p>
<p>I'd do the SQL part without doing the formatting, then do the formatting on the client side:</p> <pre><code>var items = list.MyItems.Select(item =&gt; new { item.ID, item.Sector, item.Description, item.CompleteDate, item.DueDate }) .AsEnumerable() // Don't do the next bit in the DB .Select(item =&gt; new { item.ID, item.Sector, item.Description, CompleteDate = FormatDate(CompleteDate), DueDate = FormatDate(DueDate) }); static string FormatDate(DateTime? date) { return date.HasValue ? date.Value.ToShortDateString() : "" } </code></pre>
<p><code>ToShortDateString()</code> is not supported by Linq to SQL <a href="http://msdn.microsoft.com/en-us/library/bb882657.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb882657.aspx</a></p>
19,728
<p>I want to automate SVN adds using NAnt. I want to add to SVN all new files in a given directory. The NAnt script will successfully execute the add command, however it displays the Tortoise SVN add dialog and this is not acceptable because it will execute on a build server running CruiseControl. The build server is running Windows Server 2003. </p> <p>Any ideas?</p> <pre><code>&lt;target name="addtest"&gt; &lt;exec program="c:\program files\tortoisesvn\bin\tortoiseproc.exe" commandline="/command:add * --force /path:C:\svn\test /notempfile /closeonend:1" basedir="C:\svn\test" failonerror="false"/&gt; &lt;/target&gt; </code></pre>
<p>Don't use tortoisesvn. Get a <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">commandline svn client</a>.</p>
<p>don't use tortoise!</p> <p>just drop to command line svn.</p> <pre><code>c:\&gt;svn add ... </code></pre>
30,642
<p>I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?</p> <p>I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.</p> <p><strong>EDIT</strong>: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to <strong>read</strong> attachments from <strong>received</strong> mail.</p> <p>Cheers, Don</p>
<p>Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading.</p> <p>The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths.</p> <p>Focus on the doEMailDownload method.</p> <pre><code>/** * Copyright (c) 2008 Steven M. Cherry * All rights reserved. */ package utils.scheduled; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Timestamp; import java.util.Properties; import java.util.Vector; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeBodyPart; import glob.ActionLogicImplementation; import glob.IOConn; import glob.log.Log; import logic.utils.sql.Settings; import logic.utils.sqldo.EMail; import logic.utils.sqldo.EMailAttach; /** * This will connect to our incoming e-mail server and download any e-mails * that are found on the server. The e-mails will be stored for further processing * in our internal database. Attachments will be written out to separate files * and then referred to by the database entries. This is intended to be run by * the scheduler every minute or so. * * @author Steven M. Cherry */ public class DownloadEMail implements ActionLogicImplementation { protected String receiving_host; protected String receiving_user; protected String receiving_pass; protected String receiving_protocol; protected boolean receiving_secure; protected String receiving_attachments; /** This will run our logic */ public void ExecuteRequest(IOConn ioc) throws Exception { Log.Trace("Enter"); Log.Debug("Executing DownloadEMail"); ioc.initializeResponseDocument("DownloadEMail"); // pick up our configuration from the server: receiving_host = Settings.getValue(ioc, "server.email.receiving.host"); receiving_user = Settings.getValue(ioc, "server.email.receiving.username"); receiving_pass = Settings.getValue(ioc, "server.email.receiving.password"); receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol"); String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure"); receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments"); // sanity check on the parameters: if(receiving_host == null || receiving_host.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no host defined. } if(receiving_user == null || receiving_user.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no user defined. } if(receiving_pass == null || receiving_pass.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no pass defined. } if(receiving_protocol == null || receiving_protocol.length() == 0){ Log.Debug("EMail receiving protocol not defined, defaulting to POP"); receiving_protocol = "POP"; } if(tmp_secure == null || tmp_secure.length() == 0 || tmp_secure.compareToIgnoreCase("false") == 0 || tmp_secure.compareToIgnoreCase("no") == 0 ){ receiving_secure = false; } else { receiving_secure = true; } if(receiving_attachments == null || receiving_attachments.length() == 0){ Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/"); receiving_attachments = "./email/attachments/"; } // now do the real work. doEMailDownload(ioc); ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); } protected void doEMailDownload(IOConn ioc) throws Exception { // Create empty properties Properties props = new Properties(); // Get the session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(receiving_protocol); store.connect(receiving_host, receiving_user, receiving_pass); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); try { // Get directory listing Message messages[] = folder.getMessages(); for (int i=0; i &lt; messages.length; i++) { // get the details of the message: EMail email = new EMail(); email.fromaddr = messages[i].getFrom()[0].toString(); Address[] to = messages[i].getRecipients(Message.RecipientType.TO); email.toaddr = ""; for(int j = 0; j &lt; to.length; j++){ email.toaddr += to[j].toString() + "; "; } Address[] cc; try { cc = messages[i].getRecipients(Message.RecipientType.CC); } catch (Exception e){ Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage()); cc = null; } email.cc = ""; if(cc != null){ for(int j = 0; j &lt; cc.length; j++){ email.cc += cc[j].toString() + "; "; } } email.subject = messages[i].getSubject(); if(messages[i].getReceivedDate() != null){ email.received_when = new Timestamp(messages[i].getReceivedDate().getTime()); } else { email.received_when = new Timestamp( (new java.util.Date()).getTime()); } email.body = ""; Vector&lt;EMailAttach&gt; vema = new Vector&lt;EMailAttach&gt;(); Object content = messages[i].getContent(); if(content instanceof java.lang.String){ email.body = (String)content; } else if(content instanceof Multipart){ Multipart mp = (Multipart)content; for (int j=0; j &lt; mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Mime type is not plain"); // Special non-attachment cases here of // image/gif, text/html, ... EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile(savefile, part); } } else if ((disposition != null) &amp;&amp; (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) ){ // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Save file (%s)", part.getFileName() ); EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile( savefile, part); } } } } // Insert everything into the database: logic.utils.sql.EMail.insertEMail(ioc, email); for(int j = 0; j &lt; vema.size(); j++){ vema.get(j).emailid = email.id; logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) ); } // commit this message and all of it's attachments ioc.getDBConnection().commit(); // Finally delete the message from the server. messages[i].setFlag(Flags.Flag.DELETED, true); } // Close connection folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); } catch (Exception e){ folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); throw e; } } protected int saveFile(File saveFile, Part part) throws Exception { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) ); byte[] buff = new byte[2048]; InputStream is = part.getInputStream(); int ret = 0, count = 0; while( (ret = is.read(buff)) &gt; 0 ){ bos.write(buff, 0, ret); count += ret; } bos.close(); is.close(); return count; } protected String decodeName( String name ) throws Exception { if(name == null || name.length() == 0){ return "unknown"; } String ret = java.net.URLDecoder.decode( name, "UTF-8" ); // also check for a few other things in the string: ret = ret.replaceAll("=\\?utf-8\\?q\\?", ""); ret = ret.replaceAll("\\?=", ""); ret = ret.replaceAll("=20", " "); return ret; } } </code></pre>
<pre><code>import java.io.IOException; import java.io.InputStream; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller @RequestMapping("/sendEmail.do") public class SendEmailAttachController { @Autowired private JavaMailSender mailSender; @RequestMapping(method = RequestMethod.POST) public String sendEmail(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFile) { // Input here final String emailTo = request.getParameter("mailTo"); final String subject = request.getParameter("subject"); final String yourmailid = request.getParameter("yourmail"); final String message = request.getParameter("message"); // Logging System.out.println("emailTo: " + emailTo); System.out.println("subject: " + subject); System.out.println("Your mail id is: "+yourmailid); System.out.println("message: " + message); System.out.println("attachFile: " + attachFile.getOriginalFilename()); mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper( mimeMessage, true, "UTF-8"); messageHelper.setTo(emailTo); messageHelper.setSubject(subject); messageHelper.setReplyTo(yourmailid); messageHelper.setText(message); // Attachment with mail String attachName = attachFile.getOriginalFilename(); if (!attachFile.equals("")) { messageHelper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } } }); return "Result"; } } </code></pre>
18,808
<p>I have this code</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(int argc,char **argv) { unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995LL; unsigned long long num2 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996LL; unsigned long long num3 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997LL; unsigned long long num4 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998LL; unsigned long long num5 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999LL; cout &lt;&lt; (unsigned long long)(num1 * num2 * num3 * num4 * num5) &lt;&lt; endl; return 0; } </code></pre> <p>As you can see the numbers are enormous, but when I do the math there I get this: 18446744073709551496</p> <p>At compile time I get these warnings:</p> <pre><code>warning: integer constant is too large for its type| In function `int main(int, char**)':| warning: this decimal constant is unsigned only in ISO C90| ... </code></pre>
<p>Your result is larger than the long long type - you need to look at a <a href="http://mattmccutchen.net/bigint/" rel="noreferrer">BigInteger</a> or arbitrary precision library, something like <a href="http://gmplib.org/" rel="noreferrer">gmp</a></p>
<p>unsigned int represents a system word. Today, that word will max out at either 2^32 -1 or 2^64 - 1, depending on whether your system is 32 bit or 64 bit. You're hitting the cap.</p> <p>You have to write a bignum class or use one off the 'net.</p> <p>Why are you doing this problem anyway?</p>
29,810
<p>Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)</p> <p>(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)</p>
<p>Here's code to get the full path to the executing app:</p> <p>Variable declarations:</p> <pre><code>char pBuf[256]; size_t len = sizeof(pBuf); </code></pre> <p>Windows:</p> <pre><code>int bytes = GetModuleFileName(NULL, pBuf, len); return bytes ? bytes : -1; </code></pre> <p>Linux:</p> <pre><code>int bytes = MIN(readlink(&quot;/proc/self/exe&quot;, pBuf, len), len - 1); if(bytes &gt;= 0) pBuf[bytes] = '\0'; return bytes; </code></pre>
<p>On POSIX platforms, you can use <a href="http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html" rel="nofollow noreferrer">getcwd()</a>.</p> <p>On Windows, you may use <a href="http://msdn.microsoft.com/en-us/library/sf98bd4y(VS.80).aspx" rel="nofollow noreferrer">_getcwd()</a>, as use of <a href="http://msdn.microsoft.com/en-us/library/ms235450(VS.80).aspx" rel="nofollow noreferrer">getcwd()</a> has been deprecated.</p> <p>For standard libraries, if Boost were standard enough for you, I would have suggested Boost::filesystem, but they seem to have removed path normalization from the proposal. You may have to wait until <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1975.html" rel="nofollow noreferrer">TR2 becomes readily available</a> for a fully standard solution.</p>
17,294
<p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p> <p>e.g. for "Employee" Entity</p> <p><strong>Design 1:</strong></p> <pre><code>-- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" </code></pre> <p><strong>Design 2:</strong></p> <pre><code>-- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId, .., ..)" </code></pre> <p>Is there any other way of doing this thing? </p> <p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p> <p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>
<p>I think the key question to ask here is 'Who / What is going to be using the history'?</p> <p>If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...</p> <p>Create a table called 'AuditTrail' or something that has the following fields...</p> <pre><code>[ID] [int] IDENTITY(1,1) NOT NULL, [UserID] [int] NULL, [EventDate] [datetime] NOT NULL, [TableName] [varchar](50) NOT NULL, [RecordID] [varchar](20) NOT NULL, [FieldName] [varchar](50) NULL, [OldValue] [varchar](5000) NULL, [NewValue] [varchar](5000) NULL </code></pre> <p>You can then add a 'LastUpdatedByUserID' column to all of your tables which should be set every time you do an update / insert on the table.</p> <p>You can then add a trigger to every table to catch any insert / update that happens and creates an entry in this table for each field that's changed. Because the table is also being supplied with the 'LastUpdateByUserID' for each update / insert, you can access this value in the trigger and use it when adding to the audit table.</p> <p>We use the RecordID field to store the value of the key field of the table being updated. If it's a combined key, we just do a string concatenation with a '~' between the fields.</p> <p>I'm sure this system may have drawbacks - for heavily updated databases the performance may be hit, but for my web-app, we get many more reads than writes and it seems to be performing pretty well. We even wrote a little VB.NET utility to automatically write the triggers based on the table definitions.</p> <p>Just a thought!</p>
<p>It sounds like you want to track changes to specific entities over time, e.g. ID 3, "bob", "123 main street", then another ID 3, "bob" "234 elm st", and so on, in essence being able to puke out a revision history showing every address "bob" has been at.</p> <p>The best way to do this is to have an "is current" field on each record, and (probably) a timestamp or FK to a date/time table.</p> <p>Inserts have to then set the "is current" and also unset the "is current" on the previous "is current" record. Queries have to specify the "is current", unless you want all of the history.</p> <p>There are further tweaks to this if it's a very large table, or a large number of revisions are expected, but this is a fairly standard approach.</p>
6,033
<p>For my area, I get the updates from </p> <ul> <li>ww.asp.net</li> <li>code.google.com</li> <li>www.webmasterworld.com</li> </ul> <p>What others do you highly recommend?</p>
<p>If you're into anything with Linux: <a href="http://www.linux.com/feature" rel="nofollow noreferrer">http://www.linux.com/feature</a></p> <p><a href="http://www.alistapart.com/" rel="nofollow noreferrer">A List Apart</a> has some excellent web articles</p> <p>If you want keep up with browsers, <a href="http://www.favbrowser.com/" rel="nofollow noreferrer">Web Browsers News and Reviews</a> might help.</p> <p>Finally, <a href="http://www.quirksmode.org/elsewhere/" rel="nofollow noreferrer">PPK</a>, a javascript expert, often has some interesting links and blog posts.</p>
<p><a href="http://ayende.com" rel="nofollow noreferrer">Ayende</a>'s (creator of <a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">Rhino Mocks</a>) blog is a great read.</p>
29,417
<p>In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s '<strong>ref</strong>' keyword.</p> <p>Example:</p> <pre><code>def func(x) x += 1 end a = 5 func(a) #this should be something like func(ref a) puts a #should read '6' </code></pre> <p>Btw. I know I could just use:</p> <pre><code>a = func(a) </code></pre>
<p>You can accomplish this by explicitly passing in the current binding:</p> <pre><code>def func(x, bdg) eval "#{x} += 1", bdg end a = 5 func(:a, binding) puts a # =&gt; 6 </code></pre>
<p>However, it seems that composite objects, like hashes, are passed by reference:</p> <pre><code>fp = {} def changeit(par) par[:abc] = 'cde' end changeit(fp) p fp </code></pre> <p>gives</p> <pre><code>{:abc=&gt;"cde"} </code></pre>
19,522
<p>What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class) Right now I can't think of any.</p>
<p>Because writing classes to be substitutably extended is <em>damn hard</em> and requires you to make accurate predictions of how future users will want to extend what you've written.</p> <p>Sealing your class forces them to use composition, which is much more robust.</p>
<p>Because you always want to be handed a reference to the class and not to a derived one for various reasons:<br> i. invariants that you have in some other part of your code<br> ii. security<br> etc</p> <p>Also, because it's a safe bet with regards to backward compatibility - you'll never be able to close that class for inheritance if it's release unsealed.</p> <p>Or maybe you didn't have enough time to test the interface that the class exposes to be sure that you can allow others to inherit from it.</p> <p>Or maybe there's no point (that you see now) in having a subclass. </p> <p>Or you don't want bug reports when people try to subclass and don't manage to get all the nitty-gritty details - cut support costs.</p>
4,426
<p>I've seen a number of questions asking about a web SVN repository-browsing tool. However, of the ones I've taken a look at, they either require a specific username/password to be configured, rely on default access to the repository being available, or require a separate user database outside Subversion.</p> <p>In a corporate setting, SVN repository admins may lock down the repository so that there isn't a "guest" or "anonymous" account that has access. And if they're using the domain username/password for access to these, it's not really a great idea to embed a real user's authentication details into a configuration file like that.</p> <p>Is there a Subversion repository browser that takes username/password information from the user and uses that to authenticate any SVN requests made on their behalf?</p> <p>EDIT: I should state that we already <em>have</em> a SVN repository served through authenticated HTTPS. We access this through thick clients like TortoiseSVN and Subclipse. I'm looking for a web-based client that provides browsing through previous revisions, diffs, and so on, but which doesn't require pre-configured authentication information to connect to the repository.</p>
<p>SVN can actually be served up through Apache and allow LDAP authentication. I've set this up before.</p> <p>There is a prepackaged windows snap-in like server that is kept current with SVN versions called VisualSVN, this is basically an SVN repository served through and apache wrapper with the LDAP modules built.</p> <p><a href="http://blogs.open.collab.net/svn/2007/03/subversion_ldap.html" rel="nofollow noreferrer">http://blogs.open.collab.net/svn/2007/03/subversion_ldap.html</a></p> <p><a href="http://www.visualsvn.com/" rel="nofollow noreferrer">http://www.visualsvn.com/</a></p> <p>This would keep you from having to maintain credentials within SVN. At least passwords.</p> <p>I must note, VisualSVN <strong>Server</strong> is freeware and requires no licensing</p>
<p>SVN can actually be served up through Apache and allow LDAP authentication. I've set this up before.</p> <p>There is a prepackaged windows snap-in like server that is kept current with SVN versions called VisualSVN, this is basically an SVN repository served through and apache wrapper with the LDAP modules built.</p> <p><a href="http://blogs.open.collab.net/svn/2007/03/subversion_ldap.html" rel="nofollow noreferrer">http://blogs.open.collab.net/svn/2007/03/subversion_ldap.html</a></p> <p><a href="http://www.visualsvn.com/" rel="nofollow noreferrer">http://www.visualsvn.com/</a></p> <p>This would keep you from having to maintain credentials within SVN. At least passwords.</p> <p>I must note, VisualSVN <strong>Server</strong> is freeware and requires no licensing</p>
29,868