instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
<p>If you simply need multiple connections, you can do something like this:</p> <pre><code>from django.db import load_backend myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle' myConnection = myBackend.DatabaseWrapper({ 'DATABASE_HOST': '192.168.1.1', 'DATABASE_NAME': 'my_database', 'DATABASE_OPTIONS': {}, 'DATABASE_PASSWORD': "", 'DATABASE_PORT': "", 'DATABASE_USER': "my_user", 'TIME_ZONE': "America/New_York",}) # Now we can do all the standard raw sql stuff with myConnection. myCursor = myConnection.cursor() myCursor.execute("SELECT COUNT(1) FROM my_table;") myCursor.fetchone() </code></pre>
<p>I think you will have to resort to "raw sql" .. kinda thing .. <br> look here: <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/topics/db/sql/</a></p> <p>you need a "connection" to your other database, if you look at <code>django/db/__init__.py</code> around line 39 (in my version ..)</p> <p><code>connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)</code></p> <p>try to take it from there ..<br> P.S. I haven't really tried this or anything .. just trying to point in the general direction of what I think might solve your problem.</p>
33,638
<p>I'm working on a web application that needs to prints silently -- that is without user involvement. What's the best way to accomplish this? It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR. The closest I've seen involves a Java applet.</p> <p>I can understand why it would a Bad Idea for just any website to be able to do this. This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc.</p>
<p>Here’s what you need to do to enable Firefox immediately print without showing the print preferences dialog box.</p> <ol> <li><p>Type about:config at Firefox’s location bar and hit Enter.</p></li> <li><p>Right click at anywhere on the page and select New > Boolean</p></li> <li><p>Enter the preference name as print.always_print_silent and click OK.</p></li> </ol> <hr> <p>I found that somewhere and it helped me</p>
<p>I have to be honest, I am kinda thinking out loud here.. But could it not be done with an applet or some sort (be it Java or whatever) that is given trusted permissions (such as that within the Intranet zone) or something?</p> <p>May be worth investigating what permissions can be given to each zone?</p> <p>Following a Google, I think you definately have a challenge, so far most of the articles I have seen involve printing to <a href="http://aspalliance.com/462" rel="nofollow noreferrer">printers connected to the server</a>.</p> <p>If its internal, would it be possible to route printing from the server to department/user printers or something?</p>
4,193
<p>One of the items in the <a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="noreferrer">Joel Test</a> is that a project/company should have a specification.</p> <p>I'm wondering what makes a spec good. Some companies will write volumes of useless specification that no one ever reads, others will not write anything down because "no one will read any of it anyway". So, what do you put into your spec? What is the good balance between the two extremes? Is there something particularly important that really, really (!) should always be recorded in a specification?</p>
<p>The best spec is one that:</p> <ol> <li>Exists</li> <li>Describes WHAT, not HOW (no solutions)</li> <li>Can be interpreted in as few ways as possible</li> <li>Is widely-distributed</li> <li>Is agreed-upon as being THE spec by all parties involved</li> <li>Is concise</li> <li>Is consistent</li> <li>Is updated regularly as requirements change</li> <li>Describes as much of the problem as is possible and practical</li> <li>Is testable</li> </ol>
<p>I think writing "Use cases" should save you bunch of pages</p>
49,703
<p>I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my <code>~/Views/Shared/Site.Master</code>):</p> <pre><code>&lt;script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with <code>~/Scripts/...</code> doesn't work. Starting with <code>/Scripts/...</code> would only work if the project was at the site root (which I don't want to assume).</p> <p>I have one working approach (I'll post below) - but: am I missing something?</p> <p>I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?</p> <p>Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:</p> <pre><code>&lt;script src="&lt;%=Url.Content("~/Scripts/jquery-1.2.6.js")%&gt;" type="text/javascript"&gt;&lt;/script&gt; </code></pre>
<p>I have a AppHelper class with some methods for adding script references: </p> <pre><code>public static string ReferenceScript(string scriptFile) { var filePath = VirtualPathUtility.ToAbsolute("~/Scripts/" + scriptFile); return "&lt;script type=\"text/javascript\" src=\"" + filePath + "\"&gt;&lt;/script&gt;"; } </code></pre> <p>so in your master page you can use:</p> <pre><code>&lt;%= AppHelper.ReferenceScript("jquery-1.2.6.js") %&gt; </code></pre>
<p>Our applications are deployed using virtual directories, and we have had some issues with other answers mentioned here (not resolving the path correctly). One way that worked well, (not the only way mind you), was to use this:</p> <pre><code>&lt;script src="&lt;%=Request.ApplicationPath%&gt;/Web/AppName/JavaScript/jquery-1.4.1.js"&gt;&lt;/script&gt; </code></pre>
45,222
<p>I am trying to build an OLAP datasource from a bunch of binary files, and our current model just isn't working. We are using SSAS as our analysis / reporting model for our results, but aren't able to get the performance we want out of SQL. </p> <p>Our main constraints are:</p> <ol> <li><p>The database is very large. We have huge dimension tables with millions of rows, and several smaller fact tables (&lt;1,000,000 rows).</p></li> <li><p>We have a dynamic cube. B/C the fact tables are built dynamically, and often (possibly multiple times per day), there can't be any huge overhead in setting up the cube. Current deploy times on the cube can exceed 24 hours, and we need orders of magnitude increase in performance which hardware just isn't gonna give us. </p></li> </ol> <p>Basically, we want a fast setup and deploy, which doesn't inherently lend itself to SSAS using SQL Server 2005, but we want to use SSRS for reporting and we want an OLAP model for analysis in Excel, so we'd still like to use SSAS to build the cube if possible. </p> <p>The common solution in SSAS for a fast deploy is ROLAP, but we are getting execution errors on larger ROLAP queries, and we also don't like all the overhead involved in converting the binary data to SQL and loading it into the cube. </p> <p>Has anyone done work on a custom OLAP datasource that SSAS can use? We are looking to create our own ROLAP engine that will query the binary source files directly.</p>
<p>If you need a low latency cube (i.e. one showing up-to-date data) the canonical architecture for such things is thus:</p> <ul> <li>Incrementally load a fact table with changed data from your source.</li> <li>Build a partitioned cube with a process that generates new partitions every day or some other suitable period. The cube has have the most recent partition set up in a ROLAP mode and the older partitions built as MOLAP.</li> <li>Set up a process that updates the partitions and changes the older partitions from ROLAP to MOLAP as it generates a new leading edge partition.</li> </ul> <p>Queries against the cube will hit the relatively small ROLAP partition for the most recent data and the MOLAP partitions for the historical data. The MOLAP partitions can have aggregations. The process keeps ticking the leading edge ROLAP partition over and converting its predecessor. AS will keep the older partition around and use it until the replacement partition is built and comes on line. </p> <p>If this type of architecture will fit your requirements you could consider doing it this way.</p>
<p>I haven't had any luck yet. We are going the route of either building our own Data Provider and building add-ins for excel to emulate the olap behavior, OR using CLR table-valued functions to emulate our data-sources and build the cube off of that. The one attempt I took at the CLR stuff had horrible performance and blew up though due to the amount of queries SSAS runs when building a cube. I am waiting to get a newer faster machine in the SQL 08 environment to see if this is feasible. Good luck Scott.</p>
16,188
<p>I am trying to write a simple networked chat program in Java. I have almost no networking experience. I was wondering what resources I should begin looking at (beside here of course).</p> <p>Sticking with the core Java API would be best for now.</p>
<p>I found a great tutorial into networking and java from sun's own website: <a href="http://download.oracle.com/javase/tutorial/networking/TOC.html" rel="noreferrer">http://download.oracle.com/javase/tutorial/networking/TOC.html</a></p> <p>The socket section even has you write a mini client / server chat demo.</p>
<p>Google is your friend. Search for "java socket programming tutorial" or something like that and you'll get lots of results, including the one suggested by zxcv as well as these:</p> <p><a href="http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html</a></p> <p><a href="http://www.cafeaulait.org/books/jnp/javanetexamples/index.html" rel="nofollow noreferrer">http://www.cafeaulait.org/books/jnp/javanetexamples/index.html</a></p>
12,064
<p>I'd like to implement a <a href="http://en.wikipedia.org/wiki/Bloom_filter" rel="noreferrer">bloom filter</a> using MySQL (other a suggested alternative).</p> <p>The problem is as follows:</p> <p>Suppose I have a table that stores 8 bit integers, with these following values:</p> <pre><code>1: 10011010 2: 00110101 3: 10010100 4: 00100110 5: 00111011 6: 01101010 </code></pre> <p>I'd like to find all results that are bitwise AND to this:</p> <pre><code>00011000 </code></pre> <p>The results should be rows 1 and 5.</p> <p>However, in my problem, they aren't 8 bit integers, but rather n-bit integers. How do I store this, and how do I query? Speed is key.</p>
<p>Create a table with int column (use <a href="http://dev.mysql.com/doc/refman/5.0/en/integer-types.html" rel="noreferrer">this link</a> to pick the right int size). Don't store numbers as a sequence of 0 and 1. </p> <p>For your data it will look like this:</p> <pre><code>number 154 53 148 38 59 106 </code></pre> <p>and you need to find all entries matching 24.</p> <p>Then you can run a query like</p> <pre><code>SELECT * FROM test WHERE number &amp; 24 = 24 </code></pre> <p>If you want to avoid convertion into 10 base numbers in your application you can hand it over to mysql:</p> <pre><code>INSERT INTO test SET number = b'00110101'; </code></pre> <p>and search like this</p> <pre><code>SELECT bin(number) FROM test WHERE number &amp; b'00011000' = b'00011000' </code></pre>
<p>For up to 64 bits, you can use a MySQL integer type, like tinyint (8b), int (16b), mediumint (24b) and bigint (64b). Use the unsigned variants.</p> <p>Above 64b, use the MySQL (VAR)BINARY type. Those are raw byte buffers. For example BINARY(16) is good for 128 bits.</p> <p>To prevent table scans you need an index per useful bit, and/or an index per set of related bits. You can create virtual columns for that, and put an index on each of them.</p>
47,092
<p>Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?</p>
<p>There are a lot of benefits:</p> <ul> <li>You get immediate feedback on if your code is working, so you can find bugs faster</li> <li>By seeing the test go from red to green, you know that you have both a working regression test, and working code</li> <li>You gain confidence to refactor existing code, which means you can clean up code without worrying what it might break</li> <li>At the end you have a suite of regression tests that can be run during automated builds to give you greater confidence that your codebase is solid</li> </ul> <p>The best way to start is to just start. There is a great <a href="https://rads.stackoverflow.com/amzn/click/com/0321146530" rel="noreferrer" rel="nofollow noreferrer">book by Kent Beck</a> all about Test Driven Development. Just start with new code, don't worry about old code... whenever you feel you need to refactor some code, write a test for the existing functionality, then refactor it and make sure the tests stay green. Also, read <a href="http://devver.wordpress.com/2008/07/07/tips-for-unit-testing/" rel="noreferrer">this great article</a>.</p>
<p>In my opinion, the single greatest thing is that it clearly allows you to see if your code does what it is supposed to. This may seem obvious, but it is super easy to run astray of your original goals, as I have found out in the past :p</p>
2,630
<p>For a stylesheet I'm writing (actually for a set of them, each generating a different output format), I have the need to evaluate whether a certain value is present in a list of values. In this case, the value being tested is taken from an element's attribute. The list it is to be tested against comes from the invocation of the stylesheet, and is taken as a top-level <code>&lt;xsl:param&gt;</code> (to be provided on the command-line when I call <code>xsltproc</code> or a Saxon equivalent invocation). For example, the input value may be:</p> <pre><code>v0_01,v0_10,v0_99 </code></pre> <p>while the attribute values will each look very much like <em>one</em> such value. (Whether a comma is used to separate values, or a space, is not important-- I chose a comma for now because I plan on passing the value via command-line switch to <code>xsltproc</code>, and using a space would require quoting the argument, and I'm lazy-enough to not want to type the extra two characters.)</p> <p>What I am looking for is something akin to Perl's <code>grep</code>, wherein I can see if the value I currently have is contained in the list. It can be done with sub-string tests, but this would have to be clever so as not to get a false-positive (<code>v0_01</code> should not match a string that contains <code>v0_011</code>). It seems that the only non-scalar data-type that XSL/XSLT supports is a node-set. I suppose it's possible to convert the list into a set of text nodes, but that seems like over-kill, even compared to making a sub-string test with extra boundaries-checking to prevent false matches.</p>
<p>Actually, using XPath string functions is the right way to do it. All you have to make sure is that you test for the delimiters as well:</p> <pre><code>contains(concat(',' $list, ','), concat(',', $value, ',')) </code></pre> <p>would return a Boolean value. Or you might use one of these:</p> <pre><code>substring-before(concat('|,' $list, ',|'), concat(',', $value, ',')) </code></pre> <p>or</p> <pre><code>substring-after(concat('|,' $list, ',|'), concat(',', $value, ',')) </code></pre> <p>If you get an empty string as the result, <code>$value</code> is not in the list.</p> <p>EDIT: </p> <p>@Dimitre's comment is correct: <code>substring-before()</code> (or <code>substring-after()</code>) would also return the empty string if the found string is the first (or the last) in the list. To avoid that, I added <em>something</em> at the start and the end of the list. Still <code>contains()</code> is the recommended way of doing this.</p>
<p>In addition to the XPath 1.0 solution provided by Tomalak, <br /> <br /> <strong>Using XPath 2.0</strong> one can tokenize the list of values:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong><code>exists(tokenize($list, ',')[. = $value])</code></strong></p> <p>evaluates to <code>true()</code> if and only if <code>$value</code> is contained in the list of values <code>$list</code></p>
46,423
<p>I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?</p>
<p>In the System.pas (which automatically gets used) the following is defined:</p> <pre><code>const sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF}; </code></pre> <p>This is from Delphi 2009 (notice the use of AnsiChar and AnsiString). (Line wrap added by me.)</p> <p>So if you want to make your TLabel wrap, make sure AutoSize is set to true, and then use the following code:</p> <pre><code>label1.Caption := 'Line one'+sLineBreak+'Line two'; </code></pre> <p>Works in all versions of Delphi since sLineBreak was introduced, which I believe was Delphi 6.</p>
<p>Sometimes I don't want to clutter up my code space, especially for a static label. To just have it defined with the form, enter the label text on the form, then right click anywhere on the same form. Choose "View as Text". You will now see all of the objects as designed, but as text only. Scroll down or search for your text. When you find it, edit the caption, so it looks something like: </p> <p>Caption = 'Line 1'#13'Line 2'#13'Line 3'</p> <p>#13 means an ordinal 13, or ascii for carriage return. Chr(13) is the same idea, CHR() changes the number to an ordinal type. </p> <p>Note that there are no semi-colon's in this particular facet of Delphi, and "=" is used rather than ":=". The text for each line is enclosed in single quotes. </p> <p>Once you are done, right-click once again and choose "View as Form". You can now do any formatting such as bold, right justify, etc. You just can't re-edit the text on the form or you will lose your line breaks.</p> <p>I also use "View as Text" for multiple changes where I just want to scroll through and do replacements, etc. Quick.</p> <p>Dave</p>
31,737
<p>I have inherited a monster.</p> <p>It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.</p> <p>To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.</p> <p>This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.</p> <p>My question is, what methods would you suggest to refactor or restructure such a thing?</p> <p>I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.</p> <p>Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.</p> <p>Thanks for any and all ideas.</p>
<p>I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.</p> <p>There is no one thing that will get you out of this. The <a href="http://en.wikipedia.org/wiki/Finite_state_machine" rel="noreferrer">state machine</a> might be the final form your code takes, but thats <em>not</em> going to help you get there, nor should you decide on such a solution before untangling the mess you already have.</p> <p>First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test. </p> <p>Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.</p> <p>Now Refactor!</p> <p>A couple things I did that i found useful:</p> <p><strong>Invert <code>if</code> statements</strong> </p> <p>A huge problem I had was just reading the code when I couldn't find the corresponding <code>else</code> statement, I noticed that a lot of the blocks looked like this</p> <pre><code>if (someCondition) { 100+ lines of code { ... } } else { simple statement here } </code></pre> <p>By inverting the <code>if</code> I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.</p> <p><strong>Extract Method</strong></p> <p>I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.</p> <p>Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood <em>procedural</em> code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).</p> <p>Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0321213351" rel="noreferrer" rel="nofollow noreferrer">Refactoring to Patterns</a> is a great book to assist in explainging patterns that are helpful in these situations.</p> <p>You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.</p>
<p>Judging by the description, a state machine might be the best way to deal with it. Have an enum variable to store the current state, and implement the processing as a loop over the records, with a switch or if statements to select the action to take based on the current state and the input data. You can also easily dispatch the work to separate functions based on the state using function pointers, too, if it's getting too bulky.</p>
13,106
<p>In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)</p>
<p>Took me some time to work it out, but after being pointed in the right direction by Otherside, I finally got it (works for version 5.2):</p> <pre><code>[Code] var MyCustomPage : TWizardPage; procedure MyEditField_OnChange(Sender: TObject); begin MsgBox('TEST', mbError, MB_OK); end; function MyCustomPage_Create(PreviousPageId: Integer): Integer; var MyEditField: TEdit; begin MyCustomPage := CreateCustomPage(PreviousPageId, 'Caption', 'Description'); MyEditField := TEdit.Create(MyCustomPage); MyEditField.OnChange := @MyEditField_OnChange; end; </code></pre>
<p>Since the scripting in innosetup is loosely based on Delphi, the controls should have some events like <code>OnEnter</code> (= control got focus) and <code>OnExit</code> (= control lost focus). You can assign procedures to these events, something like this: ComboBox.OnExit := ComboBoxExit;</p> <pre><code>procedure ComboBoxExit(Sender: TObject); begin end; </code></pre> <p>I don't have access to Innosetup right now, so you will need to lookup the available events and parameters for the procedures.</p>
16,858
<p>What is WCF in simple terms?</p> <p>It's hard to distill the meaning from <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="noreferrer">the Wikipedia page</a>.</p>
<p>WCF - <a href="http://msdn.microsoft.com/en-us/library/ms731082.aspx" rel="noreferrer">Windows Communication Framework</a> - is Microsoft's framework to make inter-process communication easier. It let's you do this communication through various means, plain old asmx web services, Remoting, MS Message Queuing, and a couple more.</p> <p>It let's you talk with other .NET apps, or non-Microsoft technologies (like J2EE). It's extensible enough to allow for newer stuff, like REST too (I don't think REST is built-in).</p>
<p>WCF is Microsoft's new .NET do-all extensible communications framework meant to replace functionality previously available in <a href="http://en.wikipedia.org/wiki/Distributed_Component_Object_Model" rel="nofollow noreferrer">DCOM</a>, <a href="http://en.wikipedia.org/wiki/.NET_Remoting" rel="nofollow noreferrer">.NET Remoting</a> and ASMX web services.</p>
6,430
<p>I have a solution which contains many class libraries and an ASP .NET website which references those assemblies.</p> <p>When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great!</p> <p>When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why?</p> <p>My command line is simply:</p> <pre><code>msbuild.exe d:\myproject\mysolution.sln </code></pre>
<p>I have found various references to this problem scattered around the Net - and I've just come across it myself. Apparently MSBuild on the command line isn't as good at tracing chains of dependencies as the IDE is.</p> <p>So as I understand it, if A depends on B which depends on C, The command line may not realize that A depends on C. </p> <p>The only solution I've found is to ensure that you manually set the project dependencies so that the ASP project references everything it depends on - don't expect it to be able to figure them all out on the command line. This has worked for me, although I only have 5 projects so it's not a bind to get going.</p> <p>I hope this helps.</p>
<p>If I recall, MSBuild dosen't copy the referenced assemblies. I've posted a "solution" a while ago: <a href="http://www.brunofigueiredo.com/post/Issue-Tracker-part-IV-The-Build-Enviroment-using-MSBuild-(or-NAnt).aspx" rel="nofollow noreferrer">http://www.brunofigueiredo.com/post/Issue-Tracker-part-IV-The-Build-Enviroment-using-MSBuild-(or-NAnt).aspx</a></p> <p>Hope it helps.</p>
34,260
<p>Do you put unit tests in the same project for convenience or do you put them in a separate assembly?</p> <p>If you put them in a separate assembly like we do, we end up with a number of extra projects in the solution. It's great for unit testing while coding but how do you release the application without all of these extra assemblies?</p>
<p>In my opinion, unit tests should be placed in a separate assembly from production code. Here are just a few cons of placing unit tests in the same assembly or assemblies as production code are:</p> <ol> <li>Unit tests get shipped with production code. The only thing shipped with product code is production code.</li> <li>Assemblies will be unnecessarily bloated by unit tests.</li> <li>Unit tests can affect build processes like automated or continuous build. </li> </ol> <p>I don't really know of any pros. Having an extra project (or 10) isn't a con.</p> <p><strong>Edit: More Info On Build and Shipping</strong></p> <p>I would further recommend that any automated build process place production and unit tests into different locations. Ideally, the unit test build process only runs if the production code builds, and copies the product files into the unit tests directory. Doing it this way results in the actual bits being separated for shipping, etc. Additionally, it is fairly trivial to run automated unit testing at this point on all tests in a particular directory.</p> <p>To summarize, here is the general idea for a daily build and testing and shipping of bits and other files:</p> <ol> <li>Production build runs, placing production files into a specific "production" directory. <ol> <li>Build production projects only.</li> <li>Copy compiled bits and other files into a "production" directory.</li> <li>Copy bits and other files into a release candidate directory, aka a Christmas release directory would be "Release20081225".</li> </ol></li> <li>If production build succeeds, unit test build runs. <ol> <li>Copy production code to "tests" directory.</li> <li>Build unit tests to "tests" directory.</li> <li>Run unit tests.</li> </ol></li> <li>Send build notifications and unit tests results to developers.</li> <li>When a release candidate (like Release20081225) is accepted, ship these bits.</li> </ol>
<blockquote> <p>Do you put unit tests in the same project for convenience or do you put them in a separate assembly?</p> </blockquote> <p><strong>No, never, ever do that</strong>. The consumers of your component cannot separate your test code from your production code and therefore, they cannot use it for anything non-trivial.</p> <p>From the perspective of a security minded consumer, every public symbol in your assembly is part of the attack surface area of your customer's products. Why would they want to use an assembly that includes <em>any</em> non-production security surface area?</p> <p><strong>SHAME ON YOU IF YOU THINK IT'S OKAY TO INCLUDE UNIT TESTS IN PRODUCTION ASSEMBLIES!</strong></p> <p>And shame on you if you accept such assemblies for inclusion in your products.</p> <hr /> <p>Is it okay to publish your test assemblies? Of course it is, and I consider it to be a best practice. They can be a great aid to customer support, and your customers might also want to incorporate them into their own test environments. Just don't force your test bits on your customers.</p>
45,170
<p>I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?</p> <p>More info: So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?</p>
<p>Most likely you've seen code which protects against "extra" incoming data. This is often due to the possibility of buffer overruns, where the extra data being copied into memory overruns the pre-allocated array and overwrites executable code with attacker code. Code written in languages like C typically has a lot of length checking to prevent this type of attack. Functions such as gets, and strcpy are replaced with their safer counterparts like fgets and strncpy which have a length argument to prevent buffer overruns.</p> <p>If you use a dynamic language like Python, your arrays resize so they won't overflow and clobber other memory, but you still have to be careful about sanitizing foreign data.</p> <p>Chat programs likely limit the size of a message for reasons such as database field size. If 80% of your incoming messages are 40 characters or less, 90% are 60 characters or less, and 98% are 80 characters or less, why make your message text field allow 10k characters per message?</p>
<p>I don't know what your actual application is, however, setting a hard limit on the total amount of data that a client can send could be useful in reducing your exposure to denial of service attacks, e.g. client connects and sends 100MB of data which could load your application unacceptably.</p> <p>But it really depends on what you application is. Are you after a per line limit or a total per connection limit or what?</p>
24,927
<p>From time to time I browse the web and look for interesting algorithms and datastructures to put into my bag of tricks. A year ago I came across the <a href="http://en.wikipedia.org/wiki/Soft_heap" rel="noreferrer">Soft Heap</a> data-structure and learned about near sorting.</p> <p>The idea behind this is that it's possible to break the O(n log n) barrier of compare based sorts if you can live with the fact that the sort algorithm cheats a bit. You get a almost sorted list but you have to live with some errors as well.</p> <p>I played around with the algorithms in a test environement but never found a use for them. </p> <p>So the question: Has anyone ever used near sorting in practice? If so in which kind of applications? Can you think up a use-case where near sorting is the right thing to do? </p>
<p>This is a total flying guess, but given the inherent subjectivity of "relevance" measures when sorting search results, I'd venture that it doesn't really matter whether or not they're perfectly sorted. The same could be said for recommendations. If you can somehow arrange that every other part of your algorithm for those things is O(n) then you might look to avoid a sort.</p> <p>Be aware also that in the worst case your "nearly sorted" data <em>does not</em> meet one possible intuitive idea of "nearly sorted", which is that it has only a small number of inversions. The reason for this is just that if your data has only O(n) inversions, then you can finish sorting it in O(n) time using insertion sort or cocktail sort (i.e. two-way bubble sort). It follows that you cannot possibly have reached this point from completely unsorted, in O(n) time (using comparisons). So you're looking for applications where a majority subset of the data is sorted and the remainder is scattered, <em>not</em> for applications requiring that every element is close to its correct position.</p>
<p>O(n log n) is already pretty fast. I don't think anyone would ever <em>start out</em> using a near-sort algorithm. You would start out with code that just does a complete sort (since your programming language of choice likely provides a <code>sort</code> function and not a <code>nearsort</code> function), and when you found empirically that the sort was taking too long, you would start to question whether your data <em>really</em> needs to be fully-sorted, and consider using a near-sort.</p> <p>Basically, you would never even consider using a near sort unless you first discovered sorting to be a severe bottleneck in your program.</p>
17,596
<p>What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?</p>
<p>You could do this fairly simply with refspecs.</p> <pre><code>git pull origin git diff @{1}.. </code></pre> <p>That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:</p> <pre><code>current=`git rev-parse HEAD` git pull origin git diff $current.. </code></pre> <p>I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:</p> <pre><code>git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}.. </code></pre>
<p>If you drop this into your bash profile you'll be able to run grin (git remote incoming) and grout (git remote outgoing) to see diffs of commits that are incoming and outgoing for origin master.</p> <pre><code>function parse_git_branch { git branch --no-color 2&gt; /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/' } function gd2 { echo branch \($1\) has these commits and \($2\) does not git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local } function grin { git fetch origin master gd2 FETCH_HEAD $(parse_git_branch) } function grout { git fetch origin master gd2 $(parse_git_branch) FETCH_HEAD } </code></pre>
8,611
<p>In XNA, how do I load in a texture or mesh from a file without using the content pipeline?</p>
<p>I believe Texture2D.FromFile(); is what you are looking for.</p> <p>It does not look like you can do this with a Model though.</p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d.fromfile.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d.fromfile.aspx</a></p>
<p>If you really want to load an Xna <code>Xna.Framework.Graphics.Model</code> on PC without the content pipeline (eg for user generated content), there is a way. I used SlimDX to load an X file, and avoid the parsing code, the some reflection tricks to instantiate the Model (it is sealed and has a private constructor so wasn't meant to be extended or customised). See here: <a href="http://contenttracker.codeplex.com/SourceControl/changeset/view/20704#346981" rel="nofollow">http://contenttracker.codeplex.com/SourceControl/changeset/view/20704#346981</a></p>
12,115
<p>In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in <code>$arrayOfStringsNotInterestedIn</code>.</p> <p>What is the syntax for this?</p> <pre><code> Get-Content $filename | Foreach-Object {$_} </code></pre>
<p>If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:</p> <pre><code>Get-Content $FileName | foreach-object { ` if ($arrayofStringsNotInterestedIn -notcontains $_) { $) } </code></pre> <p>or better (IMO)</p> <pre><code>Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_} </code></pre>
<p>To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:</p> <pre><code>(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn) </code></pre> <p>The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.</p>
10,058
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
<p>For a regular expression, you would use:</p> <pre><code>re.match(r'Run.*\.py$') </code></pre> <p>A quick explanation:</p> <ul> <li>. means match any character.</li> <li>* means match any repetition of the previous character (hence .* means any sequence of chars)</li> <li>\ is an escape to escape the explicit dot</li> <li>$ indicates "end of the string", so we don't match "Run_foo.py.txt"</li> </ul> <p>However, for this task, you're probably better off using simple string methods. ie.</p> <pre><code>filename.startswith("Run") and filename.endswith(".py") </code></pre> <p>Note: if you want case insensitivity (ie. matching "run.PY" as well as "Run.py", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.</p>
<p>This probably doesn't fully comply with file-naming standards, but here it goes:</p> <pre><code>/^Run[\w]*?\.py$/ </code></pre>
22,415
<p>When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.</p> <p>I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.</p> <p>FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.</p> <p>Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.</p> <p>Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned <code>&lt;div&gt;</code> as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible <code>&lt;iframe&gt;</code> inside the <code>&lt;div&gt;</code> and styling it with:</p> <pre class="lang-css prettyprint-override"><code>#MyDiv iframe { position: absolute; z-index: -1; filter: mask(); border: 0; margin: 0; padding: 0; top: 0; left: 0; width: 9999px; height: 9999px; overflow: hidden; } </code></pre> <p>Does anyone have an even better solution than this one?</p> <p>EDIT: The purpose of this question is as much informative as it is a real question. I find the <code>&lt;iframe&gt;</code> trick to be a good solution, but I am still looking for improvement like removing this <em>ugly useless tag</em> that degrades accessibility.</p>
<p>I don't know anything better than an Iframe</p> <p>But it does occur to me that this could be added in JS by looking for a couple of variables </p> <ol> <li>IE 6</li> <li>A high Z-Index (you tend to have to set a z-index if you are floating a div over)</li> <li>A box element</li> </ol> <p>Then a script that looks for these items and just add an iframe layer would be a neat solution</p> <p>Paul</p>
<p>I don't think there is. I've tried to solve this problem at my job. Hiding the select control was the best we could come up with (being a corporate shop with a captive audience, user experience doesn't usually factor into the PM's decisions). </p> <p>From what I could gather online when looking for a solution, there's just no good solution to this. I like the FogBugz solution (the same thing done by a lot of high-profile sites, like Facebook), and this is actually what I use in my own projects.</p>
2,949
<p>It's a part of larger code base, which forces -Werror on gcc. This warning is generated in a third party code that shouldn't be changed (and I actually know how to fix it), but I can disable specific warnings. This time man gcc failed me, so please, let some gcc master enlighten me. TIA.</p>
<p>It is the <em>-Wno-unused-value</em> option, see the <a href="http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options" rel="nofollow noreferrer">documentation</a></p>
<p>Have you tried using a <a href="http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html" rel="nofollow noreferrer">diagnostic pragma</a> directive? These are available in gcc 4.2.1+, I believe.</p>
13,664
<p>Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no longer responding" message.</p> <p>Console applications work fine, and my Swing code works fine when launching from Netbeans or from the command line. I'm running Windows Vista x64 with the JDK 1.6 Update 10 beta, which may be a configuration the Jetbrains guys haven't run into yet.</p>
<p>Ask your question directly on the IDEA website. They always react fast and the problem you have is probably either fixed or documented.</p>
<p>IDEA 8 Milestone 1 is a beta(ish) "based on a new platform". This may have changed the way that swing is handled. Also you are running a beta JDK.</p> <p>You will probably get more help/submit a bug at the Jetbrain forums unless they are on SO also. <a href="http://www.jetbrains.net/jira/browse/IDEA/" rel="nofollow noreferrer" title="Jetbrains jira tracker">Here is the bug tracker link</a></p>
4,185
<p>I have a controller that returns either JSON or partial html depending on if the user is logged in. </p> <p>Is there anyway to tell the difference once the result has been returned?? What is the best way.</p> <p>Obviously i have different actions to complete if the response is json or if it is the partial html. With the json one i do a redirect to the login page, and with the html one i just display it. If only i could render the html server side and send it back in json format?? From what i have heard this cannot be done as yet. Thoughts?</p> <p>Cheers.</p> <p><strong>DUPLICATE: <a href="https://stackoverflow.com/questions/291466/can-i-evaluate-the-response-type-of-an-ajax-call-in-success-callback">Can I evaluate the response type of an $.ajax() call in success callback?</a></strong></p>
<p>You could use <a href="http://www.devpro.it/JSON/files/JSON-js.html" rel="nofollow noreferrer">JSON.js</a> to find out if a given string is JSON or not. </p> <blockquote> <p><strong>JSON encoder / decoder</strong><br> This object uses good practices to encode/decode every kind of JSON compatible variable quickly and a bit safer.</p> </blockquote> <p>It provides a <code>decode()</code> function that returns either an object or <code>undefined</code>.</p>
<p>I'd say, assuming you have control of the thing returning JSON or partial HTML, that you should change the Content-Type header of the JSON result to something like <code>application/x-format-json</code> or an equally obvious type.</p>
40,433
<h3>Background</h3> <p>I work for a large organization which has thousands of MS Access applications floating around. I didn't write any of these - in fact, most of the original authors have long since left the company - but from time to time another Access app lands on my desk for support. I would <em>soooo</em> love to replace access with a different solution.</p> <h3>Requirement</h3> <p>I know that there are several good alternatives for the database part of MS Access (the Jet database), such as SQLite, MySQL, VistaDB, etc.</p> <p>What I would like to know is: Is there anything that will replace the front end part of MS Access?</p> <p>I.e. Something which can be used to build forms, write simple scripts and queries, etc?</p> <h3>Why?</h3> <p>@BracC asked &quot;why replace access?&quot; - A fair question indeed.<br /> I want to get rid of access because:</p> <ul> <li>it hides logic, leading to hard-to-support applications. Logic can be in lots of different places, none of which provide or encourage any structure: <ul> <li>macros</li> <li>modules</li> <li>queries</li> <li>forms</li> </ul> </li> <li>its very nature encourages users to create &quot;little&quot; applications which become &quot;not so little applications&quot;. Then the user leaves and I have to support a bunch of spaghetti. I know that access isn't the only culprit, but it's the leader in my organisation, and I would love to get rid of it completely.</li> </ul> <h3>For extra credit</h3> <p>what I would <em>really</em> love to find is something which can read in an MDB file and output something like C# which replicates the functionality. (Or any language - not fussy).</p> <p>I hope this is all clear. If not, please post a comment and I'll re-write/add detail.</p> <h3>Update</h3> <p>@GuinnessFan makes some points I find interesting. I have added my comments to discuss those points.</p> <p>What we have done since I asked the question:</p> <ul> <li>Got users to give us a definitive list of access applications they use and need. (The understanding is that any MDB files not on the list can be deleted - hooray!).</li> <li>Analysed the MDBs on the list, coming to the following conclusions: <ul> <li>Most of the &quot;applications&quot; consist of a single hard-coded query or a single linked table.</li> <li>Many are a small number of queries with, perhaps, a date parameter or similar.</li> <li>very few (if any) have any truly complex logic.</li> </ul> </li> <li>We are now working through the list, converting most of the apps to SSRS (SQL Server Reporting Services) packages.</li> <li>Anything which can't be replicated using SSRS will become a hand-crafted web application. However, there aren't many of these.</li> </ul> <p>May I say many thanks, to <em><strong>everybody</strong></em> who has given me helpful answers.</p>
<p>You could check out <a href="http://apex.oracle.com/i/index.html" rel="noreferrer">Oracle's Application Express</a>. It's free and it's geared toward Access developers.</p> <p>It has a migration assistant as well that you run your Access database through, it proccesses the data and the forms, migrates everything to an Oracle Database (this works with the free database, Oracle XE, and comes install by default) and builds web forms for your Access database.</p> <p>So in the end you'll have your Access databases on the web, your data in Oracle and somewhat nice web front end for extending them.</p> <p>As far as Oracle goes, the tool isn't half bad. You can sign up for a free instance to play around with <a href="http://apex.oracle.com/pls/otn/f?p=4700:1:194910063149485:::::" rel="noreferrer">here</a>.</p> <p><a href="http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e12854/toc.htm" rel="noreferrer">Here's the document that explains how you migrate Access Databases.</a></p>
<blockquote> <p>Is there anything that will replace the front end part of MS Access?</p> </blockquote> <p>Maybe <a href="http://www.kexi-project.org/" rel="nofollow noreferrer">Kexi</a>?</p>
27,374
<p>Why am I getting an out of memory exception?</p> <p>So this dies in C# on the first time through:</p> <p><strong>splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));</strong> </p> <p>Where splitBitmaps is a List&lt;BitMap&gt; BUT this works in VB for at least 4 iterations:</p> <p><strong>arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))</strong></p> <p>Where arlSplitBitmaps is a simple array list. (And yes I've tried arraylist in c#)</p> <p>This is the fullsection:</p> <pre><code>for (Int32 splitIndex = 0; splitIndex &lt;= numberOfResultingImages - 1; splitIndex++) { Rectangle rectDimensions; if (splitIndex &lt; numberOfResultingImages - 1) { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, splitImageWidth, splitImageHeight); } else { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight); } splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat)); </code></pre> <p>} </p> <p>neededImage is a Bitmap by the way. </p> <p>I can't find any useful answers on the intarweb, especially not why it works just fine in VB.</p> <p><strong>Update:</strong></p> <p>I actually found a reason (sort of) for this working but forgot to post it. It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.</p>
<p>Clone() may also throw an Out of memory exception when the coordinates specified in the Rectangle are outside the bounds of the bitmap. It will not clip them automatically for you.</p>
<p>Make sure that you're calling .Dispose() properly on your images, otherwise unmanaged resources won't be freed up. I wonder how many images are you actually creating here -- hundreds? Thousands?</p>
24,309
<p>I see this from time to time and want to know what it is. I did try google, but its filtering out the characters from the search. I have a few books that don't reference it either. </p> <p>FWIW, I remember in pascal that is was the assignment operator. </p> <p>Can anybody point me to the MSDN or similar page?</p>
<p>You can use the := syntax to assign the parameters to a Sub or Function by name, rather than strictly by position. For example:</p> <pre><code>Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TestRoutine(Y:="TestString", X:=12) End Sub Private Sub TestRoutine(ByVal X As Long, Optional Y As String = "") ' Do something with X and Y here... ' End Sub End Class </code></pre> <p>Note that TestRoutine specifies X as the first parameter, and Y as the second, but the call in Form1_Load has them in the opposite order, naming each parameter with the := operator.</p> <p>Here's a link to an MSDN article on the subject:</p> <p><a href="http://msdn.microsoft.com/en-us/library/51wfzyw0.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/51wfzyw0.aspx</a></p> <p>I don't see this used very often, except in VBA macros generated by Excel's macro recorder, which uses it <strong><em>a lot</em></strong>.</p>
<p>VB uses that operator for attribute value assignments:</p> <p><a href="http://www.ondotnet.com/pub/a/dotnet/excerpt/vbnut_8/index1.html" rel="nofollow noreferrer">http://www.ondotnet.com/pub/a/dotnet/excerpt/vbnut_8/index1.html</a></p>
38,843
<p>I have see code like this</p> <pre><code>Dim s as something = new something Dim s as new something </code></pre> <p>what's the difference? is there any?</p>
<p>A slight difference.</p> <p>The first allows you to do:</p> <pre><code>Dim s as ParentType = new InheritedType </code></pre> <p>The second doesn't.</p> <p>The "advantage" of this is <code>s</code> can be a number of different types related to ParentType without it exploding at runtime.</p>
<p>I believe all you're doing is specifically casting something as something.</p>
41,577
<p>I need more than the default diff! I have recently purchased "Beyond Compare" and I'd like to integrate it with svn, so its launched when I type:</p> <p>svn diff foo.c</p> <p>How do I do this?</p>
<p>From a <a href="http://www.scootersoftware.com/vbulletin/showthread.php?t=41520" rel="noreferrer">Beyond Compare forum post</a>:</p> <p>/usr/bin/bcompare_svn:</p> <pre><code>#!/bin/bash /usr/bin/bcompare $6 $7 &amp; exit 0 </code></pre> <p>The invocation of bcompare is obvious but I had to add "exit 0" so that svn would open more than one file at a time.</p> <p>To make svn invoke my script, I added the following line in the [helpers] section in ~/.subversion/config</p> <pre><code>diff-cmd=/usr/bin/bcompare_svn </code></pre>
<p>I recently added instructions for Subversion on Linux to our <a href="http://www.scootersoftware.com/support.php?zz=kb_vcs.php" rel="nofollow noreferrer">Using Beyond Compare With Version Control Systems</a> web page. Once you follow the steps at the above link it should launch Beyond Compare 3 for Linux when you run "svn diff".</p>
36,111
<p>I have a controller action that is being executed by a link that was created using 'Ajax.ActionLink()' the problem is that I can't tell in my action that the request is an AJAX request because <code>Request.IsMvcAjaxRequest()</code> is always returning false.</p> <p>Does <code>Request.IsMvcAjaxRequest()</code> not work with <code>Ajax.ActionLink()</code> generated requests?</p> <p>Here is the code I am using to generate my link:</p> <pre><code>&lt;%= Ajax.ActionLink("Delete", "Delete", new { graphUri = ViewData.Model.Uri.Value }, new AjaxOptions { Confirm = "Really delete?", OnSuccess = "success", OnFailure = "fail", HttpMethod = "DELETE" }, new { title = "Delete Graph", @class = "deleteGraphLink" })%&gt; </code></pre> <p>When I look at the code for the <a href="http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266442&amp;changeSetId=17272" rel="nofollow noreferrer"><code>IsMvcAjaxRequest</code> extension method</a> it looks like it will only work for AJAX Forms and not for AJAX ActionLinks.</p> <p><strong>Update 11/13</strong></p> <p>If I change the HttpMethod in the AjaxOptions to POST, all is well. Anyone know how to get Request.IsMvcAjaxRequest() to work properly when you are using the DELETE method?</p>
<p>There are no form parameters on a delete. Try adding __MVCASYNCPOST=true as route data (query parameter in the url)</p>
<p>Because "IsMvcAjaxRequest" just returns (request["__MVCASYNCPOST"] == true), and that checks the query string, form post and cookies... it should work with POST,GET,etc.</p> <p>Try putting a break point in your code behind and making sure it's hitting for the POST, then change to "DELETE" and see if it's hitting your code then (because this should work). It might be that you have an ActionFilter that's only allowing "POSTS" to get through (or something else that is thwarting the behavior).</p>
36,805
<p>What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".</p>
<p>There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.</p> <p>The number of sessions the database was configured to allow</p> <pre><code>SELECT name, value FROM v$parameter WHERE name = 'sessions' </code></pre> <p>The number of sessions currently active</p> <pre><code>SELECT COUNT(*) FROM v$session </code></pre> <p>As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.</p>
<pre><code>select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER' </code></pre>
19,625
<p>I am a Winforms and business engine developer who is using asp.net for the first time in over 2 years, and in that time I have noticed a few convention changes.</p> <p>What is the logic behind the anti-'tables for layout' movement?</p> <p>Is it to allow css classes to be used to handle layout, and if so, should this really be an issue on pages you are fairly sure will remain static, or is it just considered 'ugly'?</p>
<p>A few additional points:</p> <ul> <li><p>Don't be a fanatic about it. CSS isn't perfect, and there are some things that can be done much easier with tables. So if you need to, put a little table in there. It won't kill you.</p></li> <li><p>The major "evil" of table-based layouts was the kind of deeply-nested mess that used to be the only way to get precise control over the page. You would have tables within tables within tables, and transparent images strategically placed to control spacing. I think this is pretty rare nowadays, and CSS will let you clean up 90% of this mess.</p></li> <li><p>The "semantic web", where tags are there to give meaning to the page, not to describe the layout, is a good goal. However, the current version of HTML doesn't go very far toward reaching it. As a result, you will ALWAYS have plenty of tags in your pages that are just there for layout, with no other meaning. That doesn't mean you shouldn't try to separate content and layout as much as possible; it just means you won't get there 100%.</p></li> </ul>
<p>Honestly, don't worry that much about using tables. Even some of the best, most semantically correct people advise using tables if it's easier for the flow of the document. Just use what works for - the dissadvantage to using tables isn't all that great.</p>
40,416
<p>Is there a way to pass null arguments to C# methods (something like null arguments in c++)?</p> <p>For example:</p> <p>Is it possible to translate the following c++ function to C# method:</p> <pre><code>private void Example(int* arg1, int* arg2) { if(arg1 == null) { //do something } if(arg2 == null) { //do something else } } </code></pre>
<p>Yes. There are two kinds of types in .NET: reference types and value types.</p> <p>References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.</p> <p>Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.</p> <p>The usage is slightly different, though.</p> <pre><code>// Both of these types mean the same thing, the ? is just C# shorthand. private void Example(int? arg1, Nullable&lt;int&gt; arg2) { if (arg1.HasValue) DoSomething(); arg1 = null; // Valid. arg1 = 123; // Also valid. DoSomethingWithInt(arg1); // NOT valid! DoSomethingWithInt(arg1.Value); // Valid. } </code></pre>
<p>Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?</p> <p>e.g.</p> <pre><code>private void Example(int? arg1, int? arg2) { if(arg1 == null) { //do something } if(arg2 == null) { //do something else } } </code></pre>
34,158
<p>I have a project that uses a class library for the business layer functionality (database access, etc.). A web application sits on top of this. I have a web service that I would like to call in the class library. Every time I add a 'service reference' (I am using VS2008) to the class library, everything seems to work OK. The name of the web service is 'EmployeeService'. However, when I try to access it from code, intellisense gives me options like: </p> <p>'EmployeeServiceSoap'</p> <p>'EmployeeServiceSoapChannel'</p> <p>'EmployeeServiceSoapClient'</p> <p>and lots of '...Request'</p> <p>'...RequestBody'</p> <p>'...RequestResponse' types. </p> <p>I can't access my EmployeeService class even if I write it anyway the compiler will complain. Any ideas? Thanks for any help...</p>
<p>You're supposed to use the <code>EmployeeServiceSoapClient</code> to access the service. The Service class itself sits on the server.</p>
<p>You're supposed to use the <code>EmployeeServiceSoapClient</code> to access the service. The Service class itself sits on the server.</p>
46,164
<p>By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)?</p> <p>Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question: Is there a way to include the current username in the path to the netbeans setting directory? </p> <p>I want to do something like this:</p> <pre><code>netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta" </code></pre> <p>but I can't figure out the name of the variable to use (if there's any). Of course I can achieve the same thing with the --userdir option, I'm just curious.</p>
<p>yes, edit the netbeans.conf file under %NETBEANS_HOME%\etc.</p> <p>Edit the line with: netbeans_default_userdir="${HOME}/.netbeans/6.0"</p> <p>If you need different "profiles"--i.e. want to run different copies of Netbeans with different home directories, you can pass a new home directory to the launcher. Run "netbeans.exe --userdir /path/to/dir" or "nb.exe --userdir /path/to/dir"</p>
<p>"HOME" is the only variable supported by the IDE. When deploying a custom application using the Netbeans Platform, "APPNAME" is also supported out of the box.</p>
14,184
<p>I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:</p> <pre><code>class Consumer { private: vector&lt;char&gt; read(size_t n) { // If the internal buffer has `n` elements, then dequeue them // Otherwise wait for more data and try again } public: void run() { read(10); read(4839); // etc } void feed(const vector&lt;char&gt; &amp;more) { // Safely queue the data // Notify `read` that there is now more data } }; </code></pre> <p>In this case, <code>feed</code> and <code>run</code> will run on separate threads and <code>read</code> should be a blocking read (like <code>recv</code> and <code>fread</code>). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform <code>read</code> to try again.</p> <p>I hear <strong>condition variables</strong> are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them. </p> <p>Thanks for any help!</p> <p>(Yes, I know it's inefficient to return vectors. Let's not get into that.)</p>
<p>This code is not production ready. No error checking is done on the results of any library calls.</p> <p>I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it.</p> <p>In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can cot be abused inside other methods of Consumer. But as long as you take note that the lock must be acquired before you use the condition variable (in any way) then this simple situation can stand as is.</p> <p>Out of interest have you checked the boost threading library?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;pthread.h&gt; class LockThread { public: LockThread(pthread_mutex_t&amp; m) :mutex(m) { pthread_mutex_lock(&amp;mutex); } ~LockThread() { pthread_mutex_unlock(&amp;mutex); } private: pthread_mutex_t&amp; mutex; }; class Consumer { pthread_mutex_t lock; pthread_cond_t cond; std::vector&lt;char&gt; unreadData; public: Consumer() { pthread_mutex_init(&amp;lock,NULL); pthread_cond_init(&amp;cond,NULL); } ~Consumer() { pthread_cond_destroy(&amp;cond); pthread_mutex_destroy(&amp;lock); } private: std::vector&lt;char&gt; read(size_t n) { LockThread locker(lock); while (unreadData.size() &lt; n) { // Must wait until we have n char. // This is a while loop because feed may not put enough in. // pthread_cond() releases the lock. // Thread will not be allowed to continue until // signal is called and this thread reacquires the lock. pthread_cond_wait(&amp;cond,&amp;lock); // Once released from the condition you will have re-aquired the lock. // Thus feed() must have exited and released the lock first. } /* * Not sure if this is exactly what you wanted. * But the data is copied out of the thread safe buffer * into something that can be returned. */ std::vector&lt;char&gt; result(n); // init result with size n std::copy(&amp;unreadData[0], &amp;unreadData[n], &amp;result[0]); unreadData.erase(unreadData.begin(), unreadData.begin() + n); return (result); } public: void run() { read(10); read(4839); // etc } void feed(const std::vector&lt;char&gt; &amp;more) { LockThread locker(lock); // Once we acquire the lock we can safely modify the buffer. std::copy(more.begin(),more.end(),std::back_inserter(unreadData)); // Only signal the thread if you have the lock // Otherwise race conditions happen. pthread_cond_signal(&amp;cond); // destructor releases the lock and thus allows read thread to continue. } }; int main() { Consumer c; } </code></pre>
<p>Glib Asynchronous Queues provide the locking and sleep on reading an empty queue you are looking for. See <a href="http://library.gnome.org/devel/glib/2.20/glib-Asynchronous-Queues.html" rel="nofollow noreferrer">http://library.gnome.org/devel/glib/2.20/glib-Asynchronous-Queues.html</a> You can combine them with gthreads or gthread pools.</p>
25,350
<p>I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?</p>
<p>Here is how to build a function that returns a result set that can be queried as if it were a table:</p> <pre><code>SQL&gt; create type emp_obj is object (empno number, ename varchar2(10)); 2 / Type created. SQL&gt; create type emp_tab is table of emp_obj; 2 / Type created. SQL&gt; create or replace function all_emps return emp_tab 2 is 3 l_emp_tab emp_tab := emp_tab(); 4 n integer := 0; 5 begin 6 for r in (select empno, ename from emp) 7 loop 8 l_emp_tab.extend; 9 n := n + 1; 10 l_emp_tab(n) := emp_obj(r.empno, r.ename); 11 end loop; 12 return l_emp_tab; 13 end; 14 / Function created. SQL&gt; select * from table (all_emps); EMPNO ENAME ---------- ---------- 7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7902 FORD 7934 MILLER </code></pre>
<p>If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).<br> If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL. Here an example: (I used a procedure instead of a function, like @Thilo did) </p> <pre><code>create or replace procedure myprocedure(retval in out sys_refcursor) is begin open retval for select TABLE_NAME from user_tables; end myprocedure; declare myrefcur sys_refcursor; tablename user_tables.TABLE_NAME%type; begin myprocedure(myrefcur); loop fetch myrefcur into tablename; exit when myrefcur%notfound; dbms_output.put_line(tablename); end loop; close myrefcur; end; </code></pre>
12,637
<p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p> <p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p> <p>What's your sense?</p> <h2>Update:</h2> <p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p> <p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p> <p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p> <p>Thanks for your patience!</p>
<p>I think your best bet is to match for all curly braced entries, and then check against Python itself whether or not it's valid Python, for which <a href="https://docs.python.org/2/library/compiler.html" rel="nofollow noreferrer">compiler</a> would be helpful.</p>
<p>After posting this, reading the replies so far (thanks everyone!), and thinking about the problem for a while, here is the best approach I've been able to come up with:</p> <ol> <li>Find the first <code>${</code>.</li> <li>Find the next <code>}</code> after that.</li> <li>Feed whatever's in between to <code>compile()</code>. If it works, stick a fork in it and we're done.</li> <li>Otherwise, keep extending the string by looking for subsequent occurences of <code>}</code>. As soon as something compiles, return it.</li> <li>If we run out of <code>}</code> without being able to compile anything, use the results of the last compilation attempt to give information about where the problem lies.</li> </ol> <p>Advantages of this approach:</p> <ul> <li>The code is quite short and easy to understand.</li> <li>It's pretty efficient -- optimal, even, in the case where the expression contains no <code>}</code>. Worst-case seems like it wouldn't be too bad either.</li> <li>It works on many expressions that contain <code>${</code> and/or <code>}</code>.</li> <li>No external dependencies. No need to import <em>anything</em>, in fact. (This surprised me.)</li> </ul> <p>Disadvantages:</p> <ul> <li>Sometimes it grabs too much or too little. See below for an example of the latter. I could imagine a scary example where you have two expressions and the first one is subtly wrong and the algorithm ends up mistakenly grabbing the whole thing and everything in between and returning it as valid, though I haven't been able to demonstrate this. Perhaps things are not so bad as I fear. I don't think misunderstandings can be avoided in general -- the problem definition is kind of slippery -- but it seems like it ought to be possible to do better, especially if one were willing to trade simplicity or execution time.</li> <li>I haven't done any benchmarks, but I could imagine there being faster alternatives, especially in cases that involve lots of <code>}</code> in the expression. That could be a big deal if one wanted to apply this technique to sizable blocks of Python code rather than just very short expressions.</li> </ul> <p>Here is my implementation.</p> <pre><code>def findExpr(s, i0=0, begin='${', end='}', compArgs=('&lt;string&gt;', 'eval')): assert '\n' not in s, 'line numbers not implemented' i0 = s.index(begin, i0) + len(begin) i1 = s.index(end, i0) code = errMsg = None while code is None and errMsg is None: expr = s[i0:i1] try: code = compile(expr, *compArgs) except SyntaxError, e: i1 = s.find(end, i1 + 1) if i1 &lt; 0: errMsg, i1 = e.msg, i0 + e.offset return i0, i1, code, errMsg </code></pre> <p>And here's the docstring with some illustrations in doctest format, which I didn't insert into the middle of the function above only because it's long and I feel like the code is easier to read without it.</p> <pre><code>''' Search s for a (possibly invalid) Python expression bracketed by begin and end, which default to '${' and '}'. Return a 4-tuple. &gt;&gt;&gt; s = 'foo ${a*b + c*d} bar' &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s) &gt;&gt;&gt; i0, i1, s[i0:i1], errMsg (6, 15, 'a*b + c*d', None) &gt;&gt;&gt; ' '.join('%02x' % ord(byte) for byte in code.co_code) '65 00 00 65 01 00 14 65 02 00 65 03 00 14 17 53' &gt;&gt;&gt; code.co_names ('a', 'b', 'c', 'd') &gt;&gt;&gt; eval(code, {'a': 1, 'b': 2, 'c': 3, 'd': 4}) 14 &gt;&gt;&gt; eval(code, {'a': 'a', 'b': 2, 'c': 'c', 'd': 4}) 'aacccc' &gt;&gt;&gt; eval(code, {'a': None}) Traceback (most recent call last): ... NameError: name 'b' is not defined Expressions containing start and/or end are allowed. &gt;&gt;&gt; s = '{foo ${{"}": "${"}["}"]} bar}' &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s) &gt;&gt;&gt; i0, i1, s[i0:i1], errMsg (7, 23, '{"}": "${"}["}"]', None) If the first match is syntactically invalid Python, i0 points to the start of the match, i1 points to the parse error, code is None and errMsg contains a message from the compiler. &gt;&gt;&gt; s = '{foo ${qwerty asdf zxcvbnm!!!} ${7} bar}' &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s) &gt;&gt;&gt; i0, i1, s[i0:i1], errMsg (7, 18, 'qwerty asdf', 'invalid syntax') &gt;&gt;&gt; print code None If a second argument is given, start searching there. &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s, i1) &gt;&gt;&gt; i0, i1, s[i0:i1], errMsg (33, 34, '7', None) Raise ValueError if there are no further matches. &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s, i1) Traceback (most recent call last): ... ValueError: substring not found In ambiguous cases, match the shortest valid expression. This is not always ideal behavior. &gt;&gt;&gt; s = '{foo ${x or {} # return {} instead of None} bar}' &gt;&gt;&gt; i0, i1, code, errMsg = findExpr(s) &gt;&gt;&gt; i0, i1, s[i0:i1], errMsg (7, 25, 'x or {} # return {', None) This implementation must not be used with multi-line strings. It does not adjust line number information in the returned code object, and it does not take the line number into account when computing the offset of a parse error. ''' </code></pre>
25,401
<p>I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation block and all static methods.</p> <p>Is this something that's worth keeping since it will require merging a lot of conflicts, what sort of situation would I be looking at for this refactoring to be worthwhile?</p> <p>We are running this app under Weblogic 8.1 (so JDK 1.4.2)</p> <hr> <p>sorry Thomas, let me clarify..</p> <p>the HEAD version has the traditional singleton pattern (private constructor, getInstance() etc)</p> <p>the branch version has no constructor, is a 'public abstract class' and modified all the methods on the object to be 'static'. The code that used to exist in the private constructor is moved into a static block.</p> <p>Then all usages of the class are changed which causes multiple conflicts in the merge.</p> <p>There are a few cases where this change was made.</p>
<p>From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader business, you avoid some tricky problems, especially when you try to reload the web application.</p>
<p>Does this discussion help? (I don't know if it's taboo to link to another programming forum, but I'd rather not just quote the whole discussion =) )</p> <p><a href="http://forums.sun.com/thread.jspa?threadID=5221231&amp;messageID=9898827" rel="nofollow noreferrer">Sun Discussion on this subject</a></p> <p>The verdict seems to be that it doesn't make enough of a difference to matter in most cases, though technically the static methods are more efficient.</p>
4,790
<p>Does anyone know how to resize images proportionally using JavaScript?</p> <p>I have tried to modify the DOM by adding attributes <code>height</code> and <code>width</code> on the fly, but seems did not work on IE6.</p>
<p>To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto.</p> <pre><code>image.style.width = '50%' image.style.height = 'auto' </code></pre> <p>This will ensure that its aspect ratio remains the same.</p> <p>Bear in mind that browsers tend to <em>suck</em> at resizing images nicely - you'll probably find that your resized image looks horrible.</p>
<pre><code>function resize_image(image, w, h) { if (typeof(image) != 'object') image = document.getElementById(image); if (w == null || w == undefined) w = (h / image.clientHeight) * image.clientWidth; if (h == null || h == undefined) h = (w / image.clientWidth) * image.clientHeight; image.style['height'] = h + 'px'; image.style['width'] = w + 'px'; return; } </code></pre> <p>just pass it either an img DOM element, or the id of an image element, and the new width and height.</p> <p>or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio</p>
20,585
<p>When possible.. do you leave parentheses in or out in Ruby? </p>
<p>From the <a href="https://web.archive.org/web/20100420090330/http://www.pathf.com/blogs/2008/10/elements-of-ruby-style/" rel="noreferrer" title="Elements of Ruby Style">Elements of Ruby Style</a></p> <blockquote> <p><strong>Ruby allows you to leave out parenthesis, in general, resist this temptation.</strong></p> <p>Parenthesis make the code easier to follow. General Ruby style is to use them, except in the following cases:</p> <ul> <li>Always leave out empty parentheses</li> <li>The parentheses can be left out of a single command that is surrounded by ERb delimiters -- the ERb markers make sure the code is still readable</li> <li>A line that is a single command and a single simple argument can be written without the parenthesis. Personally, I find that I do this less and less, but it's still perfectly readable. I tend not to like single lines in regular ruby code that have multiple arguments and no parentheses.</li> <li>A lot of Ruby-based Domain Specific Languages (such as Rake) don't use parenthesis to preserve a more natural language feel to their statements.</li> </ul> </blockquote>
<p>If you've been programming for a long time, you'll probably have an "itch" to add parentheses, and in many cases there are good reasons for this.</p> <p>The code is easier on the eyes though in my opinion, and I haven't run into a problem yet--if you're going to need parentheses, you'll know it beforehand before you have to run into the debugging script.</p>
44,262
<p>I've editing this original question as I think I've narrowed down the problem...</p> <p>I have one view in my site that will not let me put $document.ready within a masterpage contentplaceholder. I've stripped this page to the bare bones and the only thing that is special about it is it has a custom route in global.asax</p> <pre><code> routes.MapRoute("Books", "{controller}/{action}/{keywords}/{pageNumber}", new { controller = "Books", action = "SearchResults" } ); </code></pre> <p>Any idea why this custom route would stop $document.ready working correctly when put in a masterpages contentplaceholder zone?</p>
<p>I had the same problem and it turned out that when I used a certain route it changed the perceived file hierarchy of the site such as the ../../Content link for the .js file didn't work any more. I fixed it by changing my jquery script reference to look like this:</p> <pre><code>&lt;script src="&lt;%= Url.Content("~/Content/jquery-1.2.6.min.js") %&gt;" type="text/javascript"&gt;&lt;/script&gt; </code></pre>
<p>Just stick it somewhere within the content control of your view page in a <code>&lt;script ...&gt;</code> tag.</p> <pre><code>&lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"&gt; &lt;div class="contentItem"&gt; &lt;%!-- yadda --%&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { // do your worst }); &lt;/script&gt; &lt;/asp:Content&gt; </code></pre> <p>If you have stuff that runs on every page, you can peel that off into a .js file and access it from the master page. But for functions relating to a specific view, this is probably the simplest way to go and easiest to maintain.</p>
30,747
<p>When choosing a layer height, I know that often you go as fine as your printer will do for better precision, but sometimes you go a little thicker, for speed, for example.</p> <p>I also see 0.1&nbsp;mm and 0.2&nbsp;mm as common thicknesses.</p> <p>What are my options here? When I'm working on a part where I want to print a draft piece, and the quality matters less, can I set it to 0.15&nbsp;mm? 0.11&nbsp;mm? The Ultimaker Cura slicer I normally use will let me put in almost anything, but what can it really do? If I can use values in between simple 0.1&nbsp;mm increments, are there reasons I might want to do so?</p> <p>For reference, I have a Monoprice Maker Select Plus with a 0.4&nbsp;mm nozzle and, again, Ultimaker Cura as the slicer. But more general answers for other printer types and slicers are also encouraged. I want to know about this generally, and not just for one printer.</p>
<p>You decide which layer height you want based on the quality you desire, but never go over about 75&nbsp;% of your nozzle diameter, so with your 0.4&nbsp;mm nozzle never choose layer heights larger than 0.3&nbsp;mm. The rationale of this rule of thumb is that the filament leaves the nozzle as a tube and needs to be flattened to make it adhere to the previous layer.</p>
<p>You decide which layer height you want based on the quality you desire, but never go over about 75&nbsp;% of your nozzle diameter, so with your 0.4&nbsp;mm nozzle never choose layer heights larger than 0.3&nbsp;mm. The rationale of this rule of thumb is that the filament leaves the nozzle as a tube and needs to be flattened to make it adhere to the previous layer.</p>
1,165
<p>How do I make open “read only” the only option within a SharePoint document library?</p> <p>When using either Word 2003 or 2007 and saving the document as a template or modifying the file properties as “read only” doesn’t prevent modification of the file in a SharePoint document library. Modifying the document library permissions to only allow “read only” access doesn’t work either. What works is to use a SharePoint URL link list to access the files within an external server directory, but that defeats the use of a SharePoint document library.</p>
<p>I don't know if you can force read only to be the only option, but you can implement your own event handler to override the ItemUpdating event. Just cancel the update and any changes will be discarded.</p> <p>Sahil shows a very basic event handler that performs the cancel <a href="http://blah.winsmarts.com/2006-7-Sharepoint_2007__List_Events_Practical_Example__Creating_a_rigged_survey.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>The event handler works, but I have found a simpler workaround.</p> <p>If you “Check Out” the file and leave it checked out, no one else has the option to edit the file. This is still not ideal, but for forcing a document to be “read only” it works.</p>
11,154
<p>I've been able to find details on several self-balancing <code>BST</code>s through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter). </p> <p>I want a <code>BST</code> that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized. </p> <p>I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered.</p>
<p><a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="nofollow noreferrer">Red-black</a> is better than AVL for insertion-heavy applications. If you foresee relatively uniform look-up, then Red-black is the way to go. If you foresee a relatively unbalanced look-up where more recently viewed elements are more likely to be viewed again, you want to use <a href="http://en.wikipedia.org/wiki/Splay_tree" rel="nofollow noreferrer">splay trees</a>.</p>
<blockquote> <p>[hash tables have] O(1) insertion and search</p> </blockquote> <p>I think this is wrong.</p> <p>First of all, if you limit the keyspace to be finite, you could store the elements in an array and do an O(1) linear scan. Or you could shufflesort the array and then do a linear scan in O(1) expected time. When stuff is finite, stuff is easily O(1).</p> <p>So let's say your hash table will store any arbitrary bit string; it doesn't much matter, as long as there's an infinite set of keys, each of which are finite. Then you have to read all the bits of any query and insertion input, else I insert y0 in an empty hash and query on y1, where y0 and y1 differ at a single bit position which you don't look at.</p> <p>But let's say the key lengths are not a parameter. If your insertion and search take O(1), in particular hashing takes O(1) time, which means that you only look at a finite amount of output from the hash function (from which there's likely to <em>be</em> only a finite output, granted).</p> <p>This means that with finitely many buckets, there must be an infinite set of strings which all have the same hash value. Suppose I insert a lot, i.e. &omega;(1), of those, and start querying. This means that your hash table has to fall back on some other O(1) insertion/search mechanism to answer my queries. Which one, and why not just use that directly?</p>
2,456
<p>I have 2 components for example (editor.mxml using mx:windows), when I click an edit button, I want to get the current value from the other component's datafield? (datagrid.mxml using mx:window)</p> <p>I do know how to access the main MXML's datagrid by parentDocument or Application.application method, but stumped block if I want to access other way as mentioned above. Keep the code as simple as possible.</p>
<p>You could either do <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a>, that is, give component <code>A</code> a reference to component <code>B</code> so that they can communicate directly (example of tighter coupling,) or have both components communicate through a common <a href="http://en.wikipedia.org/wiki/Mediator_pattern" rel="nofollow noreferrer">mediator</a> using events (example of more loose coupling.)</p> <p>Both of those options would be implemented wherever it is that you're creating those components (<code>A</code> and <code>B</code> in this example) and adding them to the display list.</p>
<p>This might be more complicated than it deserves, and it smacks of Pattern-Fever, but you could use a mediator class that listens for the CLICK event from the button and knows enough about the other component to query its property. It could even transmit that data using a custom event, which the button listens for.</p> <p>While this involves three classes instead of two, it often turns out to be easier to have two components that focus on looking good and one that worries about coordination.</p> <p>Cheers</p>
49,574
<p>How to add child rows in datagrid c#.net windows forms?</p>
<p>I'm not sure if this is what you're asking, but if you want to append rows you're easiest way is to append them to whatever DataSource you're using before you DataBind()</p> <p>If this wasn't what you're after, please provide more detail.</p>
<p>Usually you bind the datagrid to a dataset. Could you please clarify what you are looking for so that we can get into more detail?</p>
12,765
<p><strong>C#6 Update</strong></p> <p>In <a href="https://msdn.microsoft.com/en-us/magazine/dn802602.aspx" rel="nofollow noreferrer">C#6 <code>?.</code> is now a language feature</a>:</p> <pre><code>// C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null; // C#6 propertyValue1 = myObject?.StringProperty; </code></pre> <p>The question below still applies to older versions, but if developing a new application using the new <code>?.</code> operator is far better practice.</p> <p><strong>Original Question:</strong></p> <p>I regularly want to access properties on possibly null objects:</p> <pre><code>string propertyValue1 = null; if( myObject1 != null ) propertyValue1 = myObject1.StringProperty; int propertyValue2 = 0; if( myObject2 != null ) propertyValue2 = myObject2.IntProperty; </code></pre> <p>And so on...</p> <p>I use this so often that I have a snippet for it.</p> <p>You can shorten this to some extent with an inline if:</p> <pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null; </code></pre> <p>However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:</p> <pre><code>propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null; </code></pre> <p>What I really want is <code>??</code> style syntax, which works great for directly null types:</p> <pre><code>int? i = SomeFunctionWhichMightReturnNull(); propertyValue2 = i ?? 0; </code></pre> <p>So I came up with the following:</p> <pre><code>public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action, TResult valueIfNull ) where T : class { if ( input != null ) return action( input ); else return valueIfNull; } //lets us have a null default if the type is nullable public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action ) where T : class where TResult : class { return input.IfNotNull( action, null ); } </code></pre> <p>This lets me us this syntax:</p> <pre><code>propertyValue1 = myObject1.IfNotNull( x =&gt; x.StringProperty ); propertyValue2 = myObject2.IfNotNull( x =&gt; x.IntProperty, 0); //or one with multiple levels propertyValue1 = myObject.IfNotNull( o =&gt; o.ObjectProp.IfNotNull( p =&gt; p.StringProperty ) ); </code></pre> <p>This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.</p> <p>This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:</p> <pre><code>if( ( obj1 == null &amp;&amp; obj2 == null ) || ( obj1 != null &amp;&amp; obj2 != null &amp;&amp; obj1.Property == obj2.Property ) ) ... //becomes if( obj1.NullCompare( obj2, (x,y) =&gt; x.Property == y.Property ) ... </code></pre> <p>What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?</p> <hr> <p>I guess what I really want here is a compiler/language extension:</p> <pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null; //becomes propertyValue1 = myObject?StringProperty; </code></pre> <p>This would make the complex case far easier:</p> <pre><code>propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null //becomes propertyValue1 = myObject?ObjectProp?StringProperty; </code></pre> <p>This would only work for value types, but you could return nullable equivalents:</p> <pre><code>int? propertyValue2 = myObject?ObjectProp?IntProperty; //or int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0; </code></pre>
<p>We independently came up with the exact same extension method name and implementation: <a href="http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html" rel="noreferrer">Null-propagating extension method</a>. So we don't think it's confusing or an abuse of extension methods.</p> <p>I would write your "multiple levels" example with chaining as follows:</p> <pre><code>propertyValue1 = myObject.IfNotNull(o =&gt; o.ObjectProp).IfNotNull(p =&gt; p.StringProperty); </code></pre> <p>There's a <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=192177" rel="noreferrer">now-closed bug on Microsoft Connect</a> that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.</p>
<p>Personally, even after all your explanation, I can't remember how the heck this works:</p> <pre><code>if( obj1.NullCompare( obj2, (x,y) =&gt; x.Property == y.Property ) </code></pre> <p>This could be because I have no C# experience; however, I could read and understand everything else in your code. I prefer to keep code language agnostic (esp. for trivial things) so that tomorrow, another developer could change it to a whole new language without too much information about the existing language.</p>
14,981
<p>In my C++ program (on Windows), I'm allocating a block of memory and can make sure it stays locked (unswapped and contiguous) in physical memory (i.e. using VirtualAllocEx(), MapUserPhysicalPages() etc). </p> <p>In the context of my process, I can get the VIRTUAL memory address of that block, <b> but I need to find out the PHYSICAL memory address of it </b> in order to pass it to some external device. </p> <p><br> <b>1.</b> Is there any way I can translate the virtual address to the physical one within my program, in USER mode? <br> <br><b>2.</b> If not, I can find out this virtual to physical mapping only in KERNEL mode. I guess it means I have to write a driver to do it...? Do you know of any readily available driver/DLL/API which I can use, that my application (program) will interface with to do the translation? <br><br> <b>3.</b> In case I'll have to write the driver myself, how do I do this translation? which functions do I use? Is it <b>mmGetPhysicalAddress()</b>? How do I use it? <br><br><b>4.</b> Also, if I understand correctly, mmGetPhysicalAddress() returns the physical address of a virtual base address that is in the context of the calling process. But if the calling process is the driver, and I'm using my application to call the driver for that function, I'm changing contexts and I am no longer in the context of the app when the mmGetPhysicalAddress routine is called... so how do I translate the virtual address in the application (user-mode) memory space, not the driver?</p> <p>Any answers, tips and code excerpts will be much appreciated!!</p> <p>Thanks</p>
<p><em>In my C++ program (on Windows), I'm allocating a block of memory and can make sure it stays locked (unswapped and contiguous) in physical memory (i.e. using VirtualAllocEx(), MapUserPhysicalPages() etc).</em></p> <p>No, you can't really ensure that it stays locked. What if your process crashes, or exits early? What if the user kills it? That memory will be reused for something else, and if your device is still doing DMA, that will eventually result in data loss/corruption or a bugcheck (BSOD).</p> <p>Also, <code>MapUserPhysicalPages</code> is part of Windows AWE (Address Windowing Extensions), which is for handling more than 4 GB of RAM on 32-bit versions of Windows Server. I don't think it was intended to be used to hack up user-mode DMA.</p> <p><em>1. Is there any way I can translate the virtual address to the physical one within my program, in USER mode?</em></p> <p>There are drivers that let you do this, but you cannot program DMA from user mode on Windows and still have a stable and secure system. Letting a process that runs as a limited user account read/write physical memory allows that process to own the system. If this is for a one-off system or a prototype, this is probably acceptable, but if you expect other people (particularly paying customers) to use your software and your device, you should write a driver. </p> <p><em>2. If not, I can find out this virtual to physical mapping only in KERNEL mode. I guess it means I have to write a driver to do it...?</em></p> <p>That is the recommended way to approach this problem.</p> <p><em>Do you know of any readily available driver/DLL/API which I can use, that my application (program) will interface with to do the translation?</em></p> <p>You can use an <a href="http://msdn.microsoft.com/en-us/library/aa489506.aspx" rel="noreferrer">MDL (Memory Descriptor List)</a> to lock down arbitrary memory, including memory buffers owned by a user-mode process, and translate its virtual addresses into physical addresses. You can also have Windows temporarily create an MDL for the buffer passed into a call to <code>DeviceIoControl</code> by using <a href="http://msdn.microsoft.com/en-us/library/ms795857.aspx" rel="noreferrer"><code>METHOD_IN_DIRECT</code></a> or <a href="http://msdn.microsoft.com/en-us/library/ms795857.aspx" rel="noreferrer"><code>METHOD_OUT_DIRECT</code></a>. </p> <p>Note that contiguous pages in the virtual address space are almost never contiguous in the physical address space. Hopefully your device is designed to handle that.</p> <p><em>3. In case I'll have to write the driver myself, how do I do this translation? which functions do I use? Is it mmGetPhysicalAddress()? How do I use it?</em></p> <p>There's a lot more to writing a driver than just calling a few APIs. If you're going to write a driver, I would recommend reading as much relevant material as you can from <a href="http://msdn.microsoft.com/en-us/library/aa973498.aspx" rel="noreferrer">MSDN</a> and <a href="http://www.osronline.com/" rel="noreferrer">OSR</a>. Also, look at the examples in the <a href="http://www.microsoft.com/whdc/devtools/wdk/default.mspx" rel="noreferrer">Windows Driver Kit</a>.</p> <p><em>4. Also, if I understand correctly, mmGetPhysicalAddress() returns the physical address of a virtual base address that is in the context of the calling process. But if the calling process is the driver, and I'm using my application to call the driver for that function, I'm changing contexts and I am no longer in the context of the app when the mmGetPhysicalAddress routine is called... so how do I translate the virtual address in the application (user-mode) memory space, not the driver?</em></p> <p>Drivers are not processes. A driver can run in the context of any process, as well as various elevated contexts (interrupt handlers and DPCs).</p>
<p>Wait, there is more. For the privilege of runnning on your customer's Vista 64 bit, you get expend more time and money to get your kernal mode driver resigned my Microsoft,</p>
47,846
<p>What tools do you use to find unused/dead code in large java projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.</p> <p>Suggestions for general strategies/techniques (other than specific tools) are also appreciated.</p> <p><strong>Edit:</strong> Note that we already use code coverage tools (Clover, IntelliJ), but these are of little help. Dead code still has unit tests, and shows up as covered. I guess an ideal tool would identify clusters of code which have very little other code depending on it, allowing for docues manual inspection.</p>
<p>An Eclipse plugin that works reasonably well is <a href="http://www.ucdetector.org/" rel="noreferrer">Unused Code Detector</a>.</p> <p>It processes an entire project, or a specific file and shows various unused/dead code methods, as well as suggesting visibility changes (i.e. a public method that could be protected or private).</p>
<p>Eclipse can show/highlight code that can't be reached. JUnit can show you code coverage, but you'd need some tests and have to decide if the relevant test is missing or the code is really unused. </p>
19,655
<p>Please pardon my lack of Photoshop skills, but I'm curious what type of strategy Apps like Facebook and AP Mobile News are using for the 'label slider' in their applications. Here's a quick snippet outlining what I'm talking about as I'm sure the name I'm labeling the utility as is being butchered: <a href="http://dl-client.getdropbox.com/u/57676/slider.jpg" rel="nofollow noreferrer">http://dl-client.getdropbox.com/u/57676/slider.jpg</a></p> <p>Essentially the user can touch the label and glide it along the X axis. It has a smooth bounce effect also once it hits the edges. This gives quite a bit more real estate if you need to present more on the screen than what your portrait mode allows for and is thus very valuable.</p> <p>Is it a matter of just creating a UILabel that's wider than the screen with a bit of Touch API + Core Animation? Would love insight on how to start tackling this thing.</p>
<p>You'll most likely want to use a UIScrollView, with a UILabel as its content view. Size the label appropriately to your content, and then set the contentSize property of the scrollview to that size. </p>
<p>I created a similar control, and it's much easier than you think. It's just a UIScrollView with a series of UIButtons added to it. You could use labels instead of buttons - just depends on the feel you want. I think Facebook is probably using labels for theirs. </p> <p>In any case, you'll probably want to use a series of components rather than one component (which is what Ben suggested) in the event that you want to, say, style the "selected" label differently from the others. It also makes hit detection a little easier.</p> <p>You get the bounce effect for free by default - you may have noticed that most scroll views in iPhone apps do the same thing. It can be turned off as well.</p>
43,802
<p>I am having severe performance issues when compiling a moderately large ASP.Net website in Visual Studio 2008 (targeting .Net 3.5). I know there are some tips &amp; registry hacks for improving compilation performance in VS 2005, are there any for VS 2008? Specifically, it seems that VS 2008 is compiling the whole website every time F5 is hit, even when no files have changed in that project since the last compile, or perhaps there is some way to skip the validation stage? </p>
<ul> <li><p><strong>Antivirus problems</strong>: Make sure that your Antivirus program excludes your project directories! Make sure that your Microsoft.NET directory inside of your Windows directory is also on the exclusion list.</p></li> <li><p><strong>IIS vs. "Cassini"</strong> : If you can, use IIS instead of VS's integrated web server (aka "Cassini"). Doing this will prevent the server from having to restart every time you run.</p></li> <li><p><strong>Memory</strong>: Do you have enough?</p></li> </ul>
<p>I'm guessing this is an ASP.Net Website project and <em>not</em> an ASP.Net Web Application project. You'll get better compile performance from a Web Application project so you might consider converting it.</p> <p>For a Website project, you can open the Website in Visual Studio, right click the web site project node in the Solution Explorer and click Properties. When the dialog box opens, click the Build item and set the item labeled "Before Running Startup Page" to "No Build" or "Build Page". This will prevent Visual Studio from compiling all the pages in your site and improve your local development experience at the cost of reduced compilation. Probably a worthy trade-off in your case.</p>
36,638
<p>Is there a good way to time SQL queries when using Linq to SQL? I really like logging feature, but it would be great if you could somehow also time that query. Any ideas?</p>
<p>SQL Profiler to get the query and the time, and also Execution Path in Query analyzer to see where the bottlenecks are.</p>
<p>We use SQL Profiler to test our queries with LLBLGen Pro. </p>
10,179
<p>I recently tried cleaning my CR-10S Pro heat bed with acetone and it made this white stain on it.</p> <p>Anyone have any solutions to this?</p>
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p> <p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p> <p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p> <p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p> <p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
1,869
<h2>Backstory</h2> <p>I've had issues in the past with my drive gear "eating" my filament. It seemed that the filament quit extruding for one reason or another and the drive gear would slowly eat away at the side of the filament.</p> <p>I eventually assumed it was the plastic filament guides causing unnecessary tension that the drive gear couldn't compete with, ultimately keeping the filament from moving forward. Thusly, allowing the drive gear to continue "trying".</p> <p>My solution was to hang my spools above the machine to avoid using the filament guides feeding from the back of the machine up through the top.</p> <h2>Question</h2> <p>Can the plastic filament guides really cause that much drag? What other variables can I expect to look out for?</p> <p><em>Machine:</em> <strong>MakerBot Replicator Dual (1st Generation)</strong></p>
<p>For an easy test, try manually pulling the filament through the U-loop of guide tube. How hard is it to pull through? It should only take 1-2 lbs of tension at most. </p> <p>Then do a "tug test" on the extruder. Start it loading and grab the filament by hand to try to stop it from extruding. The Replicator 1/2/2x extruder style can typically pull ~8-10 lbs of tension and it should be fairly difficult to stop the filament. When you do stop the filament, you should hear clicking/thumping from the stepper stalling, NOT quiet grinding as the drive gear chews through the filament. If the grip slips rather than stalls, your extruder hardware needs to be tuned or replaced. </p> <p>There are three common causes of excessive feed tube drag:</p> <ul> <li>Use of polyethylene tubing instead of PTFE -- this makes a shockingly large difference in drag friction. You can use a heat gun or torch (outside!!) to tell the difference between PE and PTFE. PE will soften quickly and then melt fairly easily, whereas PTFE will simply go clear and eventually char without melting. Nylon is also sometimes used for feed tubes with acceptable results, but if you have any suspicion about the tube material, just buy new PTFE tubes from a reputable vendor like McMaster. </li> <li>Too many loops/curves in the tube. Total drag friction is an exponential function of the total amount of curvature in the tube. You should have one good U-loop, no spirals or floppy zig-zags. </li> <li>Excessive friction on the spool rotation. Any spool back-tension gets greatly magnified through the feed tube per the <a href="https://en.wikipedia.org/wiki/Capstan_equation" rel="nofollow">capstan equation</a>. This can be caused by a bad spool holder, or if the filament is knotted on the spool due to letting the end of the spool loose during handling. </li> </ul>
<p>The friction inside of the guide tubes is fairly minimal assuming that the lines are straight and there isn't anything else inside them. My guess would be that you may have another issue. Reducing the drag in the guide tubes while it may reduce the problem of clogged nozzle, might just be hiding the symptoms of another problem.</p> <p>I've heard, but never tried adding a dab of Canola oil to the tip of your filament prior to feeding it into your extruder. Specifically for Makerbots.</p> <p>Link my source: <a href="https://groups.google.com/forum/#!topic/makerbot/Wn-MKC1Ybm0%5B1-25%5D" rel="nofollow noreferrer">https://groups.google.com/forum/#!topic/makerbot/Wn-MKC1Ybm0%5B1-25%5D</a> </p>
224
<p>I was wondering if its possible to inject a thread into a remote app domain running in a separate process. </p> <p>My guess is that I could do this using the debugging interfaces (ICorDebug) but I was wondering if there is any other way? </p>
<p>There was recently an announcement of a new facility Mono provides to do just this. See this post on <a href="http://tirania.org/blog/archive/2008/Sep-29.html" rel="nofollow noreferrer">assembly injection</a>. </p>
<p>Mike Stall has an <a href="http://blogs.msdn.com/jmstall/archive/2006/09/28/managed-create-remote-thread.aspx" rel="nofollow noreferrer">interesting sample</a> on how to use CreateRemoteThread to inject remote threads in managed apps. </p> <p>This answer is still incomplete, cause I would like to run new code in the remote appdomain. I guess I could try creating 1 new thread that loads a library for me, and another that will call a place in my new library to do the work. </p>
22,382
<p>In my project I have a class that is inherited by many other classes. We'll call it ClassBase.</p> <pre><code>public class ClassInheritFromBase : ClassBase </code></pre> <p>When ClassBase is being inherited, <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it.</p> <p>The project compiles and runs fine.</p> <p>If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else.</p> <p>Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.</p>
<p>For those who still have a problem with this, (I still get it from time to time) here's the steps I did to get rid of the ambiguous reference warning in ReSharper.</p> <ol> <li>First I went to all my class libraries and made sure that all references to my other class libraries had the <em>Copy Local</em> property set to false.</li> <li>In the project where I actually got the ambiguous reference warning, I went to my bin catalog and deleted all .dll and .pdb files for all the libraries that had their own project.</li> <li>After a new build, or in my case "update reference" on the .dll files in VS, the errors from Resharper were gone.</li> </ol> <p>I'm using Resharper 5.1 in Visual Studio 2008 with only a reference to the dlls I'm using which is why I had to "update reference"</p>
<p>I encountered the same problem. The issue I had was caused by a custom build provider (from an open source library I'm using called <a href="http://www.codeplex.com/PageMethods" rel="nofollow noreferrer">PageMethods</a>) and the fact that all my .aspx pages inherit from a BasePage class which lives in the App_Code folder.</p> <p>I couldn't get any build of ReSharper to work with my project (4.1.933, 4.1.943 (latest) or 4.5). The fix in the latest ReSharper build fixes the "Ambiguous Reference" problem, but breaks the custom build provider.</p> <p>The only way I could get both the build provider and base classes to work with ReSharper was to put the Base Classes into a separate class library.</p> <p>The following are the logged Jira bugs that seem to relate to this issue:</p> <ul> <li><a href="http://www.jetbrains.net/jira/browse/RSRP-92804" rel="nofollow noreferrer">False "Ambiguous reference" for symbols from App_Code</a></li> <li><a href="http://www.jetbrains.net/jira/browse/RSRP-68028" rel="nofollow noreferrer">Custom build provider may generate partial class with second part residing in app_code</a></li> </ul>
23,320
<p>How do you generate and analyze a thread dump from a running JBoss instance?</p>
<p>There is a JBoss-specific method that is slightly more user-friendly:</p> <p><a href="http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole" rel="nofollow noreferrer">http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole</a></p> <p>This is especially useful when you don't have direct access to the host machine (which "kill" would require).</p>
<p>Sometimes JBoss locks so much that even jmx-concole doesn't respond. In such case use kill -3 on Linux and <a href="http://www.latenighthacking.com/projects/2003/sendSignal/" rel="nofollow">SendSignal</a> on Windows.</p>
8,448
<p>It drives me nuts to hear business proponents using the term realtime for web-based systems. I'm becoming the crazy in the room, chanting, "There is no such thing as realtime on the web! We're in banking, not the rocket launch/ship navigation/airplane autopilot business!"</p> <p>Anyone have anything better for performance specifications than realtime, or its horrible hybrid, near-realtime?</p>
<p>In the banking industry most of the time "real time" means the opposite of "end-of-day". </p> <p>Because there was no such thing as internet/intranet/LANs/WANs in the old days, all balancing is done at "end-of-day". Transactions done in one branch with a certain bank account are oblivious of the transactions done in another; all of the balance resolution will occur during end of day. When mainframes came in the same rule applied: resolutions are done by computer by a long-running-process usually run between 9PM and 12 midnight.</p> <p>This is the reason behind terms such as "current balance" and "available balance", e.g., available balance is what has been determined by the end-of-day process as an account's balance for the previous day; current balance is what it's supposed to be, but you can't touch it yet since the bank is not sure if you've made some transaction somewhere else.</p> <p>With the advent of ATMs, the internet, and other interconnectivity technologies, "real time" balance resolution is now possible: a withdrawal, an online transaction, a purchase debit, etc will immediately be reflected in the customers' bank accounts without the need to wait for end-of-day processing.</p>
<p>How do you define "real-time" for embedded systems? I would say that a decent definition is "a system which is able to process and respond to inputs faster than the average time between inputs." In other words, a system that will never fall behind in processing compared to the systems which are feeding it data. Using this definition everything on the web is a real-time system, since web servers that fall behind tend to be inaccessable (ie. the slashdot effect). </p>
7,406
<p>I'm adding a new field to a list and view. To add the field to the view, I'm using this code:</p> <pre><code>view.ViewFields.Add("My New Field"); </code></pre> <p>However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.</p>
<p>I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using:</p> <pre><code>string[] fieldNames = new string[] { "Title", "My New Field", "Modified", "Created" }; SPViewFieldCollection viewFields = view.ViewFields; viewFields.DeleteAll(); foreach (string fieldName in fieldNames) { viewFields.Add(fieldName); } view.Update(); </code></pre>
<p>You have to use the follow method to reorder the field</p> <pre><code> string reorderMethod = @"&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt; &lt;Method ID=""0,REORDERFIELDS""&gt; &lt;SetList Scope=""Request""&gt;{0}&lt;/SetList&gt; &lt;SetVar Name=""Cmd""&gt;REORDERFIELDS&lt;/SetVar&gt; &lt;SetVar Name=""ReorderedFields""&gt;{1}&lt;/SetVar&gt; &lt;SetVar Name=""owshiddenversion""&gt;{2}&lt;/SetVar&gt; &lt;/Method&gt;"; </code></pre>
15,518
<p>I've just read up on <code>Thread.IsBackground</code> and if I understand it correctly, when it's set to <code>false</code> the Thread is a foreground thread which means it should stay alive until it has finished working even though the app have been exited out. Now I tested this with a winform app and it works as expected but when used with a console app the process doesn't stay alive but exits right away. Does the <code>Thread.IsBackground</code> behave differently from a console app than a winform app?</p>
<p>The <code>Thread.IsBackground</code> property only marks if the thread should block the process from exiting. It doesn't perform any magic to keep the thread alive until some sort of explicit exit.</p> <p>To quote the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx" rel="nofollow noreferrer" title="MSDN - Thread.IsBackground Property (System.Threading)">Thread.IsBackground Property MSDN</a> (emphasis mine):</p> <blockquote> <p>A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. <b>Once all foreground threads belonging to a process have terminated, the common language runtime ends the process.</b> Any remaining background threads are stopped and do not complete.</p> </blockquote> <p>In order to keep your console app alive you'll need to have some sort of loop which will spin until you ask it to stop via a flag or similar. Windows Forms applications have this built in because of their message pump (I believe).</p>
<p>IMHO really you should be a lot more explicit about the expected semantics of your application and deliberately &lt;thread&gt;.Join.</p>
13,270
<p>I seem to recall reading about an Amazon S3-compatible test server that you could run on your own server for unit tests or whatever. However, I've just exhausted my patience looking for this with both Google and AWS. Does such a thing exist? If not, I think I'll write one.</p> <p>Note: I'm asking about Amazon S3 (the storage system) rather than Amazon EC2 (cloud computing).</p>
<p>Are you thinking of <a href="http://github.com/technoweenie/parkplace" rel="nofollow noreferrer">Park Place</a>?</p> <p>FYI, its <a href="http://code.whytheluckystiff.net/parkplace/" rel="nofollow noreferrer">old home page</a> is offline now.</p>
<p>Amazon uses Xen, so you can probably just run your AMI in your own Xen installation. I'd just fire up an instance and run the tests there, though. It doesn't cost much and you should usually be fine with developing locally and infrequently testing it on their system.</p>
11,688
<p><strong>What Delphi coding standards document(s) do you follow?</strong></p> <p>Our company is looking at putting some better coding standards in place, to improve our code’s readability, reviewability, and maintainability. We’ve come across CodeGear’s “Object Pascal Style Guide”, but it hasn’t been touched in quite a while and I imagine a number of people have made some local improvements or additions. I’ve come across some published variations and other documents, which I will list, below.</p> <p>NB: I do <em>not</em> want to start a style war. I just want to know what standards you follow, and why.</p> <p>Thanks.</p> <p><hr /> <strong>UPDATE:</strong> Well, the "JCL Delphi Language Style Guide" seems to be the clear winner! Thanks!</p>
<p><strong>Project JEDI Delphi Language Style Guide With JCL Additions</strong></p> <p>(An extension of CodeGear’s “Object Pascal Style Guide”)</p> <p><a href="https://wiki.delphi-jedi.org/wiki/Project_JEDI_Delphi_Language_Style_Guide" rel="nofollow noreferrer">https://wiki.delphi-jedi.org/wiki/Project_JEDI_Delphi_Language_Style_Guide</a></p> <p>(Thanks to Jeroen Pluimers and AmigoJack for reporting that the old links had died. And in case this latest link also dies, <a href="http://web.archive.org/web/*/https://wiki.delphi-jedi.org/wiki/Project_JEDI_Delphi_Language_Style_Guide" rel="nofollow noreferrer">here's its Internet Archive link</a>, for good measure.)</p>
<p><strong>CodeGear’s “Hungarian peanut butter”, for naming identifiers</strong></p> <p><a href="http://dn.codegear.com/article/27983" rel="nofollow noreferrer">http://dn.codegear.com/article/27983</a></p>
32,907
<p>Whenever I try to backup a database it goes until 90% and gets stuck there until I manually kill (because it doesn't stop if I try to stop it) the msftesql process.</p> <p>That clearly means that something makes a conflict between the fulltext indexing and the backup process. </p> <p>So, have you seen anything like this? If not, how would you go about debugging this problem?</p>
<p>The first and obvious debug point is to disable full text indexing and try backing up the database again. If it does backup, then you know that FTS is the problem. If it doesn't, then you have another issue to find.</p> <p>I would also check both the SQL Logs and the Event Viewer to see if any useful information is there.</p> <p>Finally, if you have actual, physical access to the server during the backup, listen and see if the disk is making any funny noises during the backup process to indicate a disk failure of some sort. </p> <p>I can say that I've never had FTS stop a backup from happening, but that doesn't mean it couldn't happen.</p>
<p>I have the same problem. The activity monitor shows that the Backup job has a wait type MSSEARCH</p> <p>The index is manually populated when run it is hanging for days on end until I force-ably stop it or the service is restarted. it used to take minutes to populate.</p>
12,655
<p>I'm new to ASP.NET MVC and all tutorials, samples, and the like I seem to find are very basic.</p> <p>Is it possible (and if yes, a good design) to have routes like so: .../Organization/10/User/5/Edit .../Organization/10/User/List</p> <p>In other words; can the urls mirror your domain model?</p>
<p>Possible, yes, with a route something like:</p> <pre><code>"~/Organization/{orgId}/{Controller}/{id}/{action}" </code></pre> <p>Whether it is a good design or not I couldn't say for sure, only that it seems rather complicated to me. </p> <p>If you have multiple User tables, one for each company, it might make some sense.</p>
<p>"<strong>If you have multiple User tables</strong>, one for each company, it might make some sense." Why only then? </p> <p>"~/Organization/10/User/5/Edit"</p> <p>... gives me the organization context at all times.</p> <p>I didn't say so in my first question, but I've written an action filter that authorizes according to the rule that the logged on user must belong to the organization of the current action (hence not being able to see/edit/whatever user(s) of another organization).</p> <p>I'm not saying that it's the best solution, but if not implementing this cross-cutting concern (aspect) as an action filter knowing the org id (via the action params), how would you solve the authorization issue elegantly?</p> <p>As I initially stated, I'm new to the world of MVC and very excited about the answers.</p>
48,057
<p>I have the following table structure</p> <pre><code>CREATE TABLE `table` ( `id` int(11) NOT NULL auto_increment, `date_expired` datetime NOT NULL, `user_id` int(11) NOT NULL, `foreign_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `date_expired` (`date_expired`,`user_id`,`foreign_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>As you'll notice, I have duplicate indexes on user_id: <code>date_expired</code> &amp; <code>user_id</code>. I of course want the unique index because I want to ensure the data is unique.</p> <p>The reason for the duplicate indexes is because without the <code>user_id</code> index, my main search query takes 4 seconds. With the extra index it takes 1 second. The query is joining the table on <code>user_id</code> and checking <code>date_expired</code>.</p> <p>The table only has 275 records.</p> <ul> <li>How bad is it to have a unique and normal index on the same field?</li> <li>How bad is it to have larger indexes than data when the table is purely ids?</li> </ul>
<p>I believe if you created your unique index as (<code>user_id</code>, <code>date_expired</code>, <code>foreign_id</code>), you'll get the same benefit of having a normal index on <code>user_id</code> with just the unique index. MySQL can use the first columns of any index to pare down the number of rows in the join in the same manner as an index on <code>user_id</code>. </p> <p>See <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html#id3515520" rel="noreferrer">MySQL's index documentation</a> for more information.</p> <p>Are you referring to the <code>id</code> auto_increment column elsewhere in your schema to save space? Since your unique index covers all of the other columns in your table, it is in essence a primary key itself and could be dropped if you're not.</p> <p>You can check what keys your query is using by prefixing it with EXPLAIN.</p>
<p>Having several indexes including one field is not bad at all (essentially, they do index different things). It has a slight impact on write perfomance, but that's the typical trade-off you have with every index in first place. Having indexes eating up more space than the data itself is not bad if space is cheap. In your case, it should be cheap given the fact that you have a really small amount of entries.</p> <p>The question I would ask in your position is: How does the indexing of such a small table so severly affect my query runtime? Perhaps you are doing something wrong (I think about lots of possibly redundant querys to this table), as a single one should be nowhere near this time range with this small number of entries).</p>
37,286
<p>PL/Ruby is a loadable procedural language for Postgres that lets you use Ruby to write user defined functions for the database.</p> <p>Anyone know of an equivalent way of writing user defined functions for MySQL in Ruby?</p>
<p>Starting from version 5 (I think) Mysql supports <a href="http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html" rel="nofollow noreferrer">stored procedures</a>, but the syntax is restricted to SQL:2003 which is somewhat similar to PL/SQL. </p> <p>Other languages aren't supported and I'm not aware of any projects offering ruby support. Last time I checked the PL/Ruby extensions to postgres were still a bit wonky as well, though.</p>
<p>Mysql as far as I am aware only supports MySQLs own stored procedure language. </p> <p>I'm a postgresql fan too, and this is something that has always frustrated me about MySQL when I have had no choice but to use it. :(</p>
32,026
<p>I was reading googlebooks on chrome, where they talk about why they decided to spin up a process to host browser tab, every time you created a new tab.' So </p> <p>2 tabs = 2 chrome processes</p> <p>3 tabs = 3 chrome processes and so on .. right??</p> <p>But i opened up some 20 or so tabs, but in task manager, i could only find 3 chrome processes.. </p> <p>What is going on??</p> <p>I was taught that creating a process is an expensive proposition in terms of resources needed, and there are other light weight options available (like app domains in .net for ex).. So is chrome taking some hybrid approach?? Create few processes and then start hosting additional tabs inside those limited set of processes??</p>
<p>it's being hosted in the first process. open up chrome. you'll see 2 processes (manager and initial tab). then open 10 more tabs, you'll notice the second process's memory jump a lot. then type in google.com or something into the first tab, and you'll see a new process get spawned.</p> <p>also notice, if you do shift+esc and brink up the task manager in chrome, all those tabs will be grouped together, one w/ memory, the others without.</p>
<p>Process creation is relatively expensive, certainly compared to thread creation. But the frequency of process creation in Chrome is <em>very</em> slow, so the real issue is the amount of resource overhead vs other techniques.</p> <p>The Google team figured that the benefits of a separate process model justified the resource costs. Given the current resources on desktop machines this trade off makes a lot of sense.</p>
6,439
<p>How do I remove items from, or add items to, a select box? I'm running jQuery, should that make the task easier. Below is an example select box.</p> <pre><code>&lt;select name="selectBox" id="selectBox"&gt; &lt;option value="option1"&gt;option1&lt;/option&gt; &lt;option value="option2"&gt;option2&lt;/option&gt; &lt;option value="option3"&gt;option3&lt;/option&gt; &lt;option value="option4"&gt;option4&lt;/option&gt; &lt;/select&gt; </code></pre>
<p>Remove an option:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#selectBox option[value='option1']").remove();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;select name="selectBox" id="selectBox"&gt; &lt;option value="option1"&gt;option1&lt;/option&gt; &lt;option value="option2"&gt;option2&lt;/option&gt; &lt;option value="option3"&gt;option3&lt;/option&gt; &lt;option value="option4"&gt;option4&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>Add an option:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#selectBox").append('&lt;option value="option5"&gt;option5&lt;/option&gt;');</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;select name="selectBox" id="selectBox"&gt; &lt;option value="option1"&gt;option1&lt;/option&gt; &lt;option value="option2"&gt;option2&lt;/option&gt; &lt;option value="option3"&gt;option3&lt;/option&gt; &lt;option value="option4"&gt;option4&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p>
<p>I just want to suggest another way to add an <code>option</code>. Instead of setting the <code>value</code> and <code>text</code> as a string one can also do:</p> <pre><code>var option = $('&lt;option/&gt;') .val('option5') .text('option5'); $('#selectBox').append(option); </code></pre> <p>This is a less error-prone solution when adding options' values and texts dynamically. </p>
49,141
<p>I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible?</p> <p>Bonus question: how would I do it if the stream was in mp3 or other format?</p> <p>This is for windows in native C++.</p>
<p>Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine. If not, this answer isn't relevant.</p> <p>What you want to do isn't trivial. There is a good article <a href="http://www.codeproject.com/KB/audio-video/wavefiles.aspx" rel="nofollow noreferrer">here</a> on code project that describes the windows audio model. It describes how to set up the audio device and how to stream data into the device for playback. You "simply" need to supply data coming in from your socket as data for the playback buffers. But that's where all of the tricky work is. You have to be sure that</p> <ul> <li>You have enough data to begin a playback</li> <li>Handle the case when your socket is starved for data and you have nothing to send to the playback buffer</li> <li>You are able to read data off of the socket with enough speed to keep the playback buffers full</li> </ul> <p>It's an interesting exercise. But tricky.</p>
<p>Mark is right about this being a tricky problem. The waveOutXXXX API is ancient (it predates Windows 95) and requires more error-prone coding than you would think. You will have an easier time interacting with the API in C++ than with C#. Just make sure this is something you really want to do.</p> <p>If your stream is some format other than WAV file data (like MP3 or WMA), you will have to perform the additional step of decoding the data into WAV format and playing it with the waveOutXXXX API. Finding a good component to do MP3 decoding is trickier than you would expect - I think this is related to the Fraunhofer licensing situation (you're supposed to pay them if you use MP3 code in any way).</p> <p><strong>I'd find an off-the-shelf product to do this, unless you want the learning experience.</strong></p>
15,821
<p>I am writing a compiler in F# and I want to be able to access the <a href="http://msdn.microsoft.com/en-us/library/ms404384.aspx" rel="nofollow noreferrer">unmanaged metadata COM interfaces</a> in the .net runtime. Before anybody mentions it, <em>Reflection.Emit is not suitable for my purposes</em>, nor do I want to use any other method than the metadata COM interfaces.</p> <p>I've imported mscoree.tlb but it doesn't seem to include the interfaces I need.</p> <p>The interfaces I'm interested in include <a href="http://msdn.microsoft.com/en-us/library/ms230877.aspx" rel="nofollow noreferrer">IMetaDataEmit</a>. Any sample code relating to this would be very useful, though I've not been able to find any so far.</p> <p>C# samples would be fine as I can easily convert them to F#.</p> <p>Thanks in advance to anybody who can help me with this rather cryptic query!</p> <p><strong>Update:</strong> I have now got this sorted by writing explicit COM references using the interface GUIDs!</p>
<p>I found a possible solution by myself in this MSDN article: <a href="http://msdn.microsoft.com/en-us/library/76e4d2xw.aspx" rel="noreferrer">ClickOnce Deployment and Security</a>.</p> <h2>ASP.NET Form-Based Authentication</h2> <p>If you want to control which deployments each user can access, you should <strong>not enable anonymous access</strong> to ClickOnce applications deployed on a Web server. Rather, you would enable users access to the deployments you have installed based on a user's identity (using Windows NT authentication).</p> <p>If you deploy to an environment without Windows NT authentication, a solution could be to try using <strong>ASP.NET form-based authentication</strong> to authenticate the user. However, ClickOnce does not support forms-based authentication because it uses persistent cookies; these present a security risk because they reside in the Internet Explorer cache and can be hacked. Therefore, if you are deploying ClickOnce applications, any authentication scenario besides Windows NT authentication is unsupported.</p> <h2>Passing Arguments</h2> <p>An additional security consideration occurs if you have to pass arguments into a ClickOnce application. ClickOnce enables developers to supply a query string to applications deployed over the Web. The query string takes the form of a series of name-value pairs at the end of the URL used to start the application:</p> <pre><code>http://servername.adatum.com/WindowsApp1.application?username=joeuser </code></pre> <p>By default, query-string arguments are disabled. To enable them, the attribute <strong>trustUrlParameters must be set in the application's deployment manifest</strong>. This value can be set from Visual Studio and from MageUI.exe. For detailed steps on how to enable passing query strings, see How to: Retrieve Query String Information in a ClickOnce Application.</p> <p>You should never pass arguments retrieved through a query string to a database or to the command line without checking the arguments to make sure that they are safe. Unsafe arguments are ones that include database or command line escape characters that could allow a malicious user to manipulate your application into executing arbitrary commands. </p> <p><em>Note: Query-string arguments are the only way to pass arguments to a ClickOnce application at startup. You cannot pass arguments to a ClickOnce application from the command line.</em> </p>
<p>A ClickOnce installer is just a couple installer files sitting out on your web server, right? So then, you can just implement some sort of directory security on those files. You can do this on a couple different levels I believe; for example IIS permissions or (if your users are on your domain) NTFS permissions.</p> <p>Also, IIS permissions (everything actually?) should be able to be setup programatically.</p>
23,745
<p>In another <a href="https://stackoverflow.com/questions/242650/is-mutation-testing-useful-in-practice">question</a> I asked if <a href="http://en.wikipedia.org/wiki/Mutation_testing" rel="noreferrer">mutation-testing</a> is useful in practice. As I didn't get any answers that satisfy me, I want to check the current tools myself. So I need an overview about current existing mutation-test-frameworks. Which of them are most usable and why?</p> <ul> <li>I program in Java, so I would prefer Java-tools, but I would risk a look at interesting frameworks for different languages.</li> <li>I want to integrate in an automatic build-process, so I would prefer tools that can be executed through command-line.</li> </ul>
<p>There is also <a href="http://pitest.org" rel="noreferrer" title="pit">PIT</a> which can be hooked into your build via a maven plugin or command line interface. </p> <p>It provides much nicer reports than the other available tools with combined mutation and line coverage. It also runs considerably faster than the source based tools for Java such as Jester, and about twice as fast as Jumble.</p> <p>Unlike the Jumble and Javalanche it also works with all the major mocking frameworks (Mockito, JMock, EasyMock, PowerMock and JMockit).</p> <p>(disclosure I'm the author).</p>
<p>Jester does provide a file for the mutations and they are limited. To some degree, you can add your own mutations to the file.</p> <p>I've experimented with Jumble and Jester and I found that Jumble provides more mutations and better documentation. Additionally, I've had quick responses from the project owners when I've emailed them. One drawback to Jumble is that it operates on the bytecode using BCEL. That presents something of a learning curve for many developers. </p> <p>My company, State Farm, wrote an Ant task that we may contribute back to the Jumble project. Based on what I've read in their mailing lists, others are working on an Ant task for Jumble too. </p> <p>I'm looking at Javalanche as well. I’ll be glad to share what I know when I’m done.</p>
30,596
<p>Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?</p>
<p>Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.</p>
<p>Using Management Studio - you may create a Job (unter SQL Server Agent) One Job may include several Steps from T-SQL scripts up to SSIS Packages</p> <p>Jeb was faster ;)</p>
36,509
<p>What kind of performance implications are there to consider when using try-catch statements in php 5? </p> <p>I've read some old and seemingly conflicting information on this subject on the web before. A lot of the framework I currently have to work with was created on php 4 and lacks many of the niceties of php 5. So, I don't have much experience myself in using try-catchs with php.</p>
<p>One thing to consider is that the cost of a try block where no exception is thrown is a different question from the cost of actually throwing and catching an exception.</p> <p>If exceptions are only thrown in failure cases, you almost certainly don't care about performance, since you won't fail very many times per execution of your program. If you're failing in a tight loop (a.k.a: banging your head against a brick wall), your application likely has worse problems than being slow. So don't worry about the cost of throwing an exception unless you're somehow forced to use them for regular control flow.</p> <p>Someone posted an answer talking about profiling code which throws an exception. I've never tested it myself, but I confidently predict that this will show a much bigger performance hit than just going in and out of a try block without throwing anything.</p> <p>Another thing to consider is that where you nest calls a lot of levels deep, it can even be faster to have a single try...catch right at the top than it is to check return values and propagate errors on every call.</p> <p>In the opposite of that situation, where you find that you're wrapping every call in its own try...catch block, your code will be slower. And uglier.</p>
<p>Generally speaking, they're expensive and not worthwhile in PHP.</p> <p>Since it is a checked expressions language, you MUST catch anything that throws an exception.</p> <p>When dealing with legacy code that doesn't throw, and new code that does, it only leads to confusion.</p> <p>Good luck!</p>
12,991
<p>Has anyone ever seen the storage class <code>auto</code> explicitly used in C/C++? If so, in what situation?</p>
<p>auto is never useful in current C/C++ because all variables are implicitly auto. It is useful in C++0x, where it can replace the type declaration entirely - if you have a variable with an initial assignment, 'auto' will just make it the type of that assignment value, as in the comments.</p>
<p>No, it's assumed if you omit the class specifier. The only reasonable uses I can think of would be to call attention to a particular local variable that overrides, say, a global variable with the same name, or as an interview question.</p> <p>Chances are, you'll confuse the poor programmer who's stuck maintaining the code!</p>
31,481
<p>Everybody knows that you should close a connection immediately after you finish using it.</p> <p>Due to a flaw in my domain object model design, I've had to leave the connection open for the full page life cycle. Essentially, I have a Just In Time property which opens a connection on first call, and then on Page.Unload (..) it would check if a db connection was ever open, and then close it if it was. Since it only takes a second, I’ve had the opinion its not too much different than closing it immediately.</p> <p>Is this ok? Or should it still be closed immediately after every single use? </p> <p>Thanks in advance.</p>
<p>No, it is not OK.</p> <p>If your application will ever need to grow or scale, you'll want to fix this issue. By holding that connection open you're reducing your ability to scale. Keep in mind that open connections take up memory on the server, memory on the client, hold open locks, etc.</p>
<p>page crashes? this is what using and finally are for</p> <p>that said, for the sake of DB performance (i.e. scaling)* it's best to keep connections open as short a period as possible allowing only that you don't want to open close open close open close for rapidly sequential and predictable work</p> <p>* I was told this by a mentor early in my career, I must say I've not actually tested this myself but it sounds right theoretically</p>
38,788
<p>Summary for the impatient:</p> <p>What I want to know is what you want to have in a new gui language. About the short answers mentioning <code>$your_favorite_one</code>; I assume you mean that, such a language should look like <code>$your_favorite_one</code>. These are not helpful. Resist the temptation.</p> <p>I'm thinking on the user friendliness of XML based languages such as XHTML (or HTML, although not XML they are very similar), XUL, MXML and others ("others" in this context means that, I am aware of the existence of other languages and their implementations alternative to their original ones, and the purpose of the mentioning only these languages by name is, to give an idea of what I am talking about and I don't feel like mentioning any others and also, I see no point in trying to make a comprehensive list anyway.). I have some opinions about what features should such a language have;</p> <ol> <li>The language should be "human writable" such that, an average developer should be able to code a good amount without constantly referring which tags have which properties, what is allowed inside what. XHTML/HTML is the best one in this regard.</li> <li>There should be good collection of controls built-in for common tasks. XHTML/HTML just sucks here.</li> <li>It should be able to be styled with css-like language (with respect to functionality). It should be easy to separate concerns about the structure and eye-candy. Layout algorithm of this combined whole should be simple and intuitive. Why the hell float removes the element from the layout? Why there is not a layout:not-included or something similar instead?</li> </ol> <p>I know that I don't even mention very important design considerations like interaction with rendering engine and other general purpose languages, data binding, strict XML compliance (ability to define new tags? without namespaces?) but these are the points that I would like to ask what you consider important for such a language?</p>
<p>Most recent XML GUI language (not only for GUI actually) is called XAML. It has all that candies: styles, layout definition, objects initialization, etc. But it's a <strong>pain</strong> to write more or less large XAML files. Auto-completion helps but the core problem - forest of angle brackets - is not solved. Another problem with advanced XML-based GUI langs - they try to serve to several purposes at once, but XML syntax is not suitable for all situations. For example XAML supports data-binding, but why the hell I should write it in attribute string? It's first class feature and should have proper support.</p> <p>IMO all modern XML-based langs suck terribly. Language intended for <em>humans</em> must not force it's users to write tons of brackets or do deep tags nesting. It must be <em>user</em> friendly, not <em>computer</em> friendly. My dream it to have GUI language with Python-like syntax. </p> <h3>In conclusion I want to say:</h3> <p><strong>Dear XML-based langs authors, please be humane, don't create another language based on XML. Read some good book on Domain Specific Languages and please, don't make me type &lt; and > symbols ever again.</strong></p>
<p>You should have specified whether you mean web or rich client, but either way take a look at XAML/WPF. If you're anti-MS, then look at Moonlight, the Mono implementation of SilverLight.</p>
14,444
<p>Has anyone used <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer/" rel="nofollow noreferrer">Pear: Spreadsheet_Excel_Writer</a>?</p> <p>The <a href="http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php" rel="nofollow noreferrer">Formatting Tutorial</a> lists a script similar to what I'm working with: (trimmed down)</p> <pre><code>&lt;?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer(); $worksheet =&amp; $workbook-&gt;addWorksheet(); $worksheet-&gt;write(0, 0, "Quarterly Profits for Dotcom.Com"); $workbook-&gt;send('test.xls'); $workbook-&gt;close(); ?&gt; </code></pre> <p>What I think I understand so far about it...<br> <code>$workbook-&gt;send('test.xls');</code> sets the headers up for Excel file transfer. Now, no errors seem to come up, but the file downloaded is entirely empty (even in a hex editor).</p> <p>So...<br> Where (in what class/method) is the <code>$workbook</code> binary supposed to be written? Or, am I misunderstanding it all?</p> <p><strong>Note</strong>: I honestly don't know what version of Spreadsheet_Excel_Writer is being used; the sources don't include such useful information.<br> I can tell you the copyright is <strong><em>2002-2003</em></strong>; so, anywhere from version 0.1 to 0.6.</p> <p>[<strong>Edit</strong>] Sorry, thought I'd mentioned this somewhere.. This is someone else's script that I've been assigned to fix.</p>
<p>Here is some sample code:</p> <pre><code>&lt;?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer('test.xls'); $worksheet =&amp; $workbook-&gt;addWorksheet('My first worksheet'); if (PEAR::isError($worksheet)) { die($worksheet-&gt;getMessage()); } $workbook-&gt;close(); ?&gt; </code></pre> <p>I think for starters, give your worksheet a name and try to write a file directly (without <code>send()</code>).</p> <p>Also, make sure with all methods you call, test the response with <code>PEAR::isError()</code>.</p>
<p>send() sends cache-control headers and content type headers, but not content. The content is sendt, as I understand from the code, when $workbook->close() is called.</p>
24,258
<p>I'm trying to change the background color of a single subplot in a MATLAB figure.</p> <p>It's clearly feasible since the UI allows it, but I cannot find the function to automate it.</p> <p>I've looked into <code>whitebg</code>, but it changes the color scheme of the whole figure, not just the current subplot. </p> <p>(I'm using MATLAB Version 6.1 by the way)</p>
<p>You can use the set command.</p> <pre><code>set(subplot(2,2,1),'Color','Red') </code></pre> <p>That will give you a red background in the subplot location 2,2,1.</p>
<p>I've not used Matlab in several years, but I think it might well be the whitebg method called after the subplot declaration, similar to the way in which you would set a title.</p> <pre><code>subplot(3, 2, 4), hist(rand(50)), whitebg('y'); </code></pre>
19,068
<p>I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.</p> <p>Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.</p> <p>Net::HTTP doesn't look like the best idea. <a href="http://curb.rubyforge.org/" rel="noreferrer">curb</a> is looking good.</p>
<p>I like <a href="https://github.com/rest-client/rest-client" rel="noreferrer">RestClient</a>. It encapsulates net/http with cool features like multipart form data:</p> <pre><code>require 'rest_client' RestClient.post('http://localhost:3000/foo', :name_of_file_param =&gt; File.new('/path/to/file')) </code></pre> <p>It also supports streaming.</p> <p><code>gem install rest-client</code> will get you started.</p>
<p>I had the same problem (need to post to jboss web server). Curb works fine for me, except that it caused ruby to crash (ruby 1.8.7 on ubuntu 8.10) when I use session variables in the code.</p> <p>I dig into the rest-client docs, could not find indication of multipart support. I tried the rest-client examples above but jboss said the http post is not multipart.</p>
22,275
<p>I'm having trouble with <code>TryUpdateModel()</code>. My form fields are named with a prefix but I am using - as my separator and not the default dot.</p> <pre><code>&lt;input type="text" id="Record-Title" name="Record-Title" /&gt; </code></pre> <p>When I try to update the model it does not get updated. If i change the name attribute to <code>Record.Title</code> it works perfectly but that is not what I want to do.</p> <pre><code>bool success = TryUpdateModel(record, "Record"); </code></pre> <p>Is it possible to use a custom separator?</p>
<p>Another thing to note is that the prefix is to help reflection find the proper field(s) to update. For instance if I have a custom class for my ViewData such as:</p> <pre><code>public class Customer { public string FirstName {get; set;} public string LastName {get; set;} } public class MyCustomViewData { public Customer Customer {get; set;} public Address Address {get; set;} public string Comment {get; set;} } </code></pre> <p>and I have a textbox on my page</p> <pre><code>&lt;%= Html.TextBox("FirstName", ViewData.Model.Customer.FirstName) %&gt; </code></pre> <p>or </p> <pre><code>&lt;%= Html.TextBox("Customer.FirstName", ViewData.Model.Customer.FirstName) %&gt; </code></pre> <p>here is what works</p> <pre><code>public ActionResult Save (Formcollection form) { MyCustomViewData model = GetModel(); // get our model data TryUpdateModel(model, form); // works for name="Customer.FirstName" only TryUpdateModel(model.Customer, form) // works for name="FirstName" only TryUpdateModel(model.Customer, "Customer", form); // works for name="Customer.FirstName" only TryUpdateModel(model, "Customer", form) // do not work ..snip.. } </code></pre>
<p>There is a reason not to use . as ID/Name in HTML bcs it is not standard. For example, the will break if there is a dot in target.</p>
45,221
<p>I have ran into an odd problem with the ActionLink method in ASP.NET MVC Beta. When using the Lambda overload from the MVC futures I cannot seem to specify a parameter pulled from ViewData.</p> <p>When I try this:</p> <pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload(((string)ViewData["groupName"])), "upload new photo") %&gt; </code></pre> <p>The HTML contains a link with an empty URL.</p> <pre><code> &lt;a href=""&gt;upload new photo&lt;/a&gt; </code></pre> <p>However if I hard code the parameter, like this:</p> <pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload("groupA"), "upload new photo") %&gt; </code></pre> <p>The output contains an actual URL.</p> <pre><code> &lt;a href="/group/groupA/Photo/Upload"&gt;upload new photo&lt;/a&gt; </code></pre> <p>I assume this probably has something to do with the visibility and availability of the ViewData, and it not being there when the Lambda gets evaluated by the internals of the framework. But that is just a guess.</p> <p>Am I doing something incorrect in the first sample to cause this, or is this some short of bug? </p> <p><strong>Update</strong>: I am using the latest version of the MVC futures. It has been pointed out that this works for some people. Since it doesn't work for me this makes me think that it is something specific to what I am doing. Does anybody have any suggestion for what to look at next, because this one really has me stumped.</p>
<p>Have you updated your version of the Microsoft.Web.Mvc.dll where the Strongly typed actionlink resides. </p> <p>Apparently this dll has been updated for the Beta release. The function may have been slightly modified.</p> <p>I just tried this </p> <pre><code>&lt;%= Html.ActionLink&lt;HomeController&gt;(x=&gt;x.Search((string)ViewData["search"]), "search?") %&gt; </code></pre> <p>and it worked fine.</p>
<p>Ok, I figured out what my problem was.</p> <p>Apparently I was not even setting the ViewData slot that I was trying to read from in the view, resulting in it being a null value.</p> <p>So effectually I was writing:</p> <pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload(null), "upload new photo") %&gt; </code></pre> <p>I think the ultimate kicker to this whole thing was the fact that the parameter (groupname) represents a non-defaultable value in my routing table.</p> <pre><code>routes.MapRoute( "Group", "group/{groupname}/{controller}/{action}/{id}", new {controller = "Photos", action = "View", Id = ""}); </code></pre> <p>So according to the routing rule the property groupname has to be present, but according go the Lambda gropname was omitted (null). This resulted in the MVC framework being unable to find a route that satisfied my query, and just returning null.</p>
26,540
<p>I have two arrays of <code>System.Data.DataRow</code> objects which I want to compare. </p> <p>The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted. </p> <p><strong>How do I do this in PowerShell?</strong></p>
<p>I wrote a script to do this a little while back. The script (Compare-QueryResults.ps1) is available <a href="http://podcast.acoupleofadmins.com/media/Scripts/Compare-QueryResults.ps1" rel="nofollow noreferrer">here</a> and you will also need my Run-SQLQuery script (available <a href="http://podcast.acoupleofadmins.com/media/scripts/Run-SQLQuery.ps1" rel="nofollow noreferrer">here</a>) or you can replace that with a script or function of your own.</p> <p>Basically, what the script does is take the results of each of your queries and break the datarows apart so that each field is its own object. It then uses Compare-Object to check for any differences between the data in those rows. It returns a comparison object that shows you all the differences between the data returned.</p> <p>The results are an object, so you can save them to a variable and use Sort-Object or the Format-* cmdlets with them.</p> <p>Good luck. If you have any problems with the scripts, let me know, I'd be happy to walk you through them. I've been using them for application testing, seeing what rows are being modified by different actions in a program.</p>
<p>Do you need two arrays of DataRows? the DataRow object has a RowState property which will give you what you require. See the MSDN Docs: <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/</a></p>
4,196
<p>In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?</p> <p>My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. </p> <ul> <li>Do I have to choose between performance and data integrity? </li> <li>If so, is in general better to go one way or is it particular to the case? </li> <li>Are there other alternatives?</li> </ul>
<p><a href="https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734">RichQ's answer</a> is a reasonable technique, if you're using an array, vector, etc. </p> <p>If you're using a collection that isn't indexed by ordinal values... or think you <em>might need to</em> at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated <code>begin()</code>/<code>end()</code> methods:</p> <pre><code>class Blah { public: typedef std::vector&lt;mydata&gt; mydata_collection; typedef myDataCollection::const_iterator mydata_const_iterator; // ... mydata_const_iterator data_begin() const { return myPreciousData.begin(); } mydata_const_iterator data_end() const { return myPreciousData.end(); } private: mydata_collection myPreciousData; }; </code></pre> <p>...which you can then use in the normal fashion:</p> <pre><code>Blah blah; for (Blah::mydata_const_iterator itr = blah.data_begin(); itr != blah.data_end(); ++itr) { // ... } </code></pre>
<p>Using const is a reasonable choice. You may also wish to check out the boost C++ library for their shared pointer implementation. It provides the advantages of pointers i.e. you may have the requirement to return a shared pointer to "null" which a reference would not allow.</p> <p><a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm</a></p> <p>In your case you would make the shared pointer's type const to prohibit writes.</p>
6,644
<p>I wish to use the Validating event on a label in VB.Net (Visual Studio 2005, .Net Runtime 2.0).</p> <p>I have two text boxes side by side. These are for a %/% split allocation, such as 80/20, 50/50, etc. So, I have validation on each box to ensure that their values are >= 0 and &lt;= 100. It is my desire to have the label off to the left of the textboxes have its own validation, which will ensure that the two text box values total exactly 100. </p> <p>I know I can do this in the individual text box Validating event. I just do not want that behavior. I would rather have a discrete message on each text box, stating that its contents are outside the valid domain of values, and have an error message by the label if their total is not 100.</p> <p>The problem is that, despite setting CausesValidation = True on the Label controls, their Validating events do not fire. Even manually calling Me.ValidateChildren() at the form level will not fire the event for labels.</p> <p>Any ideas?</p>
<p>validation events are for controls that have editable values. labels do not have editable values.</p> <p>your situation is not uncommon, you have a field-level validation that says 'positive integer' and a business rule that says the sum of values A and B must equal 100%.</p> <p>one way to handle this is to delay enforcing the business rule until the form is completed; this would entail validating the business rule when the user clicks the OK button (or Submit button in a web form)</p> <p>if you want instant validation, just have the validation method for both fields call the business-rule validation method</p>
<p>May I ask is this a web or form project?</p> <p>User's cannot enter any data into a label, so I don't see why they would fire validation.</p>
34,943
<p>No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables.</p> <p>But what kind of prefix do you use?</p> <p>I have been working on projects where we used <strong>m_</strong> as prefix, on other projects we used an underscore only (which I personally don't like, because an underscore only is not demonstrative enough).</p> <p>On another project we used a long prefix form, that also included the variable type. <strong>mul_</strong> for example is the prefix of a <strong>m</strong>ember variable of type <strong>u</strong>nsigned <strong>l</strong>ong.</p> <p>Now let me know what kind of prefix you use (and please give a reason for it).</p> <p><strong>EDIT:</strong> Most of you seem to code without special prefixes for member variables! Does this depend on the language? From my experience, <strong>C++ code</strong> tends to use an underscore or <strong>m_</strong> as a prefix for member variables. What about other languages?</p>
<blockquote> <p>No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables.</p> </blockquote> <p>I dispute this claim. It's not the least bit necessary if you have half-decent syntax highlighting. A good IDE can let you write your code in readable English, and can show you the type and scope of a symbol other ways. Eclipse does a good job by highlighting declarations and uses of a symbol when the insertion point is on one of them.</p> <p>Edit, thanks slim: A good syntax highlighter like Eclipse will also let you use bold or italic text, or change fonts altogether. For instance, I like italics for static things.</p> <p>Another edit: Think of it this way; the type and scope of a variable are secondary information. It should be available and easy to find out, but not shouted at you. If you use prefixes like <code>m_</code> or types like <code>LPCSTR</code>, that becomes noise, when you just want to read the primary information – the intent of the code.</p> <p>Third edit: This applies regardless of language.</p>
<p>None if it's not necessary, single underscore otherwise. Applies for python.</p>
13,682
<p>I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.</p>
<pre><code>setTimeout(function() { $('#foo').fadeOut(); }, 5000); </code></pre> <p>The 5000 is five seconds in milliseconds.</p>
<p>You can avoid using setTimeout by using the fadeTo() method, and setting a 5 second delay on that.</p> <pre><code>$("#hideAfterFiveSeconds").click(function(){ $(this).fadeTo(5000,1,function(){ $(this).fadeOut("slow"); }); }); </code></pre>
31,273
<p>As just stated in a recent <a href="https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory">question</a> and <a href="https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory#135772">answer</a>, you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.</p>
<p>Module == static class</p> <p>If you just want a class that you can't inherit, use a <code>NotInheritable</code> class; but it won't be static/Shared. You could mark all the methods, properties, and members as <code>Shared</code>, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.</p> <p>If you really want the VB.Net equivalent to a C# static class, use a <code>Module</code>. It can't be inherited and all members, properties, and methods are static/shared.</p>
<p>From the CLR point of view, C# static class is just "sealed" and "abstract" class. You can't create an instance, because it is abstract, and you can't inherit from it since it is sealed. The rest is just some compiler magic.</p>
16,449
<p>What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?</p>
<p><a href="http://search.cpan.org/perldoc?CPAN::Mini" rel="noreferrer">CPAN::Mini</a> is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a "file:" URL like this:</p> <pre><code>file:///path/to/my/cpan/mirror </code></pre> <p>If you'd like your mirror to have copies of development versions of CPAN distribution, you can use <a href="http://search.cpan.org/perldoc?CPAN::Mini::Devel" rel="noreferrer">CPAN::Mini::Devel</a>.</p> <p>Update: </p> <p>The <a href="http://www.cpan.org/misc/cpan-faq.html#How_mirror_CPAN" rel="noreferrer">"What do I need to mirror CPAN?"</a> FAQ given in another answer is for mirroring <em>all</em> of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.</p>
<p>Try <a href="http://search.cpan.org/perldoc/CPAN::Mini" rel="nofollow noreferrer">CPAN::Mini</a>.</p>
10,317
<p>Is there any difference between</p> <pre><code> int on_exit(void (*function)(int , void *), void *arg); </code></pre> <p>and</p> <pre><code> int atexit(void (*function)(void)); </code></pre> <p>other than the fact that the function used by on_exit gets the exit status?</p> <p>That is, if I don't care about the exit status, is there any reason to use one or the other?</p> <p><strong>Edit:</strong> Many of the answers warned against <code>on_exit</code> because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? </p>
<p>According to <a href="http://www.delorie.com/gnu/docs/glibc/libc_560.html" rel="noreferrer">this link</a> I found, it seems there are a few differences. <code>on_exit</code> will let you pass in an argument that is passed in to the <code>on_exit</code> function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit.</p> <p>Furthermore, it appears that <code>on_exit</code> was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive.</p>
<p>@Nathan</p> <p>First, see if there is another API call to determine exit status... a quick glance and I don't see one, but I am not well versed in the standard C API.</p> <p>An easy alternative is to have a global variable that stores the exit status... the default being an unknown error cause (for if the program terminates abnormally). Then, when you call exit, you can store the exit status in the global and retrieve it from any atexit functions. This requires storing the exit status diligently before every exit call, and clearly is not ideal, but if there is no API and you don't want to risk <code>on_exit</code> not being on the platform... it might be the only option.</p>
3,189
<p>I need to manipulate 100,000 - 200,000 records.<br> I am thinking of using LINQ (to SQL) to do this.<br> I know from experience that filtering dataviews is very slow.<br> So how quick is LINQ?<br> <br> Can you please tell me your experiences and if it is worth using, or would I be better off using SQL stored procedures (heavy going and less flexible)? <br> <br> Within the thousands of records I need to find groups of data and then process them, each group has about 50 records.</p>
<p>LINQ to SQL translates your query expression into T-SQL, so your query performance should be exactly the same as if you sent that SQL query via ADO.NET. There is a little overhead I guess, to convert the expression tree for your query into the equivalent T-SQL, but my experience is that this is small compared with the actual query time.</p> <p>You can of course find out exactly what T-SQL is generated, and therefore make sure you have good supporting indexes.</p> <p>The primary difference from DataViews is that LINQ to SQL does not bring all the data into memory and filter it there. Rather it gets the database to do what it's good at and only brings the matching data into memory.</p>
<p>Normally the manipulation of that many records should happen as close as possible to the db. If it where my task I would look to do it in stored procs. That me personally. Linq is yet another layer of abstraction on top of data access and while it works well for "normal" needs i.e. a few hundred entities sent to the UI it should not be thought of as a replacement for data warehouse type operations. </p>
14,123
<p>Let's pretend I have the following xaml...</p> <p></p> <pre><code>&lt;UserControl.Resources&gt; &lt;local:ViewModel x:Name="viewModel" /&gt; &lt;local:LoadChildrenValueConverter x:Name="valueConverter" /&gt; &lt;/UserControl.Resources&gt; &lt;UserControl.DataContext&gt; &lt;Binding Source="{StaticResource viewModel}" /&gt; &lt;/UserControl.DataContext&gt; &lt;Grid x:Name="LayoutRoot" Background="White"&gt; &lt;control:TreeView ItemsSource="{Binding Root}"&gt; &lt;control:TreeView.ItemTemplate&gt; &lt;control:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource valueConverter}}"&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/control:HierarchicalDataTemplate&gt; &lt;/control:TreeView.ItemTemplate&gt; &lt;/control:TreeView&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>...and the following code to go with it...</p> <pre> using System; using System.Collections.ObjectModel; using System.Windows.Data; namespace SilverlightViewModelSpike { public class ViewModel { public ViewModel() { Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public ObservableCollection Root { get; private set; } } public class LoadChildrenValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } </pre> <p>This works as expected, but it feels wrong that I have two separate classes that are required in order to grab the needed data for my view (imagine that ViewModel and LoadChildrenValueConverter pulled data from a web service instead of returning hard coded data). Is there a better solution here? I was thinking maybe something like this...</p> <pre> using System; using System.Collections.ObjectModel; using System.Windows.Data; namespace SilverlightViewModelSpike { public class ViewModel { public ViewModel() { Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; ValueConverter = new LoadChildrenValueConverter(); } public ObservableCollection Root { get; private set; } public LoadChildrenValueConverter ValueConverter { get; private set; } } public class LoadChildrenValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } </pre> <p>... but then i can't get this line to work...</p> <p><code>&lt;control:HierarchicalDataTemplate ItemsSource="{???}"</code>></p> <p>...and even that doesn't seem like a great solution. Does anyone have a nice clean solution for this?</p>
<p>Since you're using a ViewModel to sit between your actual model and your view, I wonder if it's easier just to implement the IValueConverter logic directly in there. Sort of like:</p> <pre><code>public class ViewModel { public ObservableCollection Root { get; set: } public ObservableCollection Children { get { /* return children items */ } } } </code></pre> <p>Then you can simply bind directly to your second property:</p> <pre><code>&lt;control:HierarchicalDataTemplate ItemsSource="{Binding Children}"&gt; </code></pre> <p>I think the main purpose of a ViewModel object is to limit the number of "tricks" (such as IValueConverters) you need to pull to get the data you need from the original model. Since you have one, you might as well make use of it.</p> <p><strong>Edit 1</strong></p> <p>... and of course now that I re-read your post I see that there's more to it. You're getting the children for each item in your "Root" collection.</p> <p>How about implementing the IValueConverter as a static instance in your ViewModel itself?</p> <pre><code>public class ViewModel : IValueConverter { public static readonly IValueConverter ChildrenConverter = new LoadChildrenValueConverter(); } </code></pre> <p>Now you should be able to say:</p> <pre><code>&lt;control:HierarchicalDataTemplate ItemsSource="{Binding Converter={x:Static local:ViewModel.ChildrenConverter}}"&gt; </code></pre> <p><strong>Edit 2</strong></p> <p>Ok, you're using Silverlight so {x:Static} isn't available to you.</p> <p>The only other option I can think of that will let you reuse the one static resource instead of having to declare two is to implement the IValueConverter directly in your ViewModel. This is no good if you will need to do more than one type of conversion, but if your ViewModel is very narrow-focused then it could do the job. So:</p> <pre><code>public class ViewModel : IValueConverter { // move your Convert and ConvertBack methods into here } </code></pre> <p>Now you can do this:</p> <pre><code>&lt;control:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource ViewModel}}"&gt; </code></pre>
<p>Sorry guys I am a little confused about what you are trying to do here... Anyway, from the title it sounds as if you want to a property in your value converter to a property in your value converter. Firstly have a look at an article I have written explaining exactly how you can do that: <a href="http://nick-howard.blogspot.com/2011/06/silverlight-4-value-converter.html" rel="nofollow">http://nick-howard.blogspot.com/2011/06/silverlight-4-value-converter.html</a></p> <p>So what you would do is create an ObvervableCollection dependency property in your LoadChildrenValueConverter, for arguments sake let’s call it Children.</p> <p>Then in your xaml you can change the LoadChildrenValueConverter to something like this: </p> <p>That way you are only calling the web service once from your view model, and you are then sharing that ObvervableCollection in your view model with your value converter.</p> <p>Hope that helps.</p>
48,321
<p>Well, it seems simple enough, but I can't find a way to add a caption to an equation. The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.</p>
<p>The <code>\caption</code> command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:</p> <pre><code>\begin{figure} \[ E = m c^2 \] \caption{A famous equation} \end{figure} </code></pre> <p>The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The <code>\captionof</code> command of the <a href="http://www.tex.ac.uk/tex-archive/macros/latex/contrib/caption/caption-eng.pdf" rel="noreferrer">caption package</a> can be used to place a caption outside of a floating environment. It is used like this:</p> <pre><code>\[ E = m c^2 \] \captionof{figure}{A famous equation} </code></pre> <p>This will also produce an entry for the <code>\listoffigures</code>, if your document has one.</p> <p>To align parts of an equation, take a look at the <a href="http://www.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-223.html" rel="noreferrer"><code>eqnarray</code> environment</a>, or some of the environments of the <a href="http://www.ams.org/tex/amslatex.html" rel="noreferrer">amsmath</a> package: align, gather, multiline,...</p>
<p>You may want to look at <a href="http://tug.ctan.org/tex-archive/macros/latex/contrib/float/" rel="nofollow noreferrer"><a href="http://tug.ctan.org/tex-archive/macros/latex/contrib/float/" rel="nofollow noreferrer">http://tug.ctan.org/tex-archive/macros/latex/contrib/float/</a></a> which allows you to define new floats using <code>\newfloat</code></p> <p>I say this because captions are usually applied to floats.</p> <p>Straight ahead equations (those written with <code>$ ... $</code>, <code>$$ ... $$</code>, <code>begin{equation}...</code>) are in-line objects that do not support <code>\caption</code>.</p> <p>This can be done using the following <a href="https://tex.stackexchange.com/a/97034/149720">snippet</a> just before <code>\begin{document}</code></p> <pre><code>\usepackage{float} \usepackage{aliascnt} \newaliascnt{eqfloat}{equation} \newfloat{eqfloat}{h}{eqflts} \floatname{eqfloat}{Equation} \newcommand*{\ORGeqfloat}{} \let\ORGeqfloat\eqfloat \def\eqfloat{% \let\ORIGINALcaption\caption \def\caption{% \addtocounter{equation}{-1}% \ORIGINALcaption }% \ORGeqfloat } </code></pre> <p>and when adding an equation use something like</p> <pre><code>\begin{eqfloat} \begin{equation} f( x ) = ax + b \label{eq:linear} \end{equation} \caption{Caption goes here} \end{eqfloat} </code></pre>
18,011
<p>What the difference between <code>Application("some-object")</code> and <code>Cache("some-object")</code> in ASP.NET?</p>
<p>Application is an application wide, no timeout (except when the pool restarts) dictionary. The cache is a temporary repository for common cache storage.</p> <p><a href="http://www.eggheadcafe.com/articles/20030405.asp" rel="nofollow noreferrer">This</a> And <a href="http://bytes.com/forum/thread314515.html" rel="nofollow noreferrer">This</a> might help clarify the differences and usages.</p> <p><a href="http://wiki.asp.net/page.aspx/59/application-and-cache/" rel="nofollow noreferrer">Here</a> is another one.</p>
<p>Application and cache are both application level storage of item, but difference is that in usage cenario , like cache is more flexible can do much more like scavenges ( removes unimortent item from cache automaticaly) ,but cache on othere side is volatilemeans that it is not sure that data will stay for application life .But Application is more relaibrel ,data stays when ever application is running but it is simple .</p>
16,529
<p>I know that that is not a question... erm anyway HERE is the question.</p> <p>I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries.</p> <pre><code>ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe </code></pre> <p>A sample of the data would be something like this</p> <pre><code>id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 </code></pre> <p>It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry</p> <p>The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables.</p> <p>(It is hard to draw the diagram!)</p> <pre><code>Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID </code></pre> <p>Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table?</p> <p>I can do it for one Country (this is a select to show what I want out)</p> <pre><code>SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); </code></pre> <p>(the mega table is called species)</p> <p>But using this strategy I would need to do the query for each column in the original table. </p> <p>Is there a way of doing this in sql?</p> <p>I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though!</p> <p>Any thoughts (or clarification required)?</p>
<p>I would use a script to generate all the individual queries, since this is a one-off import process.</p> <p>Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are.</p> <p>However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.</p>
<p>You're probably going to want to create replacement tables in place. The script sort of depends on the scripting language you have available to you, but you should be able to create the country ID table simply by listing the columns of the table you have now. Once you've done that, you can do some string substitutions to go through all of the unique country names and insert into the speciesFoundInCountry table where the given country column is not null.</p>
10,258
<p>Well I'm new to OOP in PHP and am trying to write a site with it. The site is a basic flash games site and has categories to track the games. My first step was to create a basic MVC setup and list all the categories. The problem is I don't know how to create an array with all of the categories in it. Can I add this to the controller? Should I be adding a new method to the model? Let me know, code is below.</p> <p><strong>index.php</strong> (controller)</p> <pre><code>&lt;?php require_once 'database.php'; require_once 'models/category.php'; if (isset($_GET['page'])) { } else { //display home page require_once 'views/home.php'; } ?&gt; </code></pre> <p><strong>models/category.php</strong> (model)</p> <pre><code>&lt;?php class Category { private $id,$name; function __construct($id) { $category_query = $database_connection-&gt;prepare('SELECT id,name FROM categories WHERE id=?'); $category_query-&gt;execute(array($id)); $category = $category_query-&gt;fetch(); $this-&gt;id = $category['id']; $this-&gt;name = $category['name']; } function get_id() { return $this-&gt;id; } function get_name() { return $this-&gt;name; } } ?&gt; </code></pre> <p><strong>views/home.php</strong> (view)</p> <pre><code>List of all categories: &lt;ul&gt; &lt;?php foreach ($all_categories as $category) { ?&gt; &lt;li&gt;&lt;?php echo $category-&gt;get_name(); ?&gt; (ID: &lt;?php echo $category-&gt;get_id(); ?&gt;)&lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; </code></pre>
<p>Very simply, you're just missing the glue to put it all together. This is often described as the "business logic". What you currently have as your "model" is actually your data storage layer. Your model needs to use this to return to the controller what it needs to give to the view. </p> <p>Down in the code, you have several alternatives. One would be for the controller to use the data class you have to assemble the array the view wants to use. This is best if no other controller will need to do that. Another solution would be to add some model code to do that. This enables other controllers to call the same model to get the same data, but if you have other classes that need the same procedure, you would be repeating code. The third solution is to extend your data model to provide a collection view. Then the model code becomes a simple translation layer between what sort of collection the controller wants and asking the data model for it. It might even be simple enough to leave in the controller.</p>
<p>Like Staticsan said, there's lots of places you can put it, and books written about it. I'd change the constructor so that if you give it no arguments, it does no query. Then I'd use a static method that does its own query of all categories (or some subset) and then assembles an array of Category objects to return... </p> <p>Probably better is to write a class called CategoryFactory that is just responsible for making and returning these objects. From there (or from the static method factory) you can make sure you're only doing one query.</p> <p>MVC is not the end all be all for web application architecture, Fowler and Alur et al go into the shady details.</p>
43,615
<p>I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a <em>good</em> thing.</p> <p>Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?</p>
<p>Consider a simple shopping cart application that uses a <code>CartContents</code> class to keep track of the items in the shopping cart and an <code>Order</code> class for processing a purchase. The <code>Order</code> needs to determine the total value of the contents in the cart, it might do that like so:</p> <p><strong>Tightly Coupled Example:</strong></p> <pre class="lang-cs prettyprint-override"><code>public class CartEntry { public float Price; public int Quantity; } public class CartContents { public CartEntry[] items; } public class Order { private CartContents cart; private float salesTax; public Order(CartContents cart, float salesTax) { this.cart = cart; this.salesTax = salesTax; } public float OrderTotal() { float cartTotal = 0; for (int i = 0; i &lt; cart.items.Length; i++) { cartTotal += cart.items[i].Price * cart.items[i].Quantity; } cartTotal += cartTotal*salesTax; return cartTotal; } } </code></pre> <p>Notice how the <code>OrderTotal</code> method (and thus the Order class) depends on the implementation details of the <code>CartContents</code> and the <code>CartEntry</code> classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a <code>List&lt;CartEntry&gt;</code> collection to keep track of the items we'd have to change the <code>Order</code> class as well.</p> <p>Now here's a slightly better way to do the same thing:</p> <p><strong>Less Coupled Example:</strong></p> <pre class="lang-cs prettyprint-override"><code>public class CartEntry { public float Price; public int Quantity; public float GetLineItemTotal() { return Price * Quantity; } } public class CartContents { public CartEntry[] items; public float GetCartItemsTotal() { float cartTotal = 0; foreach (CartEntry item in items) { cartTotal += item.GetLineItemTotal(); } return cartTotal; } } public class Order { private CartContents cart; private float salesTax; public Order(CartContents cart, float salesTax) { this.cart = cart; this.salesTax = salesTax; } public float OrderTotal() { return cart.GetCartItemsTotal() * (1.0f + salesTax); } } </code></pre> <p>The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.</p>
<p>Loose coupling, in general, is 2 actors working independently of each other on the same workload. So if you had 2 web servers using the same back-end database, then you would say that those web servers are loosely coupled. Tight coupling would be exemplified by having 2 processors on one web server... those processors are tightly coupled.</p> <p>Hope that's somewhat helpful.</p>
28,079
<p>I have just built my Anet A8 and it won't print. </p> <p>I will preheat it (190°C 60°C) and then press "<code>Print File</code>" and select, then it starts for a second, gets to around 11% and stops and shows "<code>Preheat PLA</code>". The PLA is already preheated - it is coming out of the nozzle. </p> <p>Any help would be appreciated.</p>
<p>I had a similar problem last week where the thermostat's heat shrink was being melted by the block and the two wires were touching. I fixed this by securing the thermistor and putting a thermal insulator between the block and the wires. I also put a small piece of heat shrink between the wires to insulate them so they will never touch. Thank you and I hope this helps.</p>
<p>The Anet A8 files that come preloaded are <code>.stl</code> so if you try to print those it will say printing zero percent and then just switch right back to preheating PLA without any error message. Download a free slicer tool if that's the case.</p>
580
<p>In our legacy system, we wrote our own VM to execute our internal DSL at run time. The in-house VM was designed to run our internal DSL only. We are in the process of rewriting our legacy application. One of the idea we are considering is, to transform our internal DSL to external DSL (C# or Java) and take advantage of their VM. </p> <p>There are no clear guide lines when to write our own VM for our intenral DSL vs. transforming to external DSL and running it that VM. </p>
<p>The internal DSL/VM vs. external DSL/VM decision is the same as all build vs. buy vs. download decisions. The guidelines are clear and the same for all software.</p> <p>Why support your own VM, when someone else will support Java or Python for you?</p> <p>Here's some clear guidelines. Note that these are the same guidelines for all software.</p> <ol> <li><p>Is it cheaper for you to continue to maintain your own software. In this case, DSL and VM? </p></li> <li><p>Is your own DSL and VM better than Java or Python? By "better", you must fill in any combination of quality factors: faster, smaller, more reliable, better features, less resource use, more auditable, more secure, etc.</p></li> </ol> <p>Don't be confused by DSL and VM. It's nothing special; it's just more software.</p>
<p>It is definitely not an anti-pattern. External DSLs have many advantages compared to the internal ones. Independence from the host language or implementation platform in your case is one of them. Other benefits are better syntax flexibility, possibility to use model driven approches like model transformations, model viewing and others.</p>
23,645