instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Using Windows key as Meta is very useful in Emacs, is there the way to do it in Vim?</p>
<p>You can use <a href="http://www.autohotkey.com/docs/misc/Remap.htm" rel="noreferrer">AutoHotkey to map</a> the windows key to a different key. Only activate the mapping when vim is active:</p> <pre><code>#IfWinActive ahk_class GVIM RWin::Alt LWin::Alt #IfWinActive ; This puts subsequent remappings and hotkeys in effect for all windows. </code></pre>
<p>Not quite sure, but the <kbd>Ctrl</kbd>+<kbd>Esc</kbd> key combo is a windows only key mapping. It won't help with vim</p>
42,427
<p>In my views I use a helper that takes arbitrary HTML as a block:</p> <pre><code>&lt;% some_block_helper do %&gt; Some arbitrary HTML and ERB variables here. More HTML here. &lt;% end %&gt; </code></pre> <p>My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.</p>
<p>To add just a bit to what James said, I think something like this should work just fine:</p> <pre><code>describe SomeHelper do it 'should do something' do helper.some_block_helper { the_block_code }.should XXXX end end </code></pre>
<ol> <li>For a functional test, write a normal <a href="http://rspec.info/documentation/rails/writing/views.html" rel="nofollow noreferrer">view spec</a> and test the result.</li> <li>To unit test your <a href="http://rspec.info/documentation/rails/writing/helpers.html" rel="nofollow noreferrer">helper</a>, pass an arbitrary html input string to it directly.</li> </ol> <p>If there's any other difficulty I'm missing, please comment?</p>
23,978
<p>Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (<a href="http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx</a>). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window or on the DOM element, and I cannot find it anywhere.</p> <p>Does someone know how you can obtain a reference to the instance?</p> <p>Best regards,</p> <p>JacobE</p>
<p>Does the $find() routine find it?</p>
<p>Yes, the $find method turned out to be the solution for me.</p> <p>I could probably also use the return value of $create if I had any influence on how the javascript was rendered on the page - but unfortunately I didn't... :-)</p>
27,894
<h2>Summary</h2> <p>Is that possible for webapps deployed on linux + tomcat5.5 to use/see all <code>/usr/share/java/</code> jars automatically?</p> <h2>Details</h2> <p>I'm packaging my java webapp for Ubuntu (yet the question is related to any linux-based distro) and going to make it depend on tomcat.</p> <p>I'm going to put context descriptor (an xml file) to <code>/usr/share/tomcat5.5/conf/Catalina/localhost/</code> to make my app deployed. Having my web dir here: <code>/usr/share/&lt;appname&gt;/web</code>, how can I enable my app to use java jar libs installed in the system (<code>/usr/share/java</code>)?</p> <p>I can't just symlink <code>/usr/share/java -&gt; &lt;webdir&gt;/WEB-INF/lib</code>, since I have my custom jars need to be placed in <code>lib</code> dir.</p> <h2>Bad Solution</h2> <p>The solution I've found so far is to symlink each required jar to <code>&lt;webdir&gt;/WEB-INF/lib/</code>.</p> <p>This is not so good, because I have to symlink a lot of jars and even worse to symlink all jars my direct dependency lib (jar) requires (and so on). In case my direct dependency lib changes its list of required jars I'll have to maintain that symlinks.</p>
<p>According to <a href="http://tomcat.apache.org/tomcat-5.5-doc/class-loader-howto.html" rel="nofollow noreferrer">the Tomcat classloading documentation</a>, you need to put any shared libs that should be available to all Tomcat apps in the $CATALINA_BASE/shared/lib library -- so one way to do what you're looking to do is to move your libraries from /usr/share/java to $CATALINA_BASE/shared/lib.</p> <p>BUt if I'm not misunderstanding that same documentation, Tomcat also makes the system-wide CLASSPATH variable's contents available to the classloader at launch, so if your directory -- /usr/share/java -- were included in the system-wide CLASSPATH variable, then that should work too. I've never done this, though; Tomcat's method of making the contents of $CATALINA_BASE/shared/lib available Tomcat-wide has always served me perfectly.</p>
<p>You should not do that. Java EE applications are the supposed to be self sufficient and not depend on any resources outside the deployment package other than those provided by the container. So you should take the libs you need from that directory and add it to your war or ear package. </p> <p>This guarantees that your application will behave the same wherever you deploy it and you will not be subject to unexpected changes in the versions of the libs in /usr/share/java....</p>
14,049
<ul> <li>You can use App.config; but it only supports key/value pairs.</li> <li>You can use .Net configuration, configuration sections; but it can be really complex.</li> <li>You can use Xml Serialization/Deserialization by yourself; your classes-your way.</li> <li>You can use some other method; what can they be? ...</li> </ul> <p>Which of these or other methods (if there are) do you prefer? Why?</p>
<p>When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section):</p> <p>Define your custom section:</p> <pre><code> public class CustomSection : ConfigurationSection { [ConfigurationProperty("LastName", IsRequired = true, DefaultValue = "TEST")] public String LastName { get { return (String)base["LastName"]; } set { base["LastName"] = value; } } [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")] public String FirstName { get { return (String)base["FirstName"]; } set { base["FirstName"] = value; } } public CustomSection() { } } </code></pre> <p>Programmatically create your section (if it doesn't already exist):</p> <pre><code> // Create a custom section. static void CreateSection() { try { CustomSection customSection; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe"); // Create the section entry // in the &lt;configSections&gt; and the // related target section in &lt;configuration&gt;. if (config.Sections["CustomSection"] == null) { customSection = new CustomSection(); config.Sections.Add("CustomSection", customSection); customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } catch (ConfigurationErrorsException err) { //manage exception - give feedback or whatever } } </code></pre> <p>Following CustomSection definition and actual CustomSection will be created for you:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" /&gt; &lt;/configSections&gt; &lt;CustomSection LastName="TEST" FirstName="TEST" /&gt; &lt;/configuration&gt; </code></pre> <p>Now Retrieve your section properties:</p> <pre><code> CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection"); string lastName = section.LastName; string firstName = section.FirstName; </code></pre>
<p>I keep most of my config in IoC container, e.g. Spring.Net.</p>
14,299
<p>A lot of programming languages and frameworks do/allow/require something that I can't seem to find the name for, even though there probably is one in computer science. What they basically do is bind to a variable/object/class/function by name. </p> <p><a href="http://www.adobe.com/products/flex/" rel="noreferrer">Flex</a> example ("selectAll()"):</p> <pre><code>&lt;mx:Button click="selectAll()" label="Select All"/&gt; </code></pre> <p><a href="http://mate.asfusion.com/" rel="noreferrer">Mate</a> example ("price"):</p> <pre><code>&lt;Injectors target="{QuotePanel}"&gt; &lt;PropertyInjector targetKey="price" source="{QuoteManager}" sourceKey="currentPrice" /&gt; &lt;/Injectors&gt; </code></pre> <p>Java example ("Foo"):</p> <pre><code>Class.forName("Foo") </code></pre> <p>There are many other examples. You get the idea. What troubles me is that there is virtually no way to verify this at compile-time, and not much the IDE can do to help in terms of code completion, navigation, and refactoring. But that's besides the point.</p> <p>My question is, what is this called? <strong><em>I don't think it's one of these: <a href="http://en.wikipedia.org/wiki/Dynamic_binding" rel="noreferrer">dynamic binding</a>, <a href="http://en.wikipedia.org/wiki/Name_binding" rel="noreferrer">name binding</a>, <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)" rel="noreferrer">reflection</a></em></strong></p> <p><strong>Update</strong>: No, this is not a quiz, sorry if it sounds like one. It's simply a matter of "name that song" for programming.</p> <p><strong>Update</strong>: Answers that helped:</p> <ul> <li>From Tim Lesher: It's called "late binding", "dynamic binding", or "runtime binding". <em>The fact that it binds by a string is just an implementation detail</em>...</li> <li>From Konrad Rudolph: ...<em>it's simply input for an interpreter</em>.</li> </ul> <p><strong>Update</strong>: As people have correctly pointed out, some of the examples are late binding, some are reflection, some are runtime-evaluation (interpretation), etc. However, I conclude there probably is no name that describes them all. It's just a bunch of examples that do have something in common, but not enough to give it a name. I liked the "everything is a string" answer, but even though it's funny, it doesn't fully do it justice either.</p>
<p>It's called "late binding", "dynamic binding", or "runtime binding". The fact that it binds by a string is just an implementation detail, although it does imply that the string-to-symbol mapping exists at runtime (which some languages, like c++, don't provide).</p> <p>"Introspection" or "reflection", on the other hand, refer to the ability to find out what interfaces, methods, or attributes an object implements at runtime.</p> <p>It's true that dynamically-bound symbols can't be verified before execution; that's what makes them different from statically-bound symbols. </p>
<p>In the .NET world we call this databinding, and it has handled using reflection.</p> <p>It also reminds me strongly of dependency injection.</p>
24,162
<p>Microsoft has come out with this fairly new technology that I am considering using for a .NET 3.5 application. I am curious, is anyone using this technology already? I am worried that the use of the secure virtual machine will negatively affect performance. Also, the way Microsoft advertises the product, it seems as though the licensing integration is very seamless and does not require any development work in the code. It seems like a great product but I want to make sure I know of any pitfalls before committing to it.</p>
<p>Microsoft announced today that they <a href="http://blogs.zdnet.com/microsoft/?p=1624" rel="nofollow noreferrer">are not accepting any new customers</a> for SLP. Sounds like the whole program is going down the drain... I'm glad my company didn't sign up for it yet!</p>
<p>It seems that SLP does not support .NET 3.5 at the moment. </p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3526285&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3526285&amp;SiteID=1</a></p> <p>Your best bet would be to implement an auxiliary DLL containing SLP API calls in .NET 2.0 or 3.0, secure it and add it as a reference to your .NET 3.5 app.</p>
18,507
<p>It would be helpful to me if I knew in advance how much the <strong><em>empty</em></strong> filament spool weighs. </p> <p>Not having emptied any spool yet, I can't contribute data points, but has anyone compiled a list of empty weights from various manufacturers and sizes?</p>
<p>Yes, there is a table on <a href="https://www.reddit.com/r/3Dprinting/comments/4hlwse/empty_spool_weights_for_estimating_remaining/" rel="nofollow noreferrer">Reddit - Empty spool weights for estimating remaining filament</a> which suggests that the norm (in 2015) was between 170 and 330 grams for a 1&nbsp;kg spool, superficially in a bimodal distribution clustered around the high and low points. Presumably these were for 3&nbsp;mm filament, this post dating to before the popularity of 1.75&nbsp;mm...</p> <p>Manufacturer's have an incentive to reduce the mass of their spools, or even ship without spools, since the shipping cost will eat into their profit margin.</p>
<p>Following on from <a href="https://3dprinting.stackexchange.com/questions/6558/is-there-a-table-or-list-of-tare-weights-of-empty-spools-of-various-manufacturer/6560#6560">Sean's excellent answer</a>, here is the (out of date) table in question: </p> <p><a href="https://i.stack.imgur.com/9Mdi0.png" rel="nofollow noreferrer" title="Empty spool weight table"><img src="https://i.stack.imgur.com/9Mdi0.png" alt="Empty spool weight table" title="Empty spool weight table"></a></p>
987
<p>Is it completely against the Java way to create struct like objects?</p> <pre><code>class SomeData1 { public int x; public int y; } </code></pre> <p>I can see a class with accessors and mutators being more Java like.</p> <pre><code>class SomeData2 { int getX(); void setX(int x); int getY(); void setY(int y); private int x; private int y; } </code></pre> <p>The class from the first example is notationally convenient.</p> <pre><code>// a function in a class public int f(SomeData1 d) { return (3 * d.x) / d.y; } </code></pre> <p>This is not as convenient.</p> <pre><code>// a function in a class public int f(SomeData2 d) { return (3 * d.getX()) / d.getY(); } </code></pre>
<p>Use common sense really. If you have something like:</p> <pre><code>public class ScreenCoord2D{ public int x; public int y; } </code></pre> <p>Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down.</p> <p>On the other hand, with:</p> <pre><code>public class BankAccount{ public int balance; } </code></pre> <p>You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters.</p> <p>It's always preferable to know <em>why</em> you're applying good practice, so that you know when it's ok to bend the rules.</p>
<p>You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class. There is no way to genuinely reproduce structs in Java.</p>
5,729
<p>I have a very simple html. The red div is inside the blue div and has a 10 px top margin. On non-ie browsers, the blue box is 10 px apart from the top of viewport and the red div is at the very top of the blue div. What I expect is the ie behavior: red div must be 10 px apart from the top of the blue div. Why does non-ie browsers render like this? (I suppose the wrong behavior is the IE's but why?)</p> <p>And, what is the correct way to do this?</p> <p><a href="http://img92.imageshack.us/img92/7662/blankmr7.jpg">why blank? http://img92.imageshack.us/img92/7662/blankmr7.jpg</a></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin:0; padding:0; } .outer { background-color: #00f; height: 50px; } .inner { height: 20px; width: 20px; background-color: #f00; margin: 10px 0 0 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="outer"&gt; &lt;div class="inner"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>As much as <a href="https://stackoverflow.com/questions/315738/unexpected-margin-with-very-simple-html#315759">strager's answer</a> already explains about as much as you need to know as to why it happens – namely that it happens the way it does in browsers other than IE because the specs say so – I think he picked the wrong quote from the section of <a href="http://www.w3.org/TR/CSS21/" rel="nofollow noreferrer">the CSS 2.1 specification</a> about <a href="http://www.w3.org/TR/CSS21/box.html#collapsing-margins" rel="nofollow noreferrer">collapsing margins</a>.</p> <p>The point he quoted explains how margins can collapse, not how they can "move" to a parent element.</p> <p>This is rather what explains it:</p> <blockquote> <ul> <li>If the top and bottom margins of a box are adjoining, then it is possible for margins to collapse through it. In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed. <ul> <li>If the element's margins are collapsed with its parent's top margin, the top border edge of the box is defined to be the same as the parent's.</li> </ul></li> </ul> </blockquote> <p>Or, in slightly more human-readable form in the <a href="https://developer.mozilla.org/En/CSS/Margin_collapsing" rel="nofollow noreferrer">Mozilla developer documentation</a>:</p> <blockquote> <p><strong>Parent and first/last child:</strong></p> <p>If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.</p> </blockquote> <p>As for how to fix it, I'd probably go for the <code>overflow: auto</code> solution <a href="https://stackoverflow.com/questions/315738/unexpected-margin-with-very-simple-html#315772">Chris Lloyd suggested</a> (as much as that may have side-effects).</p> <p>But then that really depends on what exactly the rest of your code looks like. In this simple example you could easily just change the <em>margin</em> on the child element to a <em>padding</em> on the parent element.</p> <p>Or you could float the child element, or absolutely position it...</p> <p>Or how about an inverse <a href="http://www.positioniseverything.net/easyclearing.html" rel="nofollow noreferrer">clearfix</a> if you want to get really fancy:</p> <pre><code>.outer:before { content: "."; display: block; height: 0; clear: both; visibility: hidden; } </code></pre>
<p>Could it be IE sees the DOM as div.inner having div.outer as it's parent node(and calculates offset from it),<br> and that other browsers instead has both of them answering to the body element?</p>
40,762
<p>We have a requirement to increase the functionality of a grid we are using to edit on our webapp, and our manager keeps citing Excel as the perfect example for a data grid :/ He still doesn't really get that a Spreadsheet like control doesn't exist out of the box, but I thought I'd do a bit of searching nonetheless.</p> <p>I've found a couple of products on Google, but was wondering if anyone else has any feedback around any such controls (obviously the cheaper or <em>ahem</em> freer the better)</p> <p><strong>EDIT</strong> We do currently have the Telerik controls, but what the 'current' requirement is, is a control that can copy and paste (e.g) 3 cells from one row and paste them on another, the row by row editing of Telerik doesn't really cut it. We are currently in competition with an 'Excel' based solution, which is always a nightmare in winning users around, who always prefer flexibility to structure</p>
<p>Update: with Silverlight fast approaching, maybe you can use a real excel control.</p> <p><a href="http://www.devexpress.com/Products/NET/Controls/ASP/Grid/" rel="nofollow noreferrer">Devexpress</a> has a powerful grid control for both web and windows. It is not free and I guess nothing really matches Excel. But once the users started using it, they wanted every app with it. Check these <a href="http://www.devexpress.com/Products/NET/Controls/ASP/Grid/quickstart.xml" rel="nofollow noreferrer">videos</a> especially the data grouping one.</p>
<p>This may not be directly related to your question, but on the server side have you considered what operations you will need to perform that will mimic Excel? You may want to check out <a href="http://www.spreadsheetgear.com/" rel="nofollow noreferrer">SpreadsheetGear</a> which will give you complete macro functionality. </p> <p>They have new charting features that I haven't used yet, but they are supposed to work with Asp.net.</p>
8,265
<p>This is a puzzle for me, I am able to get three DropDownLists to behave like a cascade (it fetches the correct data) but where I run into problem is where I try to set the value for the dropdownlist based on the value of the querystring. </p> <p>Only the first dropdownlist seems to take it's value from the querystring. The other two does not. In fact the 3rd DropDownlist will also exhibit the error below (it almost looks like the control isn't bound yet:</p> <pre><code>'ddlStation' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value </code></pre> <p>FYI, here is the portion that sets the DropDownList in the Page_Load event:</p> <pre><code>// see if there is any querystring and set dropdownlist accordingly if (Request.QueryString["cell"] != null) { ddlCell.SelectedValue = Request.QueryString["cell"].ToString(); if (Request.QueryString["subcell"] != null) { ddlSubCell.SelectedValue = Request.QueryString["subcell"].ToString(); if (Request.QueryString["station"] != null) { ddlStation.SelectedValue = Request.QueryString["station"].ToString(); } } } </code></pre> <p>Any help is appreciated!</p>
<p>You can only set the SelectItem/Value/Text after databinding has happened.</p>
<p>You're right that the databind must happen first.. </p> <p>What I kind of figured out is that the setting of the dropdownlist should be in the Databound event of each dropdownlist (rather than in the Page_Load event in the original). </p> <p>It works now :)</p>
42,783
<p>What good ruby gem sources would you recommend, besides <a href="http://gems.rubyforge.org/" rel="noreferrer">http://gems.rubyforge.org/</a> and <a href="http://gems.github.com/" rel="noreferrer">http://gems.github.com/</a>? It seems that RubyForge is missing most of the gems I look for these days...</p>
<p>This is now the official RubyGems source:</p> <pre><code>https://rubygems.org/ </code></pre>
<p>It would be good to add a RubyForge mirror - however I cannot find one that is up and RubyForge now (10-june-09) is down...</p>
33,708
<p>How do I draw procedural graphics in a Vista Sidebar gadget? </p> <p>I have a gadget that collects data over time and I want to draw animating graphs. My current approach is to draw the graph with VML that I update from JScript on a timer tick. Is this the best way? Can I return bitmap bits from a DLL function as the srouce to an <code>&lt;IMG&gt;</code>? Embed bitmap bits into the HTML itself (and again update it via JScript)? I'd love to hear some ideas.</p> <p>Thanks!</p>
<p>You can use Silverlight 2 with Sidebar gadgets now - the Silverlight toolkit available on Codeplex (<a href="http://www.codeplex.com/Silverlight" rel="nofollow noreferrer">http://www.codeplex.com/Silverlight</a>) includes charting controls (which support animation), so that should be relatively straightforward.</p>
<p>The way I currently do it is with Javascript and Adobe Flash Player communicating via the ExternalInterface in ActionScript. It seamlessly integrates local Javascript instances with an instance of a Flash Player and you can communicate just about anything between the two. You can use the fantastic drawing API in ActionScript and really get some power into you hands for charting or just embed some tools off the net.</p> <p>But then, if the sandbox permits it, generating data by targeting DLLs would be great! I don't have anything functional at hand to test it, so I leave it to other contributors.</p>
40,245
<p>I've implemented my own event handler and added it to the selection model of the table:</p> <pre><code>table.getSelectionModel().addListSelectionListener(event); </code></pre> <p>And implemented the method for "event" (mentioned above):</p> <pre><code>public void valueChanged(ListSelectionEvent e) { log.debug("value changed"); } </code></pre> <p>Unfortunately the event fires twice if I chance the selection and it doesn't seem possible to find the associated table, because e.getSource provides javax.swing.DefaultListSelectionModel.</p> <p>Hence my questions are:</p> <p>1) Why does it fire twice although the eventListener is only registered once?</p> <p>2) How can I find the table for which the selection applies? The DefaultListSelectionModel doesn't seem to offer any getSource() or similar.</p> <p>Many thanks!</p>
<p>1) I think you'll find it fires once for de-selecting the old selection and once for selecting the new selection. If you log the details of the event you should see exactly what's going on. I can't remember the details, so perhaps this is wrong. Either way you should be able to call getValueIsAdjusting() on the event and only use the last one in the chain (ie when it returns false).</p> <p>2) You shouldn't normally need to, but AFAIK the only way to do this is to create your Listener specifically for the table (ie pass the table to the constructor and remember it).</p>
<p>Since more than one JTable (or other component I'm guessing) can share the same selection model, it doesn't make sense to ask for the associated JTable from the event. This is the same reason that you can't retrieve a JTable from a TableModel. As Draemon suggests, store the reference to the JTable in (or make it accessible to) your listener class.</p>
49,103
<p>It seems that everybody knows you're supposed to have a clear distinction between the GUI, the business logic, and the data access. I recently talked to a programmer who bragged about always having a clean data access layer. I looked at this code, and it turns out his data access layer is just a small class wrapping a few SQL methods (like ExecuteNonQuery and ExecuteReader). It turns out that in his ASP.NET code behind pages, he has tons of SQL hard coded into the page_load and other events. But he swears he's using a data access layer.</p> <p>So, I throw the question out. How would you define a data access layer?</p>
<p>What your colleague is talking about is not a DAL by most peoples reckoning. The DAL should encapsulate any calls to the database whether done by dynamic SQL, stored procs or an ORM with something like IRepository. Your web pages never should contain SQL or business logic or else it becomes maintenance nightmare.</p>
<p>A "Black box" that holds your data. If it's user cares/can tell that there is a DB back there (aside from per consideration), it's not quite what I'm thinking of</p>
35,796
<p>I have found no way of dumping the stack on all threads in .NET. Neither a signal to be send to the process nor programatic access to all the threads. I can only get access to the current thread via Thread.CurrentThread.</p> <p>Any tricks ?</p>
<p>If you're trying to get a stack dump while the process is already running (a la jstack), there are two methods as described <a href="http://www.tomergabel.com/NETProductionDebugging101.aspx" rel="noreferrer">here</a>:</p> <h3>Using Managed Stack Explorer</h3> <p>There is a little-known but effective tool called the <a href="http://www.tomergabel.com/ct.ashx?id=1db72c20-3c25-42ad-93c4-b0551a0fed4e&amp;url=http%3a%2f%2fwww.microsoft.com%2fdownloads%2fdetails.aspx%3fFamilyID%3d80CF81F7-D710-47E3-8B95-5A6555A230C2%26displaylang%3den" rel="noreferrer">Managed Stack Explorer</a>. Although it features a basic GUI, it can effectively be a .NET equivalent of jstack if you add to the path; then it’s just a question of typing:<pre>mse /s /p <i>&lt;pid&gt;</i></pre></p> <h3>Using windbg</h3> <ol> <li>Download and install the appropriate Debugging Tools for Windows version for your architecture (x86/x64/Itanium)</li> <li>If you need information about Windows function calls (e.g. you want to trace into kernel calls), download and install the appropriate symbols. This isn't strictly necessary if you just want a thread dump of your own code.</li> <li>If you need line numbers or any other detailed information, make sure to place your assemblies' PDB files where the debugger can find them (normally you just put them next to your actual assemblies).</li> <li>Start->Programs->Debugging Tools for Windows [x64]->windbg</li> <li>Attach the debugger to your running process using the menu</li> <li>Load the SOS extension with ".loadby sos mscorwks" for .NET 2.0 (".load sos" for .NET 1.0/1.1)</li> <li>Take a thread dump using "!eestack"</li> <li>Detach using ".detach"</li> </ol> <p>I just found it necessary to take a production thread dump and this worked for me. Hope it helps :-)</p>
<p>There is a variety of handy classes in the System.Diagnostics that can help you with debugging and gathering various tracking information, i.e. StackTrace.</p> <p>There is a wonky Process class that can be used to get the number of executing threads but very few details. Use the following Snippet:</p> <pre><code>Using System.Diagnostics; var threads = Process.GetCurrentProcess().Threads; </code></pre> <p>Okay after looking a little bit more it appears the easiest way to capture all the current stacks is through a mini dump and a tool like <a href="http://msdn.microsoft.com/en-us/magazine/cc163833.aspx" rel="nofollow noreferrer">SOS</a> or if you are running vista <a href="http://www.nynaeve.net/?p=156." rel="nofollow noreferrer">this</a>.</p> <p>Good luck.</p>
23,084
<p>I'm having some problems with the ranking used by fulltext search in SQL Server.</p> <p>Suppose a user searches for two words, "foo bar". We assume the user intends to do an OR search, so we pass "foo OR bar" to our CONTAINSTABLE call. What we're finding is that an row that contains "foo" 10 times but does not contain "bar" will have a much higher rank then an row that that has both "foo" and "bar". We would want the row that has both terms to be preferred over a row that only has one term multiple times. Any advice on how to achieve this?</p> <p>I have found documentation related to a RANKMETHOD modifier, but that seems to be for SQL Enterprise search only, and not available on regular SQL Server 2005 installs. We could also switch to Lucene.Net, but I would hope to verify it has the better ranking available. We might also do multiple searches and merge the results, but that seems undesireable as the number of words searched for increases.</p>
<p>Just to followup on this.. The reason the ranking was low for rows containing strings A and B when matching against string "A or B" is that A was in a different column than B. If I create a view on the table that merges those columns into a single column, the ranking for "A or B" is more what I expected.</p>
<p>I did a short discussion on Inverted Indexes and Cosine Ranking (the core algorithms and data structures of full-text retrieval systems) <a href="https://stackoverflow.com/questions/237970/full-text-search-relevance-is-measured-in#238072">Here.</a></p> <p>On a pure cosine ranking, foo (1), bar (1) should be closer to the vector occupied by foo, bar than foo (10), bar (0). One can fiddle the cosine value post-hoc, which is essentially what <a href="http://en.wikipedia.org/wiki/Pagerank" rel="nofollow noreferrer">Pagerank</a> does. If the full-text search is fiddling the cosine ranking after calculating the dot product rather than weighting the axes, this would explain the disproportionate significance of foo.</p>
30,366
<p>I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like:</p> <pre><code>[#if_exists userName] Hi ${userName}, How are you? [/#if_exists] </code></pre> <p>However, the FreeMarker manual seems to indicate that if_exists is deprecated, but I can't find another way to achieve this. Of course, I could simple providing an additional boolean variable isUserName and use that like this:</p> <pre><code>[#if isUserName] Hi ${userName}, How are you? [/#if] </code></pre> <p>But if there's a way of checking whether userName exists then I can avoid adding this extra variable.</p>
<p>To check if the value exists:</p> <pre><code>[#if userName??] Hi ${userName}, How are you? [/#if] </code></pre> <p>Or with the standard freemarker syntax:</p> <pre><code>&lt;#if userName??&gt; Hi ${userName}, How are you? &lt;/#if&gt; </code></pre> <p>To check if the value exists and is not empty:</p> <pre><code>&lt;#if userName?has_content&gt; Hi ${userName}, How are you? &lt;/#if&gt; </code></pre>
<blockquote> <p>For versions previous to FreeMarker 2.3.7</p> </blockquote> <p>You can not use <code>??</code> to handle missing values, the old syntax is:</p> <pre><code>&lt;#if userName?exists&gt; Hi ${userName}, How are you? &lt;/#if&gt; </code></pre>
39,460
<p>Is there a window manager for <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2008</a> like <a href="http://www.codeplex.com/VSWindowManager" rel="nofollow noreferrer">this one</a>. I really liked it, and that's all I used in <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2005</a> and saw somewhere it is supposed to work in Visual&nbsp;Studio&nbsp;2008, but it doesn't. I have tried it on many installations of Visual&nbsp;Studio&nbsp;2008, and it doesn't remember any settings. I really liked being able to easily change window layout quickly. Right now I just manually import and export settings, but it's not an instant process.</p> <p>What do I have to do to make it work?</p>
<p>You can check out my blog post, <em><a href="http://www.brianschmitt.com/save-and-change-tool-layout-in-visual/" rel="nofollow noreferrer">Save and Change Tool Layout in Visual Studio</a></em>, which provides the ability to list and switch window layouts.</p>
<p>You should contact RW on <a href="http://en.wikipedia.org/wiki/CodePlex" rel="nofollow noreferrer">CodePlex</a>. He claims to have it working in Visual&nbsp;Studio&nbsp;2008. Check out <a href="http://www.codeplex.com/VSWindowManager/WorkItem/View.aspx?WorkItemId=14859" rel="nofollow noreferrer">this item</a>.</p>
14,983
<p>There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as well.</p> <ol> <li>Where do I set the value for the valuebinding? Is this supposed to happen in decode? Or should decode do something else and then have the value set in encodeBegin?</li> <li>Read from the Value Binding - When do I read data from the valuebinding vs. reading it from submittedvalue and putting it into the valuebinding? </li> <li>When are action listeners on forms called in relation to all of this? The JSF lifecycle pages all mention events happening at various steps, but its not completely clear to me when just a simple listener for a commandbutton is being called</li> </ol> <p>I've tried a few combinations, but always end up with hard to find bugs that I believe are coming from basic misunderstandings of the event lifecycle.</p>
<p>There is a pretty good diagram in the <a href="http://java.sun.com/javaee/javaserverfaces/download.html" rel="noreferrer">JSF specification</a> that shows the request lifecycle - essential for understanding this stuff.</p> <p>The steps are:</p> <ul> <li><strong>Restore View</strong>. The UIComponent tree is rebuilt.</li> <li><strong>Apply Request Values</strong>. Editable components should implement EditableValueHolder. This phase walks the component tree and calls the <em>processDecodes</em> methods. If the component isn't something complex like a UIData, it won't do much except call its own <em>decode</em> method. The <em>decode</em> method doesn't do much except find its renderer and invokes its <em>decode</em> method, passing itself as an argument. It is the renderer's job to get any submitted value and set it via <em>setSubmittedValue</em>.</li> <li><strong>Process Validations</strong>. This phase calls <em>processValidators</em> which will call <em>validate</em>. The <em>validate</em> method takes the submitted value, converts it with any converters, validates it with any validators and (assuming the data passes those tests) calls <em>setValue</em>. This will store the value as a local variable. While this local variable is not null, it will be returned and not the value from the value binding for any calls to <em>getValue</em>.</li> <li><strong>Update Model Values</strong>. This phase calls <em>processUpdates</em>. In an input component, this will call <em>updateModel</em> which will get the <em>ValueExpression</em> and invoke it to set the value on the model.</li> <li><strong>Invoke Application</strong>. Button event listeners and so on will be invoked here (as will navigation if memory serves).</li> <li><strong>Render Response</strong>. The tree is rendered via the renderers and the state saved.</li> <li>If any of these phases fail (e.g. a value is invalid), the lifecycle skips to Render Response.</li> <li>Various events can be fired after most of these phases, invoking listeners as appropriate (like value change listeners after Process Validations).</li> </ul> <p>This is a somewhat simplified version of events. Refer to the specification for more details.</p> <p>I would question why you are writing your own UIComponent. This is a non-trivial task and a deep understanding of the JSF architecture is required to get it right. If you need a custom control, it is better to create a concrete control that extends an exisiting UIComponent (like HtmlInputText does) with an equivalent renderer.</p> <p>If contamination isn't an issue, there is an open-source JSF implementation in the form of Apache MyFaces.</p>
<p>The best article I've found is <a href="http://blogs.steeplesoft.com/jsf-component-writing-check-list/" rel="nofollow noreferrer">Jsf Component Writing</a>, as for 2 where do I read the value for a value binding in your component you have a getter that looks like this</p> <pre><code> public String getBar() { if (null != this.bar) { return this.bar ; } ValueBinding _vb = getValueBinding("bar"); return (_vb != null) ? (bar) _vb.getValue(getFacesContext()) : null; } </code> </pre> <p>how did this get into the getValueBinding? In your tag class setProperties method</p> <pre><code> if (bar!= null) { if (isValueReference(bar)) { ValueBinding vb = Util.getValueBinding(bar); foo.setValueBinding("bar", vb); } else { throw new IllegalStateException("The value for 'bar' must be a ValueBinding."); } } </code></pre>
5,355
<p>I'm working for the first time with Forms Authentication, I'm using an example from the web to learn, I included in my web.config</p> <pre><code> &lt;authentication mode="Forms"&gt; &lt;forms name="MYWEBAPP.ASPXAUTH" loginUrl="Login.aspx" protection="All" path="/"/&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; </code></pre> <p>Then I created a page for logging in "login.aspx", and coded this on a button, just to start;</p> <pre><code>private void btnLogin_Click(Object sender, EventArgs e) { // Initialize FormsAuthentication FormsAuthentication.Initialize(); // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version Username.Value, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire true, // "true" for a persistent user cookie "accountants, seekers, copiers, typers", // User-data, in this case the roles FormsAuthentication.FormsCookiePath);// Path cookie valid for // Encrypt the cookie using the machine key for secure transport string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; // Add the cookie to the list for outgoing response Response.Cookies.Add(cookie); } </code></pre> <p>Also I coded in Global.asax;</p> <pre><code>protected void Application_AuthenticateRequest(object sender, EventArgs e) { if(HttpContext.Current.User != null) { if(HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; // Get the stored user-data, in this case, our roles string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new GenericPrincipal(id, roles); } } } } </code></pre> <p>And finally in another page I tried to confirm the roles aquired;</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string str = null; if (User.IsInRole("seekers")) { str += " seekers "; } if (User.IsInRole("accountants")) { str += " accountants "; } if (User.IsInRole("copiers")) { str += "copiers"; } Response.Write(str); } </code></pre> <p>But something strange happens cause it only writes "accountants" (note that "accountants" is the firts element in the delimited comma string) and not the other roles, which were supposed to be showed. I changed the order of the role list in the btnlogin click event writing "copiers" as the first element and it's written only "copiers" in the page. </p> <p>I've tried with different combinations and always is printed the first element of the delimited comma string.</p> <p>Sorry by my ignorance but what is happening here, are all the roles there or not? is normal? or there's something I'm forgetting here?</p> <p>Thanks in advance.</p>
<p>Drop the spaces in</p> <pre><code>"accountants, seekers, copiers, typers" </code></pre>
<p>You're splitting on ',' ... but when you initialize your string of roles it's actually ", " (comma space). </p> <p>A tip on this is to use debugger and use the immediate window to actually "see" what's happening as it happens.</p>
37,919
<p>I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.</p> <p>I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.</p> <p>What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.</p>
<p>I believe you need to add the following to the Makefile:</p> <pre><code>CFLAGS += -I/opt/gnu/include LDFLAGS += -L/opt/gnu/lib -R/opt/gnu/lib </code></pre> <p>The -I argument tell gcc where to find the include files. The -L flag tells ld where to find the libraries while linking. The -R flag writes /opt/gnu/lib into the library search path in the quadrupel binary, so it can find its libraries when it starts.</p>
<p>You can override the path by setting the environmental variable LD_LIBRARY_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel. </p> <pre><code>crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib </code></pre> <p>For the includes just add -I/opt/gnu/include to your CFLAGS variable. </p>
7,020
<p>I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.</p> <p>How do I do that, but then be able to turn it off for the release version?</p>
<p>All calls to <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.print.aspx" rel="noreferrer"><code>System.Diagnostics.Debug.Print()</code></a> will be removed when you switch to a release version.</p>
<p>I use: <a href="http://msdn.microsoft.com/en-us/library/system.console.writeline.aspx" rel="nofollow noreferrer" title="System.Console.WriteLine()">System.Console.WriteLine()</a></p> <pre><code>#if DEBUG System.Console.WriteLine("Message"); #endif </code></pre>
27,535
<p>We are migrating from one domain to another, and I'd like to be able to keep my same workspace, user settings, history, etc.</p> <p>Is there any way to change just my domain or log in name within Team Foundation Server?</p>
<p>I don't know the answer, but I do know enough about TFS to be a little bit frightened about it. </p> <p>If I understand you correctly, you want to change the domain that your users are authenticating as but you want to keep all the same user id's pointing to the same accounts in TFS?</p> <p>TFS is highly integrated with Active Directory, and stores AD SID's around the place. It also is pretty sensitive to changes in the AD configuration.</p> <p>I seem to remember one customer that I know of who has done this before, but I cannot find details of it now. I think that your best bet is to call Microsoft Product Support and raise a support incident about it as I have a vague memory that there was some special tool that had to be ran - but I could be mistaken.</p> <p>Good luck,</p> <p>Martin.</p>
<p>I know your login name is done through your Domain Controller but I dont know how that will work with switching which domain your TFS is on. Are you trying to move which domain the TFS installation is on or which domain your PC is on?</p>
47,054
<p>Here is classical object model:</p> <pre><code> class ViewBase { void DoSomethingForView() { } //May be virtual } class View1 : ViewBase //(derived class from ViewBase) { void DoSomethingForView() { } void DoSomethingForView1Special() { } } class View2: ViewBase //(another derived class from ViewBase) { void DoSomethingForView2Special() { } } class Application { void Print() { } void DoSomething() { } //Do some magic to create a view object (View1 or View2) and return //Something which I don't know to describe. Its like dynamically //returning object of View1 or View2 at runtime } </code></pre> <p>I want to convert this to Perl Moose class model. </p> <p>So that,</p> <p>I will call the view methods like</p> <pre><code>void Main() { App = new Application(); App-&gt;View1-&gt;DoSomethingForView(); App-&gt;View1-&gt;DoSomethingForView1Special(); App-&gt;View2-&gt;DoSomethingForView(); App-&gt;View2-&gt;DoSomethingForView2Special(); </code></pre> <p>}</p> <p>I will not know which View to be called. But at runtime, View1/View2 instance must be created &amp; DoSomethingForView() must be called.</p> <p>The above code is not exactly Perl. How to translate &amp; achieve this in Perl.</p> <p>An Application object shall have View object, but we will not know the type of the view at compile time. We have a test application, development in Perl. </p> <p>You can imagine Application is a GUI application, and View is what you are seeing in the application window. User can select any view. </p> <p>I am sorry about my English. Please let me know If I need to provide more text.</p>
<p>So this gives you roughly equivalent syntax in Perl. It doesn't help you out with some of your conflicting criteria, though. </p> <p>Note the following:</p> <ul> <li>class ABC {...} is replaced by the perl syntax package ABC;</li> <li> The capital camel-case method names are turned into proper "snake-case" perl.</li> <li>App has been turned to sigil-ed $App</li> </ul> <p>This has been tested against Moose v62, Perl 5.10. Second from the last line will fail, because <code>do_something_for_view</code> is not implemented by <code>View2</code> class. As you're calling <code>view1</code> or <code>view2</code> specifically, I don't see the application for what you seem to indicate is polymorphism.</p> <pre><code>package ViewBase; sub do_something_for_view { Carp::croak "ViewBase::do_something_for_view is ABSTRACT!"; } package View1; use Moose; extends 'ViewBase'; sub do_something_for_view { print "Doing something for View1.\n"; } sub do_something_for_view1_special { print "Doing something SPECIAL for View1.\n"; } package View2; use Moose; extends 'ViewBase'; sub do_something_for_view2_special() { print "Doing something SPECIAL for View2.\n"; } package Application; use Moose; has view1 =&gt; ( is =&gt; 'rw' # read/write , isa =&gt; 'View1' , lazy =&gt; 1 , default =&gt; sub { View1-&gt;new(); } ); has view2 =&gt; ( is =&gt; 'rw' # read/write , isa =&gt; 'View2' , lazy =&gt; 1 , default =&gt; sub { View2-&gt;new(); } ); sub print {} sub do_something {} #void Main() #{ package main; #App = new Application(); my $App = Application-&gt;new(); #App-&gt;View1-&gt;DoSomethingForView(); $App-&gt;view1-&gt;do_something_for_view(); #App-&gt;View1-&gt;DoSomethingForView1Special(); $App-&gt;view1-&gt;do_something_for_view1_special(); #App-&gt;View2-&gt;DoSomethingForView(); $App-&gt;view2-&gt;do_something_for_view(); #App-&gt;View2-&gt;DoSomethingForView2Special(); $App-&gt;view2-&gt;do_something_for_view2_special(); #} </code></pre>
<p>If you use <a href="http://search.cpan.org/perldoc?MooseX::Declare" rel="nofollow noreferrer">MooseX::Declare</a> you might be able to simplify the syntax to something quite like what you first wrote, for instance, your declarations would turn into:</p> <pre><code>use MooseX::Declare; class ViewBase { method DoSomethingForView() { } #May be virtual } class View1 extends ViewBase { method DoSomethingForView() { } method DoSomethingForView1Special() { } } class View2 extends ViewBase { method DoSomethingForView2Special() { } } class Application { method Print() { } method DoSomething() { } #Do some magic to create a view object (View1 or View2) and return #Something which I don't know to describe. Its like dynamically #returning object of View1 or View2 at runtime } </code></pre>
49,035
<p>Which way do you prefer to create your forms in MVC?</p> <pre><code>&lt;% Html.Form() { %&gt; &lt;% } %&gt; </code></pre> <p>Or</p> <pre><code>&lt;form action="&lt;%= Url.Action("ManageImage", "UserAccount") %&gt;" method="post"&gt; &lt;/form&gt; </code></pre> <p>I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. </p> <p>What is your take?</p>
<p>The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.</p>
<p>The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code. </p> <p>For example, I <a href="http://andrewpeters.net/2008/08/21/nhaml-block-methods-and-restful-helpers/" rel="nofollow noreferrer">blogged</a> about some RESTful NHaml helpers that can build urls based on a model.</p>
6,372
<p>I have played around with smart phone development (windows ce), and it seemed pretty straight forward using vs.net and having a nice emulator etc.</p> <p>How is blackberry development? Seeing as it uses JavaME I am guessing learning the SDK/syntax for a .net developer wouldn't be that hard to get going with.</p> <p>But what about the development IDE, debugging, emulators etc.?</p>
<p>I have very limited experience with the Blackberry, but from what I do have, it is fairly user friendly. Java is fairly similar to C# which you would have probably used for CE development.</p> <p>You will probably use Eclipse for the IDE which is good once you get used to it. It will probably frustrate you a bit coming from Visual Studio, but give it a chance.</p> <p>As for debugging and emulators, from my limited experience, no problems there. Actually, I find the Blackberry a much nicer platform than any of the CE devices in many ways.</p> <p>There is a Visual Studio plugin for Blackberry development too, but it requires that a runtime be installed on the Blackberries that use the programs developed, so it is only really useful for Enterprise apps where you have control over the users' phones.</p>
<p>I actually just purchased a blackberry for this very reason. You can use the Eclipse IDE and then install the JDE plugin. The JDE plugin includes the blackberry sdk as well as some emulators.</p> <p>EDIT - <a href="http://na.blackberry.com/eng/developers/javaappdev/" rel="nofollow noreferrer">http://na.blackberry.com/eng/developers/javaappdev/</a></p> <p>I encountered a snag a couple weeks ago when I was setting up the environment, however, I found my solution in the blackberry forums. YMMV</p>
48,113
<p>i have a big web application running in perl CGI. It's running ok, it's well written, but as it was done in the past, all the html are defined hardcoded in the CGI calls, so as you could imagine, it's hard to mantain, improve and etc. So now i would like to start to add some templating and integrate with a framework (catalyst or CGI::application). My question is: Somebody here has an experience like that? There is any things that i must pay attention for? I'm aware that with both frameworks i can run native CGI scripts, so it's good because i can run both (CGI native ad "frameworked" code) together without any trauma. Any tips?</p>
<p>Write tests first (for example with <a href="http://search.cpan.org/perldoc?Test::WWW::Mechanize" rel="nofollow noreferrer"><code>Test::WWW::Mechanize</code></a>). Then when you change things you always know if something breaks, and what it is that breaks.</p> <p>Then extract HTML into templates, and commonly used subs into modules. After that it's a piece of cake to switch to a framework.</p> <p>In general, go step by step so that you always have a working application.</p>
<p>Extricate the HTML from the processing logic in the CGI script. Identify all code that affects the HTML output, as these are candidates for becoming template variables. Separate that into a HTML file, with the identified parts marked with template variables. Eventually you will be able to refactor the page such that all processing is done at the start of the code and the HTML template just called up at the end of all processing.</p>
17,833
<p>What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!</p>
<p>There are a couple of things to do in order to keep your session secure:</p> <ol> <li>Use SSL when authenticating users or performing sensitive operations.</li> <li>Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish.</li> <li>Have sessions time out</li> <li>Don't use register globals</li> <li>Store authentication details on the server. That is, don't send details such as username in the cookie.</li> <li>Check the <code>$_SERVER['HTTP_USER_AGENT']</code>. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here).</li> <li>Lock down access to the sessions on the file system or use custom session handling</li> <li>For sensitive operations consider requiring logged in users to provide their authenication details again</li> </ol>
<p>This is pretty trivial and obvious, but be sure to <a href="http://www.php.net/session_destroy" rel="nofollow noreferrer">session_destroy</a> after every use. This can be difficult to implement if the user does not log out explicitly, so a timer can be set to do this.</p> <p>Here is a good <a href="http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/" rel="nofollow noreferrer">tutorial</a> on setTimer() and clearTimer().</p>
2,281
<p>For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are! </p> <p>Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.</p> <p>Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare &amp; modify it, then put it back into the string.</p> <pre><code>&lt;VAR NAME="sf_name" ID="1001210"&gt; </code></pre> <p>I am looking for the simplest (in terms of coding time) and safest way to do this.</p>
<p>The regex pattern you are looking for is:</p> <pre><code>ID="(\d+)" </code></pre> <p>Match group 1 would contain the number. Use a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx" rel="nofollow noreferrer">MatchEvaluator Delegate</a> to replace matches with dynamically calculated replacements.</p> <pre><code>Regex r = new Regex("ID=\"(\\d+)\""); string outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction)); </code></pre> <p>where <code>ReplaceFunction</code> is something like this:</p> <pre><code>public string ReplaceFunction(Match m) { // do stuff with m.Groups(1); return result.ToString(); } </code></pre> <p>If you need I can expand the Regex to match more specifically. Currently <em>all</em> ID values (that contain numbers only) are replaced. You can also build that bit of "extra intelligence" into the match evaluator function and make it return the match unchanged if you don't want to change it.</p>
<p>Take a look at this property <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx" rel="nofollow noreferrer">PreserveWhitespace</a> in <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx" rel="nofollow noreferrer">XmlDocument</a> class</p>
32,293
<p>I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this:</p> <pre><code>List allClasses = new ArrayList(); allClasses.add(String.class); </code></pre> <p>How can I do this dynamically to add all classes in a package and all its subpackages?</p> <hr> <p><strong><em>Update:</em></strong> Having read the early answers, it's absolutely true that I'm trying to solve another secondary problem, so let me state it. And I know this is possible since other tools do it. See new question <a href="https://stackoverflow.com/questions/176913/how-can-i-run-all-unit-tests-except-those-ending-in-integrationtest-in-my-intel">here</a>. </p> <p><strong><em>Update:</em></strong> Reading this again, I can see how it's being misread. I'm looking to enumerate all of MY PROJECT'S classes from the file system after compilation. </p>
<p>****UPDATE 1 (2012)****</p> <p>OK, I've finally gotten around to cleaning up the code snippet below. I stuck it into it's own github project and even added tests.</p> <p><a href="https://github.com/ddopson/java-class-enumerator" rel="nofollow noreferrer">https://github.com/ddopson/java-class-enumerator</a></p> <p>****UPDATE 2 (2016)****</p> <p>For an even more robust and feature-rich classpath scanner, see <a href="https://github.com/classgraph/classgraph" rel="nofollow noreferrer">https://github.com/classgraph/classgraph</a> . I'd recommend first reading my code snippet to gain a high level understanding, then using lukehutch's tool for production purposes.</p> <p>****Original Post (2010)****</p> <p>Strictly speaking, it isn't possible to list the classes in a <em>package</em>. This is because a package is really nothing more than a namespace (eg com.epicapplications.foo.bar), and any jar-file in the classpath could potentially add classes into a package. Even worse, the classloader will load classes on demand, and part of the classpath might be on the other side of a network connection.</p> <p>It is possible to solve a more restrictive problem. eg, all classes in a JAR file, or all classes that a JAR file defines within a particular package. This is the more common scenario anyways.</p> <p>Unfortunately, there isn't any framework code to make this task easy. You have to scan the filesystem in a manner similar to how the ClassLoader would look for class definitions.</p> <p>There are a lot of samples on the web for class files in plain-old-directories. Most of us these days work with JAR files.</p> <p>To get things working with JAR files, try this...</p> <pre><code>private static ArrayList&lt;Class&lt;?&gt;&gt; getClassesForPackage(Package pkg) { String pkgname = pkg.getName(); ArrayList&lt;Class&lt;?&gt;&gt; classes = new ArrayList&lt;Class&lt;?&gt;&gt;(); // Get a File object for the package File directory = null; String fullPath; String relPath = pkgname.replace('.', '/'); System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath); URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); System.out.println("ClassDiscovery: Resource = " + resource); if (resource == null) { throw new RuntimeException("No resource for " + relPath); } fullPath = resource.getFile(); System.out.println("ClassDiscovery: FullPath = " + resource); try { directory = new File(resource.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); } catch (IllegalArgumentException e) { directory = null; } System.out.println("ClassDiscovery: Directory = " + directory); if (directory != null &amp;&amp; directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i &lt; files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } else { try { String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); JarFile jarFile = new JarFile(jarPath); Enumeration&lt;JarEntry&gt; entries = jarFile.entries(); while(entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); if(entryName.startsWith(relPath) &amp;&amp; entryName.length() &gt; (relPath.length() + "/".length())) { System.out.println("ClassDiscovery: JarEntry: " + entryName); String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } catch (IOException e) { throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); } } return classes; } </code></pre>
<p>Look at what java.net.URLClassLoader is doing. It never enumerates classes, it just tries to find classes when asked for one. If you want to enumerate the classes, then you will need to get the classpath, split it into directories and jar files. Scan the directories (and their subdirectories) and jar files for files with the name *.class. <P>It may be worth looking at open source projects which seem to do the enumeration you want (like <a href="http://www.eclipse.org/" rel="nofollow noreferrer">Eclipse</a>) for inspiration.</p>
21,266
<p>My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better.</p> <p>I know SVN is newer, but other than that, I'm unfamiliar with its benefits.</p> <p>What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment.</p>
<p>CVS only tracks modification on a file-by-file basis, while SVN tracks a whole commit as a new revision, which means that it is easier to follow the history of your project. Add the fact that all modern source control software use the concept of revision so it is far easier to migrate from SVN than it is from CVS.</p> <p>There is also the atomic commit problem. While I only encountered it once, it is possible that 2 people committing together in CVS can conflict each other, losing some data and putting your client in an inconsistent state. When detected early, these problems are not major because your data is still out there somewhere, but it can be a pain in a stressful environment.</p> <p>And finally, not many tools are developed around CVS anymore. While the new and shiny-new tools like Git or Mercurial definitely lack tools yet, SVN has a pretty large application base on any system.</p> <p><strong>EDIT 2020</strong>: Seriously, this answer is 12 years old now. Forget SVN, go use Git like everyone else!</p>
<p>you might also choose to migrate only the latest code from CVS into SVN and freeze your current CVS repo. this will make migration easier and you might also build your legacy releases in the old CVS repo.</p>
2,365
<p>One concept I've always wondered about is the use of cryptographic hash functions and values. I understand that these functions can generate a hash value that is unique and virtually impossible to reverse, but here's what I've always wondered:</p> <p>If on my server, in PHP I produce:</p> <pre><code>md5("stackoverflow.com") = "d0cc85b26f2ceb8714b978e07def4f6e" </code></pre> <p>When you run that same string through an MD5 function, you get the same result on your PHP installation. A process is being used to produce some value, from some starting value.</p> <p>Doesn't this mean that there is some way to deconstruct what is happening and reverse the hash value? </p> <p>What is it about these functions that makes the resulting strings impossible to retrace?</p>
<p>The input material can be an infinite length, where the output is always 128 bits long. This means that an infinite number of input strings will generate the same output.</p> <p>If you pick a random number and divide it by 2 but only write down the remainder, you'll get either a 0 or 1 -- even or odd, respectively. Is it possible to take that 0 or 1 and get the original number?</p>
<p>I like all the various arguments. It is obvious the real value of hashed values is simply to provide human-unreadable placeholders for strings such as passwords. It has no specific enhanced security benefit. Assuming an attacker gained access to a table with hashed passwords, he/she can:</p> <ul> <li>Hash a password of his/her own choice and place the results inside the password table if he/she has writing/edit rights to the table.</li> <li>Generate hashed values of common passwords and test the existence of similar hashed values in the password table.</li> </ul> <p>In this case weak passwords cannot be protected by the mere fact that they are hashed.</p>
42,779
<p>What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the <code>Exception</code> object's <code>InnerException</code> and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?</p> <pre><code>try { //some code } catch (Exception ex) { throw ex; } </code></pre> <p>Vs:</p> <pre><code>try { //some code } catch { throw; } </code></pre>
<p>The way to preserve the stack trace is through the use of the <code>throw;</code> This is valid as well</p> <pre><code>try { // something that bombs here } catch (Exception ex) { throw; } </code></pre> <p><code>throw ex;</code> is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the <code>throw ex;</code> statement.</p> <p><a href="https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649">Mike</a> is also correct, assuming the exception allows you to pass an exception (which is recommended).</p> <p><a href="http://openmymind.net" rel="noreferrer">Karl Seguin</a> has a <a href="http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx" rel="noreferrer">great write up on exception handling</a> in his <a href="http://openmymind.net/FoundationsOfProgramming.pdf" rel="noreferrer">foundations of programming e-book</a> as well, which is a great read.</p> <p>Edit: Working link to <a href="http://openmymind.net/FoundationsOfProgramming.pdf" rel="noreferrer">Foundations of Programming</a> pdf. Just search the text for "exception".</p>
<p>FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:</p> <pre><code> private void foo() { try { bar(3); bar(2); bar(1); bar(0); } catch(DivideByZeroException) { //log message and rethrow... throw; } } private void bar(int b) { int a = 1; int c = a/b; // Generate divide by zero exception. } </code></pre> <p>The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.</p>
4,267
<p>Is virtual PC practical on a home personal development computer. I do some custom .net programming at home and I was wondering if in terms of performance and overall use, Virtual PC is useful. Do the applications inside Virtual PC session run slower. It will help me with my personal dev machine. Would you recommend any other products?</p>
<p>It really depends on what your home computer is like. I've used VPC to test different versions of Visual Studio (e.g. to make sure that a solution is VS2005 compatible, and to check out VS2010).</p> <p>I wouldn't want to use it all the time, but then I am working on a laptop. Given a really meaty multicore home desktop (preferrably with hardware support, of course, and lots of memory) it could be reasonably practical for day-to-day use.</p> <p><a href="http://vmware.com" rel="nofollow noreferrer">VMWare Player</a> is free and some people find it faster - I haven't used it enough to compare the two properly myself. If you're spend a lot of time "in" the VM, it would probably be worth giving both a proper test-drive.</p>
<p>You can run your dev tooling natively on your pick of O/S. and use VM's to test on other environments. Get lots of memory if you're going to do this, say 2GB or more - if you haven't already. </p> <p>AMD chips have some facilities (nested page tables etc.) that improve VM performance. 2nd gen Opterons and some Athlon 64 chips will support this for reasonable money. You can even get brand-name hardware like an HP XW4550 with this sort of chip for fairly reasonable money. I'm not sure to what extent Intel has caught up with this yet.</p>
34,827
<p>I'm trying to make a javascript dropdown list using scriptaculous and prototype. I know this can be done using CSS :hover pseudo-selectors, but I would like to add some additional flair to it. The problem is that while I can kind of get the dropdown/up effect working, it seems very flaky. Is there a simple way to do this, or should I stick to the hovers? Here is the CSS I'm using.</p> <pre><code>&lt;style type="text/css"&gt; ul {list-style-type: none} #navbar&gt;li { position: relative; float: left; padding-right: 20px; height: 2em; background-color: #002; } ul.dropdown { display: block; position: absolute; top: 2em; left: 0px; background-color: #00c; } &lt;/style&gt; </code></pre> <p>And here is the html (I added the style="display: none" per the documentatoin, which said to put it there instead of in a stylesheet if you want the target to initially be hidden).</p> <pre><code>&lt;ul id="navbar"&gt; &lt;li onmouseover="Effect.BlindDown('dropdownone', { duration: 0.8 })" onmouseover="Effect.BlindUp('dropdownone', { duration: 0.8 })"&gt;&lt;a href=""&gt;Menu Link 1&lt;/a&gt; &lt;ul id="dropdownone" class="dropdown" style="display: none"&gt; &lt;li&gt;Drop Down Link 1&lt;/li&gt; &lt;li&gt;Drop Down Link 2&lt;/li&gt; &lt;li&gt;Drop Down Link 3&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Menu Link 2&lt;/a&gt; &lt;ul id="dropdowntwo" class="dropdown"&gt; &lt;li&gt;Drop Down Link 1&lt;/li&gt; &lt;li&gt;Drop Down Link 2&lt;/li&gt; &lt;li&gt;Drop Down Link 3&lt;/li&gt; &lt;li&gt;Drop Down Link 4&lt;/li&gt; &lt;li&gt;Drop Down Link 5&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Menu Link 3&lt;/a&gt; &lt;ul id="dropdownthree" class="dropdown"&gt; &lt;li&gt;Drop Down Link 1&lt;/li&gt; &lt;li&gt;Drop Down Link 2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
<p>This effect seems to work fine <a href="http://www.java2s.com/Code/JavaScriptDemo/TextBlindUpandBlindDown.htm" rel="nofollow noreferrer">with 'onclick' events</a></p> <p>But with onmouseover, <a href="http://osdir.com/ml/lang.ruby.rails.spinoffs/2006-06/msg00358.html" rel="nofollow noreferrer">I read</a> that you need to use the effect <a href="http://www.clientcide.com/3rd-party-libraries/scriptactulous/scriptaculous-and-its-effectqueue/" rel="nofollow noreferrer">queue</a> so your blind up and blind down are not stepping on each other, like <a href="https://stackoverflow.com/questions/49630/problems-with-mouseout-event">in this script</a>.</p> <blockquote> <p>A queue is a list of events (in the current context Effects). These events take occur one after the other (or parallel) for the purpose of preventing disturbence of current actions.</p> </blockquote>
<p>The queues don't seem to help. After trying different things for over an hour, I am going to give up and just stick with plain hover menus. It's funny because I assumed this was the sort of basic UI enhancement effect these libraries were supposed to make easy.</p>
37,490
<p>According to Martin Fowler "Something can be public but that does not mean you have published it." Does this mean something like this:</p> <pre><code>public interface IRollsRoyceEngine { void Start(); void Stop(); String GenerateEngineReport(); } public class RollsRoyceEngine : IRollsRoyceEngine { public bool EngineHasStarted { get; internal set; } public bool EngineIsServiceable { get; internal set; } #region Implementation of IRollsRoyceEngine public void Start() { if (EngineCanBeStarted()) EngineHasStarted = true; else throw new InvalidOperationException("Engine can not be started at this time!"); } public void Stop() { if (EngineCanBeStopped()) EngineHasStarted = false; else throw new InvalidOperationException("Engine can not be started at this time!"); } public string GenerateEngineReport() { CheckEngineStatus(); return EngineIsServiceable ? "Engine is fine for now" : "Hmm...there may be some problem with the engine"; } #endregion #region Non published methods public bool EngineCanBeStarted() { return EngineIsServiceable ? true : false; } public bool EngineCanBeStopped() { return EngineIsServiceable ? true : false; } public void CheckEngineStatus() { EngineIsServiceable = true; //_EngineStatus = false; } #endregion } </code></pre> <p>Can it be said that published interface of this is IRollsRoyceEngine not whatever is in RollsRoyceEngine? </p> <p>If so what is the real difference between public and published methods?</p>
<p>I assume he means that the contract is king - just because a method in your class is public, doesn't entitle clients to assume that they can call it, or that they know what it does, or that it will be there in the next version. APIs are not defined by the source, they're defined by a contract, usually in the form of documentation.</p> <p>It is the responsibility of the client not to call undocumented (unpublished) functions, not the responsibility of the implementer to hide methods which shouldn't be called.</p> <p>Some people might disagree with this - typically those who don't trust documentation, and would rather find out how things work by looking at the source to see what it <em>actually</em> does, rather that what the author <em>claims</em> it does. They may well have a point, especially in practice when dealing with under-documented code. But I think that's in opposition to what Fowler is saying, which is that functionality should be formally defined, rather than inferred by examination of the particular implementation.</p>
<p>I assume he means that the contract is king - just because a method in your class is public, doesn't entitle clients to assume that they can call it, or that they know what it does, or that it will be there in the next version. APIs are not defined by the source, they're defined by a contract, usually in the form of documentation.</p> <p>It is the responsibility of the client not to call undocumented (unpublished) functions, not the responsibility of the implementer to hide methods which shouldn't be called.</p> <p>Some people might disagree with this - typically those who don't trust documentation, and would rather find out how things work by looking at the source to see what it <em>actually</em> does, rather that what the author <em>claims</em> it does. They may well have a point, especially in practice when dealing with under-documented code. But I think that's in opposition to what Fowler is saying, which is that functionality should be formally defined, rather than inferred by examination of the particular implementation.</p>
47,795
<p>I'm using the <a href="http://www.microsoft.com/unlimitedpotential/programs/multipoint.mspx" rel="nofollow noreferrer">MultiPoint</a> SDK to create a collaborative educational application for children in less affluent countries, where there is not one computer for each student in the classroom.</p> <p>Because we need to support up to 40 mice connected to one computer, we need an automated way to test our software. The SDK will support as many mice that it can find on the system and detects when mice are added and removed. Each mouse appears as a 'virtual' mouse pointer within a WPF window. Each child has independent control of 'their' pointer on the screen.</p> <p>We would like to create a test harness that tricks Windows into thinking that it has more than one mouse. The harness would need to create these fake devices (40+) and use them to send mouse messages like move, button down, etc</p> <p>Any help would be greatly appreciated.</p>
<p>Faking mice to the extent that you'd need for MultiPoint is going to require a device driver. This is not an easy task, but is by no means impossible.</p> <p>The best approach would probably be a <a href="http://msdn.microsoft.com/en-us/library/ms790173.aspx" rel="nofollow noreferrer">HID minidriver</a> that you can install using the <a href="http://msdn.microsoft.com/en-us/library/aa972910.aspx" rel="nofollow noreferrer">Setup API</a>. The driver would then accept <code>DeviceIoControl</code>s which would cause it to simulate mouse input reports.</p>
<p>you could use dsf(device simulation framework) in the ddk(driver development kit) for windows to add an emulated device dont worry its samples are in vbscript and you just need to figure out the correct input report format and codes to send.</p>
38,692
<p>I'm having some trouble with Visual Studio 2008 on my Windows XP SP2 laptop.</p> <p>What happens is that when I start a program with a few textboxes and stuff like that, the boxes are see-through. I can litteraly see through them and see what's on the underlaying screen. Like if I only have this Form showing and behind that my wallpaper, I can see my wallpaper through the Textbox, ComboBox, even through the small cracks between various elements.</p> <p>i've searched the web but haven't encountered info on this yet. Does anybody know what might be causing this and how to solve it? I'm in the process of trying to see how the text in my TextBoxes is parsed, but I can't since I can't even enter anything. I click on the textbox and I'm focused on the desktop...</p>
<p>Hmmm... I'm not sure about this, but check the "Transparency" property of your main form. That's all I can think that it might be as of now...</p> <p>Update: I meant the "<strong>Opacity</strong>" property, sorry. Update 2: No, never mind, sorry. Right-click the "<strong>TransparencyKey</strong>" property, and press <code>Reset</code> to set it back to default.</p>
<p>Check TransparencyKey, Opacity and maybe TransparencyMask?</p>
26,503
<p>I recently purchased a Windows Server 2008 server, Our company will be using it as a Web Server. I have set the web site up in IIS 7.0 and I can accsess it by typing <a href="http://10.1.1.8" rel="nofollow noreferrer">http://10.1.1.8</a> on the computers within the network.</p> <p>When I try to accsess it through the net on other computers it doesnt seem to work, But most important, How do I set up a web domain such as (www.example.com) ??</p> <p>Many Thanks, Oliver</p>
<p>Disclaimer : I dont work all that much under Windows</p> <p>In the general case, you shouldnt mess with your OS cache. It should be smart enough to cache data that are accessed often. If it isnt, you should use an application level cache. I dont know which language you are using, but most probably there is a good cache framework for your language.</p>
<p>If your in .net and the file is a dll, look into the <a href="http://en.wikipedia.org/wiki/Global_Assembly_Cache" rel="nofollow noreferrer">Global Assembly Cache (GAC)</a>.</p>
40,502
<p>Is there a known math formula that I can use to estimate the size of a new Lucene index? I know how many fields I want to have indexed, and the size of each field. And, I know how many items will be indexed. So, once these are processed by Lucene, how does it translate into bytes? </p>
<p>Here is the <a href="http://lucene.apache.org/core/3_6_1/fileformats.html" rel="nofollow noreferrer">lucene index format documentation</a>. The major file is the compound index (.cfs file). If you have term statistics, you can probably get an estimate for the .cfs file size, Note that this varies greatly based on the Analyzer you use, and on the field types you define.</p>
<p>I think it has to also do with the frequency of each term (i.e. an index of 10,000 copies of the sames terms should be much smaller than an index of 10,000 wholly unique terms).</p> <p>Also, there's probably a small dependency on whether you're using Term Vectors or not, and certainly whether you're storing fields or not. Can you provide more details? Can you analyze the term frequency of your source data?</p>
9,112
<p>I'm using Cura and it removes my holes and deletes sections of the print and disconnects parts. In Blender it looks as it should be, as I designed it. I know there are a few mishaps inside (not manifold) but is there a way to fill in everything on the inside. I only care about the externally facing faces. This is extremely infuriating I hope someone can tell me how to force Cura to print what is originally seen in the .stl.</p> <p><a href="https://i.stack.imgur.com/vhECG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vhECG.png" alt="Blender as it should look" /></a></p> <p><a href="https://i.stack.imgur.com/spmc4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/spmc4.png" alt="Again how I designed it." /></a></p> <p><a href="https://i.stack.imgur.com/R5IEQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R5IEQ.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/XhOsa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XhOsa.png" alt="enter image description here" /></a></p> <p>These are photos of how it should look.</p> <p>Now these next photos are how Cura previews it. Not only does it fill in the holes (no, fill holes isn't enabled) it adds huge gaps in the side and bottom of the print as can be seen.</p> <p><a href="https://i.stack.imgur.com/nhQv4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nhQv4.png" alt="All messed up." /></a></p> <p><a href="https://i.stack.imgur.com/H1eTp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H1eTp.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Q51Me.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q51Me.png" alt="enter image description here" /></a></p> <p>How can I force Cura to print what I see in blender in the original .stl?</p> <p>I am exporting in Blender to .stl and opening that in Cura.</p> <hr /> <p>I was able to fix it partially by fixing normals in Blender but there is still this:</p> <p><a href="https://i.stack.imgur.com/Rjk38.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rjk38.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/lFOfR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lFOfR.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/wPoMg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wPoMg.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Z2Uuy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z2Uuy.png" alt="enter image description here" /></a></p>
<p>It's common for modeling software to flip normals, causing what you describe. You said,</p> <blockquote> <p>I only care about the externally facing faces.</p> </blockquote> <p>But are you sure they are truly externally facing? Turn on normals in Blender and ensure that all the arrows/pointers are external.</p> <p>Another problem that can generate the results you're seeing are self-intersecting surfaces, non-manifold edges, and a couple others that are explained in a <a href="https://www.3dhubs.com/knowledge-base/fixing-most-common-stl-file-errors/" rel="nofollow noreferrer">3dhubs article.</a> Correcting those problems involve a bit more examination and trouble shooting.</p> <p>The slicing software prefers to have clean, well defined triangular surfaces in order to create a print file. When something is amiss, you get results you've presented.</p> <p>With the STL in hand, I opened it in Meshmixer (free) and immediately was given a clue.</p> <p><a href="https://i.stack.imgur.com/oITba.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oITba.png" alt="STL image in meshmixer" /></a></p> <p>The zebra-stripes are reversed normals.</p> <p>Here's another error point, difficult to see clearly in flat 2D image, but panning and zooming and orbiting and all those 3D manipulating things shows there's nothing there:</p> <p><a href="https://i.stack.imgur.com/FrtCK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FrtCK.png" alt="broken corner" /></a></p> <p>The other end of this not-joined area shows a bit better:</p> <p><a href="https://i.stack.imgur.com/IH41m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IH41m.png" alt="other broken corner" /></a></p> <p>After selecting all I could find/locate, I did the reverse normals and here's a slightly improved result:</p> <p><a href="https://i.stack.imgur.com/GcpRG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GcpRG.png" alt="corrected part" /></a></p> <p>Unfortunately, the other borked up portions prevented meshmixer from performing a suitable auto-repair, completely destroying the model in the process.</p> <p>Those joint corners and any other colored lines have to be addressed individually.</p>
<p>Okay, so like suggested I put it into 3D Builder (A free Windows 3D modeling program). I imported it as an stl, then exported it as an stl and imported that stl into Cura. And lo and behold all problems were gone! If you are having a similar issue give that a try! The 3D Builder program and similar ones are designed to export for the sole purpose of 3D printing so it automatically fixes these issues! If this doesn't work try editing yours in edit mode (Blender) a bit so it makes it easier for 3D Builder to fix it.</p>
1,891
<p>I am attempting to pass information from a task created within a workflow to its corresponding task form. Prior to the CreateTask activity, I create an SPWorkflowTaskProperties and fill it with the usual info (title, assigned-to, etc). I also add some elements to the ExtendedProperties property. However, those custom properties never make it into the Task.</p> <p>I've tried setting the property key to:</p> <ul> <li>the Guid of one of my task' content type's fields;</li> <li>the internal name of one of my task' content type's fields;</li> <li>an unrelated name (in the hopes of getting the info into the task's properties instead of its fields).</li> </ul> <p>Nothing works. The task, once created, contains only the built-in field values I have set. None of values I explicitly added to the extended properties show up.</p> <p>The (simplified) sequence of my activities is as follows:</p> <ul> <li>PrepareTask. This is a custom activity that contains the SPWorkflowTaskProperties </li> <li>CreateTask. The task properties are bound to the one in the PrepareTask activity.</li> <li>OnTaskCreated. The task properties are bound to the one in the PrepareTask activity.</li> <li>While (task not complete) <ul> <li>OnTaskChanged</li> </ul></li> </ul> <p>I am using WSS 3.0 SP1 and an ASPX (NOT InfoPath) task form.</p>
<p>I still don't know why my original solution didn't work. But I have found a workaround. My sequence of activities is now:</p> <ul> <li>CreateTask</li> <li>OnTaskCreated</li> <li>CopyTaskItems. This is a custom activity that puts values into my custom task's fields, then updates the task.</li> <li>While (task not complete) <ul> <li>OnTaskChanged</li> </ul></li> </ul> <p>So I have to create the task, then immediately poke values into it and update.</p> <p>I hope this will help some future reader of this question.</p>
<p>You should be using a ItemMetadata.xml document as a secondary datasource that contains the definition of the fields that you want to pass to your task form. Something like:</p> <pre><code>&lt;z:row xmlns:z="#RowsetSchema" ows_Instructions="" ows_Body="" ows_Comments="" ows_ApprovalStatus="" /&gt; </code></pre> <p>The File name is important btw.</p> <p>Notice the <code>ows_</code> (as it used the webservices all fields in the list will be prefixed with <code>ows</code>.)</p> <p>Then in you infopath form, set the default value of each control you want to display this information in. Hit the fx button and insert a field or group from the secondary datasource.</p> <p>A good resource: <a href="http://weblog.vb-tech.com/nick/archive/2007/02/25/2207.aspx" rel="nofollow noreferrer">http://weblog.vb-tech.com/nick/archive/2007/02/25/2207.aspx</a></p>
26,950
<p>In .Net (VB more specifically, but that doesn't really matter), is there a way to change the format of a number from one culture to another strictly through the that number's type? </p> <p>The issue is this: In English, the number is say, 123.45. Whereas in Sweden, the number would be 123,45</p> <p>Is there a way to convert 123,45 to 123.45 without having to convert it to a string (and then use the formatting methods) then convert it back to the correct type (single, double, etc)?</p>
<p>It wouldn't be a case of converting <em>into</em> a string and then <em>back</em> to the correct type - quite the opposite.</p> <p>The number itself doesn't have any formatting information about it. A float is a float is a float. It's only when you parse or format that the culture becomes relevant.</p> <p>If you've already got a float value, then just format it appropriately based on the culture of whoever's reading it.</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx" rel="nofollow noreferrer">NumberFormatInfo</a> class to do that.</p>
31,683
<p>I have a bash script that creates a Subversion patch file for the current directory. I want to modify it to zip the produced file, if <code>-z</code> is given as an argument to the script.</p> <p>Here's the relevant part:</p> <pre><code>zipped='' zipcommand='&gt;' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip &gt;' fi echo "Creating ${zipped}patch file $filename..." svn diff $zipcommand $filename </code></pre> <p>This doesn't work because it passes the <code>|</code> or <code>></code> contained in <code>$zipcommand</code> as an argument to <code>svn</code>.</p> <p>I can easily work around this, but the question is whether it's ever possible to use these kinds of operators when they're contained in variables.</p> <p>Thanks!</p>
<p>I would do something like this (use bash -c or eval):</p> <pre><code>zipped='' zipcommand='&gt;' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip -@' fi echo "Creating ${zipped}patch file $filename..." eval "svn diff $zipcommand $filename" # this also works: # bash -c "svn diff $zipcommand $filename" </code></pre> <p>This appears to work, but my version of zip (Mac OS X) required that i change the line:</p> <pre><code>zipcommand='| zip -@' </code></pre> <p>to</p> <pre><code>zipcommand='| zip - - &gt;' </code></pre> <p>Edit: incorporated @DanielBungert's suggestion to use eval</p>
<p>Or you should try <code>zsh</code> shell whic allows to define global aliases, e.g.:</p> <pre><code>alias -g L='| less' alias -g S='| sort' alias -g U='| uniq -c' </code></pre> <p>Then use this command (which is somewhat cryptic for the ones who took a look from behind ;-) )</p> <pre><code>./somecommand.sh S U L </code></pre> <p>HTH</p>
15,691
<p>I'm trying the following command on my shell:</p> <pre><code>curl -b usptoCookies -L -d "patentNum=6836866&amp;applicationNum=10007391&amp;maintFeeAction=Get+Bibliographic+Data&amp;maintFeeYear=04" https://ramps.uspto.gov/eram/getMaintFeesInfo.do;jsessionid=0000Nmdd1Q_YsDF90HKmb9EIIgq:11g0uehq7 </code></pre> <p>Pretty straighforward. It is attempting to post a few variables to a form. You can see the web page here: <a href="https://ramps.uspto.gov/eram/" rel="nofollow noreferrer">https://ramps.uspto.gov/eram/</a></p> <p>Try putting in the patent number and application number as: 6836866 and 10007391. Then hit the Get Bibliographic Data button.</p> <p>The web page returns stuff (a "neatly" formatted table), but the curl call seems to experience "some" problem. I am at a loss. I've used firebug on the browser to confirm that the three vars above are all that are required to complete the form post.</p> <p>It is not a problem with https, because i do get a response back. I need help.</p> <p>Anyone?</p> <p>Shaheeb Roshan</p>
<p>There's a bunch of other hidden fields in that form including a "signature". Which seems to be some unique string each time you request a page. This is probably a feature used to ensure that you aren't scraping all the information off their database.</p> <p>When I emptied out the hidden signature field, it returned an error. If you want to write a program to fetch this information, you will probably have to do something a little more complicated, and fetch the page with the "signature" on it first, so you can post that value back to the site to get a proper response.</p>
<p>I thought that might be the case, so on one of my scrapes, I had it output the content to a page that I could open in my browser. This allowed me to manipulate the form elements and re-submit to see if removing certain hidden fields would affect the post. When I opened the page and removed all hidden fields (including sessionId, signature and loadtime), I was still able to submit the form to get a valid response.</p> <p>Thinking this may be pointing to some cookie or session related problem, I fired up Selenium (through the Testing_Selenium package) and attempted the same scrape. The idea was that since Selenium actually uses a real browser, any session/cookie issue should be eliminated.</p> <p>When the Selenium run failed in the same way as the curl run, I was at my wit's end.</p> <p>I was hoping someone could see something weird or unusual about this page that might explain the failure.</p> <p>Thanks for your input, what do you think?</p> <p>Shaheeb R.</p>
47,780
<p>How can I get Emacs style key bindings in Visual Studio? Is it available in Settings? Do I need a Plug-in?</p>
<p>You can try the Emacs keyboard scheme (<strong>Tools->Options->Environment->Keyboard</strong>)</p>
<p>A quick Live search for "visual studio emacs" gave <a href="http://msdn.microsoft.com/en-us/library/ms165509(VS.80).aspx" rel="nofollow noreferrer">this page</a>. I'm not sure how thorough it is though (having never used emacs myself).</p>
23,106
<p>I was recently tasked to document a large JavaScript application I have been maintaining for some time. So I do have a good knowledge of the system.</p> <p>But due the sheer size of the application, it will probably take a lot of time even with prior knowledge around the code and the source code itself in uncompressed form.</p> <p>So I'm looking for tools that would help me explore classes and methods and their relationships in JavaScript and if possible, document them along the way, is there one available?</p> <p>Something like object browser in VS would be nice, but any tools that help me get things done faster will do.</p> <p>Thanks!</p>
<p><a href="https://addons.mozilla.org/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a>'s <a href="http://getfirebug.com/dom.html" rel="nofollow noreferrer">DOM tab</a> lets you browse the contents of the global <code>window</code> object, and you can inspect a particular object by entering <code>inspect(whatever)</code> in the command line.</p> <p>You won't be able to use it to detect relationships unless an instance of one object holds an instance of a related object, but it's a start.</p> <p>You can also use the Options menu on the DOM tab to restrict what's shown to user-defined functions and properties, which should help reduce clutter.</p>
<p>We don't know if this JS application is designed to run in a Web browser...<br> If yes, as advised, Firebug (a Firefox extension) is excellent at debugging JS and exploring Dom.<br> On the IE side, you have some tools like <a href="http://www.cheztabor.com/IEDocMon/index.htm" rel="nofollow noreferrer" title="IEDocMon">IEDocMon</a>, <a href="http://www.visionaustralia.org.au/ais/toolbar/" rel="nofollow noreferrer" title="Web Accessibility Toolbar">Web Accessibility Toolbar</a> (it does more than its name) or <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer" title="Fiddler">Fiddler</a> (unrelated to your question, but still a good tool to have).</p>
17,285
<p>What is the best way to convert existing jar (without source) written in java 1.5 into java 1.4.x?</p>
<p>Take a look at <a href="http://retroweaver.sourceforge.net/index.html" rel="noreferrer">Retroweaver</a>. It will convert the classes or jar so that it can be run using a 1.4 JRE. Depending on the 1.5 features used, you won't need any additional retroweaver run-time.</p> <p>Retroweaver uses byte code enhancement. It sounds mysterious but it works. </p>
<p>My gut instinct would be to decompile the jar, then recompile as 1.4.</p> <p>If there are no 1.5 specific API calls in the decompiled code, that should work fine. If there are, you will need to re-engineer those sections to work in the earlier java version.</p>
21,305
<p>What is the difference between request, response and server?</p>
<p><strong>Request :</strong> From Client to Server<br> <strong>Response:</strong> From Server to Client<br> <strong>Server:</strong> Receive Request and Send Response<br> <strong>Client:</strong> Send Request and Receive Response </p>
<p>The 1st answer (Ramesh Soni's answer) is simple and concise. I also wanna share a useful terms distinction that's relevance to this. </p> <h1>What's the difference between request and query???</h1> <ul> <li><p>First of all, <strong>query and request can both be nouns and verbs</strong>. E.g: </p> <ul> <li>I requested a refund. </li> <li>We received a request for a refund. </li> <li>I queried the price. </li> <li>We received a query about the price. </li> </ul></li> <li><p>To request something is to ask for something, an object or a favour etc. A request is a <em>polite demand</em>. To query is to ask about something i.e. you are <strong><em>wanting information</em></strong>. <em>A query is a question</em>.</p></li> <li><p>Also, QUERY is an inquiry(<em>Query and inquiry are synonyms</em>) They are both requests but the difference is that the <strong>QUERY is a precise request</strong>. In informatics, if you need information about something you need to send a <em>specific</em> request with precise information.</p></li> </ul> <p>"I queried information about user account Maxim Pavlov" = "I need to know about this website users. In particular, I need to know if there is any Maxim Pavlov registered on this site".</p> <ul> <li>If you are Arabic, best translations in Arabic would be, <em>request = طلب and query = إستعلام</em>)</li> </ul>
36,851
<p>I have a little pet web app project I'd like to show someone who doesn't have an application server themselves (and who has no clue about application servers).</p> <p>What is the easiest and quickest way for them to get my WAR file running with zero configuration, preferably something I could send along with or bundle with the WAR file? Is there a slimmed down version of Jetty, for example? Something else?</p>
<p>You can create the slimmed down version yourself easily.</p> <p><a href="http://docs.codehaus.org/display/JETTY/Embedding+Jetty" rel="nofollow noreferrer">http://docs.codehaus.org/display/JETTY/Embedding+Jetty</a></p> <p><a href="http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html" rel="nofollow noreferrer">http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html</a></p> <p>To run embedded Jetty you need only the following jars on the classpath:</p> <pre><code>* servlet-api-2.5-6.x.jar * jetty-util-6.x.jar * jetty-6.x.jar /usr/local/jetty-6.1.4/lib&gt; ls -la servlet-api-2.5-6.1.4.jar jetty-* -rw-rw-r-- 1 wwwrun admin 476213 2007-06-15 08:42 jetty-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 128026 2007-06-15 08:40 jetty-util-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 131977 2007-06-15 08:40 servlet-api-2.5-6.1.4.jar </code></pre> <p>Very light... </p> <p>Alternatively, the Maven <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin" rel="nofollow noreferrer">plugin</a> can work as well.</p>
<p>I would definitely just create an executable jar that embeds jetty and uses your war. The maven thing might be ok, but it's pretty easy to just write the single main function yourself.</p>
30,013
<p>It'd be really nice to target my Windows Forms app to the .NET 3.5 SP1 <em>client</em> framework. But, right now I'm using the <code>HttpUtility.HtmlDecode</code> and <code>HttpUtility.UrlDecode</code> functions, and the MSDN documentation doesn't point to any alternatives inside of, say, System.Net or something.</p> <p>So, short from reflectoring the source code and copying it into my assembly---which I don't think would be worth it---are there alternatives inside of the .NET 3.5 SP1 client framework that you know of, to replace this functionality? It seems a bit strange that they'd restrict these useful functions to server-only code.</p>
<p>Found today from <a href="http://10rem.net/blog/2010/04/07/encoding-decoding-uris-and-html-in-the-net-4-client-profile?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+PeteBrown-ASPNET+%28Pete+Brown%27s+Blog+%3A+ASP.NET%29" rel="noreferrer">this here little site</a> that HtmlEncode/Decode can be done using System.Net library in C# 4.0 Client Profile:</p> <pre><code>Uri.EscapeDataString(...) WebUtility.HtmlEncode(...) </code></pre> <p>Edit: I re-read that the question applied for the 3.5 Client Framework but maybe this can be useful those who have updated 4.0..</p>
<p>Two main ways :</p> <ol> <li>Deploy using the full .NET Framework</li> <li>Write your own / 3rd party lib for these functionalities</li> </ol>
5,697
<p>I have a Windows 2008 Server (x64) running Microsoft SQL 2008 (x64) and I'm creating a Linked Server connection to an Oracle server. I'm able to make the connection, but I cannot see any information regarding which schema a table belongs to.</p> <p>In SQL 2005, my linked servers show the schema information as I would expect.</p> <p>Does anyone know how to resolve this issue? Is it an issue with the provider, OraOLEDB.Oracle?</p> <p>Any help or pointers would be appreciated.</p>
<p>@Boojiboy - When you are looking at the tables via a linked server, there used to be a column for what schema. It appears that in the latest the new Oracle OLEDB drivers don't show this information any longer.</p>
<p>Also in the SQL 08 > Server Objects > Providers make sure your OraOLEDB.Oracle provider is allowing inprocessing</p>
4,632
<p>I have a vs.net project, and after some refactoring, have modified the name of the project. How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution?<br> Note, I used to be able to do by fiddling with things in the background using SourceSafe ... </p>
<ol> <li><strong>Check in</strong> all pending changes within the folder and ensure that all other team members to do the same.</li> <li>Ensure that you have a copy of the folder in your working directory (otherwise, you will not have the option to rename the folder in the <em>Source Control Explorer</em> in the next step). <strong>Get latest version</strong> on the folder to get a copy if you don't already have one.</li> <li><strong>Close the solution</strong>.</li> <li><strong>Rename</strong> the folder within the <em>Source Control Explorer</em>. This will move all of the files that are tracked in source control from the original folder on your file system to the new one. Note that files not tracked by source control will remain in the original folder - you will probably want to remove this folder once you have confirmed that there are no files there that you need.</li> <li><strong>Open the solution</strong> and select '<strong><code>No</code></strong>' when prompted to get projects that were newly added to the solution from source control. You will get a warning that one of the projects in the solution could not be loaded.</li> <li><strong>Select the project</strong> within <em>Solution Explorer</em>. <blockquote> <p>Note that it will be grayed out and marked as <em>'Unavailable'</em>.</p> </blockquote></li> <li>Open the <strong>Properties</strong> pane.</li> <li><strong>Edit the <em>'File Path'</em></strong> property either directly or using the '<code>...</code>' button. <blockquote> <p>Note also that this property is <a href="http://blogs.msmvps.com/deborahk/solution-files-change-project-directory-location/" rel="noreferrer">only editable in Visual Studio 2010</a>. In newer versions of Visual Studio, you will need to manually edit the project paths within the solution file.</p> </blockquote></li> <li>Right-click on the project in the <em>Solution Explore</em>r and select <strong>Reload Project</strong> from the context menu. If you get an error message saying that the project cannot be loaded from the original folder, try closing the solution, deleting the suo file in the same folder as the solution file then reopening the solution.</li> <li><strong>Check in</strong> the changes as a single changeset.</li> <li>Have other team members 'Get latest version' for the solution (right click on the solution within <em>Solution Explorer</em> and select 'Get Latest Version' from the context menu.</li> </ol> <hr> <blockquote> <p>Note: Other suggested solutions that involve removing and then re-adding the project to the solution will break project references.</p> </blockquote> <p>If you perform these steps then you might also consider renaming the following to suit.</p> <ol> <li>Project File</li> <li>Default/Root Namespace</li> <li>Assembly</li> </ol> <p>Also, consider modifying the values of the following <a href="http://msdn.microsoft.com/en-us/library/4w8c1y2s.aspx" rel="noreferrer">assembly attributes</a>.</p> <ol> <li><code>AssemblyProductAttribute</code></li> <li><code>AssemblyDescriptionAttribute</code></li> <li><code>AssemblyTitleAttribute</code></li> </ol>
<p>You could just rename the project (.Xproj file and project folder) in TFS, delete the local folder structure and all of its contents, then do a get latest for the project. All of this depends the notion of your source repository is completely up to date and compilable.</p>
7,147
<p>I work on small sites for tanning salons and stuff. We don't support ActiveX-specific stuff on IE, and we support Firefox. I've noticed some weird behavior with Chrome. My browser stats say &lt;1% of my visitors use Chrome. </p> <p>I've heard people say it's nowhere near best in class. But I like the way everything runs in its own process and stuff. </p> <p>Is Chrome going to get popular enough that I need to code for it? By the time it gets popular, will its weird rendering get fixed? </p>
<p>Write code to standards first, then for different rendering engines if needed. Never design websites for specific browsers, it's a very slippery slope.</p>
<p>I don't think you should need to code anything specific for Chrome. If they say that web standards are important to them, then Chrome will eventually follow those standards to a tee.</p> <p>I also don't believe Chrome will get very popular. When I saw it the first thing I thought was "Wow... Mozilla with a G print on it." And I have not really been very impressed since.</p> <p>Bottom line: You should make an attempt to make your site support the major browsers. Opera, IE, Firefox. Usually, following web standards and best practices will accomplish this. Other times you need to create work arounds or force browsers to act a certain way. I.E. Firefox and IE use a different border model. You can force at least FF to use the same border model as IE does.</p>
46,541
<p>I have a MOSS 2007 test site, its not public facing, instead its on our intranet, I am looking for an uptime monitoring component thats free and easy to install, any suggestions?</p> <p>Update: I don't need graphs or anything fancy, I just need to make sure that I get a notification via email if the site goes down. </p>
<p><a href="http://www.nagios.org/" rel="nofollow noreferrer">Nagios</a> might be overkill, but it is not too hard to put in place ...</p>
<p>I also came across OpManager - <a href="http://manageengine.adventnet.com/products/opmanager/" rel="nofollow noreferrer">http://manageengine.adventnet.com/products/opmanager/</a></p> <p>There is a free version which allows monitoring of 10 services. </p> <p>I tried to get it to install on my SQL 2008 Server, but ended up just using the product default mySQL installation. </p> <p>I also decided to uninstall it after 10 minutes worth of use, it seems like a great tool for a fully qualified network administrator, but it adds too much bloat to have it installed on my development server. </p>
43,223
<p>I have two combos; provinces and cities. I would like to change cities value when the province combo value changes. Here is my code</p> <pre><code>&lt;div class="cities form"&gt; &lt;?php $v = $ajax-&gt;remoteFunction(array('url' =&gt; '/cities/','update' =&gt; 'divcity')); print $form-&gt; input('Province.province_id', array('type' =&gt; 'select', 'options'=&gt; $provinces, 'onChange' =&gt; $v)); ?&gt; &lt;div id="divcity"&gt; &lt;?php echo $form-&gt;input('Cities.cities_name'); ?&gt; &lt;/div&gt; </code></pre> <p>Every time I change province combo, it call <code>cities/index.ctp</code>. anybody want to help? really thank for your help wawan</p>
<p>The 'url' => '/cities/' is calling the default index action of the cities controller.</p> <p>This automatically renders the cities/index.ctp view.</p> <p>Have you included the RequestHandler component in the cities controller?</p> <p>This can be used to detect Ajax requests and then render a different view.</p>
<p>You need to first include the <a href="http://book.cakephp.org/view/174/Request-Handling" rel="nofollow noreferrer">RequestHandler Component</a> at the top of the CitiesController, then write a function to list cities, optionally requiring a Province's id.</p> <p>I think you'll end up having something like this:</p> <pre><code>&lt;?php // In the view $v = $ajax-&gt;remoteFunction(array('url' =&gt; '/cities/list','update' =&gt; 'divcity')); print $form-&gt; input('Province.province_id', array('type' =&gt; 'select', 'options'=&gt; $provinces, 'onChange' =&gt; $v)); // In CitiesController function list($province_id = null) { // use $this-&gt;City-&gt;find('list', array('fields'=&gt;array('City.id', 'City.name'))) // to generate a list of cities, based on the providence id if required if($this-&gt;RequestHandler-&gt;isAjax()) { $this-&gt;layout = 'ajax'; $this-&gt;render(); } } ?&gt; </code></pre>
30,799
<p>I am trying to determine the best time efficient algorithm to accomplish the task described below.</p> <p>I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.</p> <p>All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).</p> <p>I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).</p> <p>Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).</p> <p>For example:</p> <pre> If I have the following records: A, B, C, D, E and the following represents the connections: (A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E), (C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E) [where (A,B) means record A connects to record B] </pre> <p>If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.</p> <pre> All paths connecting B to E: B->E B->F->E B->F->C->E B->A->C->E B->A->C->F->E </pre> <p>This is an example, in practice I may have sets containing hundreds of thousands of records.</p>
<p>It appears that this can be accomplished with a depth-first search of the graph. <strong>The depth-first search will find all non-cyclical paths between two nodes.</strong> This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to).</p> <p>I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though.</p> <p><strong>Graph.java:</strong></p> <pre class="lang-java prettyprint-override"><code>import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; public class Graph { private Map&lt;String, LinkedHashSet&lt;String&gt;&gt; map = new HashMap(); public void addEdge(String node1, String node2) { LinkedHashSet&lt;String&gt; adjacent = map.get(node1); if(adjacent==null) { adjacent = new LinkedHashSet(); map.put(node1, adjacent); } adjacent.add(node2); } public void addTwoWayVertex(String node1, String node2) { addEdge(node1, node2); addEdge(node2, node1); } public boolean isConnected(String node1, String node2) { Set adjacent = map.get(node1); if(adjacent==null) { return false; } return adjacent.contains(node2); } public LinkedList&lt;String&gt; adjacentNodes(String last) { LinkedHashSet&lt;String&gt; adjacent = map.get(last); if(adjacent==null) { return new LinkedList(); } return new LinkedList&lt;String&gt;(adjacent); } } </code></pre> <p><strong>Search.java:</strong></p> <pre class="lang-java prettyprint-override"><code>import java.util.LinkedList; public class Search { private static final String START = "B"; private static final String END = "E"; public static void main(String[] args) { // this graph is directional Graph graph = new Graph(); graph.addEdge("A", "B"); graph.addEdge("A", "C"); graph.addEdge("B", "A"); graph.addEdge("B", "D"); graph.addEdge("B", "E"); // this is the only one-way connection graph.addEdge("B", "F"); graph.addEdge("C", "A"); graph.addEdge("C", "E"); graph.addEdge("C", "F"); graph.addEdge("D", "B"); graph.addEdge("E", "C"); graph.addEdge("E", "F"); graph.addEdge("F", "B"); graph.addEdge("F", "C"); graph.addEdge("F", "E"); LinkedList&lt;String&gt; visited = new LinkedList(); visited.add(START); new Search().depthFirst(graph, visited); } private void depthFirst(Graph graph, LinkedList&lt;String&gt; visited) { LinkedList&lt;String&gt; nodes = graph.adjacentNodes(visited.getLast()); // examine adjacent nodes for (String node : nodes) { if (visited.contains(node)) { continue; } if (node.equals(END)) { visited.add(node); printPath(visited); visited.removeLast(); break; } } for (String node : nodes) { if (visited.contains(node) || node.equals(END)) { continue; } visited.addLast(node); depthFirst(graph, visited); visited.removeLast(); } } private void printPath(LinkedList&lt;String&gt; visited) { for (String node : visited) { System.out.print(node); System.out.print(" "); } System.out.println(); } } </code></pre> <p>Program Output:</p> <pre class="lang-java prettyprint-override"><code>B E B A C E B A C F E B F E B F C E </code></pre>
<p>Here's a thought off the top of my head:</p> <ol> <li>Find one connection. (Depth-first search is probably a good algorithm for this, since the path length doesn't matter.)</li> <li>Disable the last segment.</li> <li>Try to find another connection from the last node before the previously disabled connection.</li> <li>Goto 2 until there are no more connections.</li> </ol>
8,268
<p>Would a LINQ for java be a useful tool? I have been working on a tool that will allow a Java object to map to a row in a database. </p> <ol> <li>Would this be useful for Java programmers? </li> <li>What features would be useful?</li> </ol>
<p>LINQ for Java would be lovely, but the problem is the language integration.</p> <p>Java doesn't have anything as concise as lambda expressions, and they're one of the bedrocks of LINQ. I suppose they <em>could</em> layer the query expression support on top of normal Java without lambda expressions, by making the expansion create anonymous inner classes - but it would be pretty hideous. You'd also need expression trees if you wanted to do anything like LINQ to SQL.</p> <p>Checked exceptions <em>might</em> get in the way, but we'd have to see. The equivalent of IQueryable would need to have some sort of general checked exception - or possibly it could be generic in both the element type and the exception type...</p> <p>Anyway, this is all pie-in-the-sky - given the troubles the Java community is having with closures, I think it would be folly to expect anything like LINQ in Java itself earlier than about 2012. Of course, that's not to say it wouldn't be possible in a "Java-like" language. Groovy has certain useful aspects already, for instance.</p> <p>For the library side, Hibernate already provides a "non-integrated" version of a lot of the features of LINQ to SQL. For LINQ to Objects, you should look at the <a href="http://code.google.com/p/google-collections/" rel="noreferrer">Google Java Collections API</a> - it's a lot of the same kind of thing (filtering, projecting etc). Without lambdas it's a lot fiddlier to use, of course - but it's still really, really handy. (I use the Google Collections code all the time at work, and I'd hate to go back to the "vanilla" Java collections.)</p>
<p>An extension to Java which gives LINQ-to-objects capabilities is <a href="http://code.google.com/p/sbql4j/" rel="nofollow noreferrer">SBQL4J</a>. It offers:</p> <ul> <li>Type-safety in compile time</li> <li>Powerful query engine with greater capabilities than LINQ</li> <li>Compatibility with current JVMs (it uses preprocessing to translate queries to pure Java code)</li> <li>Nice performance (no reflection is used at runtime)</li> <li>Clear, precise semantics without needless, obscure syntactic sugar.</li> </ul>
45,110
<p>My gcc build toolchain produces a .map file. How do I display the memory map graphically?</p>
<p>Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the <code>sections</code> and <code>symbols</code> lists).</p> <p>You can control the script by modifying these lines:</p> <pre><code>with open('t.map') as f: colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 </code></pre> <p>map2html.py</p> <pre><code>from __future__ import with_statement import re class Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+"" class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name #=============================== # Load the Sections and Symbols # sections = [] symbols = [] with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) &gt; 0: in_sections = False #=============================== # Gererate the HTML File # colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 segments = set() for s in sections: segments.add(s.segment) segment_colors = dict() i = 0 for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1 total_size = 0 for s in symbols: total_size += s.size sections.sort(lambda a,b: a.address - b.address) symbols.sort(lambda a,b: a.address - b.address) def section_from_address(addr): for s in sections: if addr &gt;= s.address and addr &lt; (s.address + s.size): return s return None print "&lt;html&gt;&lt;head&gt;" print " &lt;style&gt;a { color: black; text-decoration: none; font-family:monospace }&lt;/style&gt;" print "&lt;body&gt;" print "&lt;table cellspacing='1px'&gt;" for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height &gt; 1.0 else height print "&lt;tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'&gt;&lt;td style='overflow:hidden'&gt;" % \ (segment_colors[section.segment], height, height, font_size) print "&lt;a href='#%s'&gt;%s&lt;/a&gt;" % (sym.name, sym.name) print "&lt;/td&gt;&lt;/tr&gt;" print "&lt;/table&gt;" print "&lt;/body&gt;&lt;/html&gt;" </code></pre> <p>And here's a bad rendering of the HTML it outputs:</p> <p><img src="https://i.imgur.com/jsGhtBn.png" alt="Map"></p>
<p>I've written a C# program to display the information in a Map file along with information not usually present in the map file (like static symbols provided you can use <code>binutils</code>). The code is available <a href="https://github.com/govind-mukundan/MapViewer" rel="nofollow noreferrer">here</a>. In short it parses the map file and also uses <code>BINUTILS</code> (if available) to gather more information. To run it you need to download the code and run the project under visual studio, browse to the map file path and click <code>Analyze</code>.</p> <p>Note: Only works for <code>GCC/LD</code> map files</p> <p>Screenshot: [<img src="https://i.stack.imgur.com/W9uZ9.png" alt="3]"></p>
7,084
<p>I am doing analysis on schema evolution and have really fallen short of real world database schemas that have evolved a bit and stored in version control. Mediawiki (<a href="http://svn.wikimedia.org/svnroot/mediawiki/trunk/phase3/maintenance/tables.sql" rel="nofollow noreferrer">http://svn.wikimedia.org/svnroot/mediawiki/trunk/phase3/maintenance/tables.sql</a>) seems to be a very good candidate so far. I've considered Bugzilla, but they don't seem to have .sql files in the trunk as in Mediawiki. Perl scripts have to be executed which builds the database schema/tables - so instead of getting only one file as in mediawiki(tables.sql), I now essentially have to download entire Bugzilla folder for different revisions to understand schema changes.</p> <p><strong>Question 1:</strong> I am wondering if any of you have known or worked with large database schemas that are open source, under revision control and changes large enough to make schema evolution analysis (preferrably have DDL scripts - .sql files).</p> <p><strong>Question 2:</strong> Also, have you come across any tools that provides analysis (table/column count, patch between revisions, etc.) on .sql files (DDL scripts). All the tools that I found require the .sql files to be loaded into a database before doing any analysis on them. </p> <p>For both the questions, MySQL or Postgres is preferred as the database.</p> <p>I aprreciate any reponse from fellow members of this community.</p> <p>Thank you,</p> <p>Venkatesh Mandalapa</p>
<p><a href="http://www.databaseanswers.org/" rel="noreferrer">http://www.databaseanswers.org/</a> - contains a number of examples for database schemas.</p>
<p>check out our work on <a href="http://schemaevolution.org" rel="nofollow noreferrer">http://schemaevolution.org</a>, there is some interesting research made at UCLA on schema evolution, we release pre-collected schema evolution histories (from mediawiki, Ensembl Genetic DB and several others), we provide statistical analysis of those cases, and there is also a tool available to automate the process of collection and analysis of the schema evolution histories. </p> <p>bye,</p> <h2>Carlo</h2> <p>Carlo A. Curino, PhD </p> <h2>MIT - CSAIL</h2> <p>The bane of my existence is doing things </p> <h2> I know the computer could do for me.</h2>
37,667
<p>When trying to install Visual Studio 2008 I get the following message straight away: </p> <blockquote> <p>"You must uninstall all pre-release products in a specific order before you can continue with setup."</p> </blockquote> <p></p> <p>And then it gived me <a href="http://www.microsoft.com/express/support/uninstall/" rel="nofollow noreferrer">this link on how to do that</a>.</p> <p>I've been working on this problem for quite some time now, uninstalling the components as best I can (my list did not actually match microsoft's list), and I can find no trace of the beta software of 3.5 framework anywhere.</p> <p>However, I just remembered something I had to "install" to make my AJAX 1.0 continue to work after installing 3.5 beta 2 - a <a href="http://weblogs.asp.net/scottgu/archive/2007/07/26/vs-2008-and-net-3-5-beta-2-released.aspx" rel="nofollow noreferrer"><strong>batch script provided by ScottGu</strong></a>. I don't know enough to understand what it actually does, but maybe this is something I have to undo in order to make the installation work?!</p> <p>I'm looking for a solution to undo what the batch did, and if that doesn't help I need more tips on how to locate what the problem might be, so that I can finally install Visual Studio 2008.</p> <p>The content of the batch from ScottGu:</p> <pre><code>@ECHO OFF ECHO Disabling publisher policy for System.Web.Extensions. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg policy.1.0.System.Web.Extensions.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) ECHO Disabling publisher policy for System.Web.Extensions.Design. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg policy.1.0.System.Web.Extensions.Design.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) :END PAUSE </code></pre>
<p>For me I had to uninstall VSS Report Services for SQL Server. Then uninstall everything SQL Express related, then uninstall Visual Studio. Clean out the registry hive for VS 9.0 and 9.0EXP. THEN it would reinstall. The VS 2008 SP1 RC attempted to update SQL Server Express to 2008 as well. That screwed up a lot of stuff on my box.</p> <p>I have also read about Silverlight tools causing a conflict. If you installed an RC of them - get it out as well.</p> <p>The only thing that batch file is doing is overwriting some policy files from 3.5 back to 1.0. Probably because the VS 2008 installer doesn't expect them to have already been updated.</p> <p>And hopefully this goes back to the old adage - never install Microsoft prerelease on anything by a VM.... (I never do this though)</p>
<p>Maybe there is something here that will help you: <a href="http://www.brokenwire.net/bw/Programming/58/visual-studio-2008-installfest-problems-with-the-visual-web-developer" rel="nofollow noreferrer">Visual Studio 2008 InstallFest</a></p> <p>I wrote that when having trouble installing Visual Studio 2008 on a "dirty" pc.</p>
24,550
<p>How do I select the unique elements from the list <code>{0, 1, 2, 2, 2, 3, 4, 4, 5}</code> so that I get <code>{0, 1, 3, 5}</code>, effectively removing <em>all instances of</em> the repeated elements <code>{2, 4}</code>?</p>
<pre><code>var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 }; var uniqueNumbers = from n in numbers group n by n into nGroup where nGroup.Count() == 1 select nGroup.Key; // { 0, 1, 3, 5 } </code></pre>
<p>In .Net 2.0 I`m pretty sure about this solution:</p> <pre><code>public IEnumerable&lt;T&gt; Distinct&lt;T&gt;(IEnumerable&lt;T&gt; source) { List&lt;T&gt; uniques = new List&lt;T&gt;(); foreach (T item in source) { if (!uniques.Contains(item)) uniques.Add(item); } return uniques; } </code></pre>
37,296
<p>How can I get the (physical) installed path of a DLL that is (may be) registered in GAC? This DLL is a control that may be hosted in things other than a .Net app (including IDEs other than VS...).</p> <p>When I use System.Reflection.Assembly.GetExecutingAssembly().Location, it gives path of GAC folder in winnt\system32 - or in Design mode in VS gives the path to the VS IDE.</p> <p>I need to get the path where physical dll is actually installed - or the bin/debug or (release) folder for VS. </p> <p>Reason is that there is an XML file I need to get at in this folder, with config setting that are used both in design mode and at runtime.</p> <p>Or how is it best to handle this scenario? I have a dubious network location I am using for design mode at the moment... (Don't think that ApplicationData folder is going to cut it (but have the .Net version soved as that's installed via ClickOnce ans can use the Clickonce Data folder) )</p>
<p>If something gets put in the GAC, it actually gets copied into a spot under %WINDIR%\assembly, like</p> <pre><code>C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll </code></pre> <p>I assume you're seeing something like that when you check the Location of the assembly in question when it's installed in the GAC. That's actually correct. (In .NET 1.1 there was a "Codebase" listed when you looked at a GAC assembly's properties, but that was only to show you where the original file was located when you ran gacutil - it didn't actually indicate what would be loaded.) You can read <a href="http://www.grimes.nildram.co.uk/workshops/fusWSFour.htm" rel="noreferrer">more about that here</a>.</p> <p>Long story short, you may not be able to do what you want to do. Instead of looking in relation to some assembly that's being loaded (<code>Assembly.GetExecutingAssembly()</code>), you might want to switch the behavior to look relative to the primary application assembly (<code>Assembly.GetEntryAssembly()</code>) or put the file in some well-known location, possibly based on an environment variable that gets set.</p>
<p>Do you have the option of embedding a resource to this DLL? That way, it doesn't really matter where the DLL is located on disk, because the XML file will follow it. You can then do something like this:</p> <pre><code>Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProject.MyXmlFile.xml"); XmlDocument d = new XmlDocument(); using (StreamReader r = new StreamReader(s)) { d.LoadXml(r.ReadToEnd()); } </code></pre>
49,439
<p>Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like</p> <pre><code>update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120) </code></pre>
<p>For the entire Table then:</p> <pre><code>Update Computers Set Total_Disk_Space = Total_Disk_Space + 120; </code></pre> <p>If, you only want to update certain ones, then you'd need filters, for example:</p> <pre><code>Update Computers Set Total_Disk_Space = Total_Disk_Space + 120 Where PurchaseDate BETWEEN '1/1/2008' AND GETDATE(); </code></pre>
<p>Yeah:</p> <pre><code>update computers set total_disk_space = total_disk_space + 120; </code></pre>
10,466
<p>I've got a solution which I setup / cleanup using batch files ... - there are a pair of MSMQ ports, send and receive, with another application on the end of the queues</p> <p>I'm finding I can't properly stop the orchestration in the batch file ... the error is the send port is unenlisted - I'm using the StopOrch.vbs script from the SDK samples</p> <p>But I can go into BizTalk Admin Console and manually stop the orchestration with Full Terminate Ok</p> <p>The setup / cleanup works Ok if I don't actually push any messages down the MSMQ queues</p>
<p>By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.</p> <pre><code>package { import mx.controls.ComboBox; import mx.core.UIComponent; public class ComboBox2 extends ComboBox { public function ComboBox2() { super(); } protected var textInputReplacement:UIComponent; override protected function createChildren():void { super.createChildren(); if ( !textInputReplacement ) { if ( itemRenderer != null ) { //remove the default textInput removeChild(textInput); //create a new itemRenderer to use in place of the text input textInputReplacement = itemRenderer.newInstance(); addChild(textInputReplacement); } } } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if ( textInputReplacement ) { textInputReplacement.width = unscaledWidth; textInputReplacement.height = unscaledHeight; } } } } </code></pre>
<p>Thank you maclema and Maurits de Boer. I added a couple more things to this class to make it fit my needs:</p> <ul> <li><p>I overrode set itemRenderer so that this will work if you set the itemRenderer through AS instead of mxml. I moved the text input replacement code to its own function to avoid duplication.</p></li> <li><p>I added setters for 'increaseW' and 'increaseH' to resize the combobox if necessary because my renderer was too big for the combobox at first. </p></li> <li><p>I subtracted 25 from the textInputReplacement width so it doesn't ever overlap the dropdown button... may be better to use something more proportional to accommodate different skins and such.</p></li> </ul> <p>Code:</p> <pre><code>package { import mx.binding.utils.BindingUtils; import mx.controls.ComboBox; import mx.core.IFactory; import mx.core.UIComponent; public class ComboBox2 extends ComboBox { public function ComboBox2() { super(); } protected var textInputReplacement:UIComponent; private var _increaseW:Number = 0; private var _increaseH:Number = 0; public function set increaseW(val:Number):void { _increaseW = val; } public function set increaseH(val:Number):void { _increaseH = val; } override public function set itemRenderer(value:IFactory):void { super.itemRenderer = value; replaceTextInput(); } override protected function createChildren():void { super.createChildren(); replaceTextInput(); } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { unscaledWidth += _increaseW; unscaledHeight += _increaseH; super.updateDisplayList(unscaledWidth, unscaledHeight); if ( textInputReplacement ) { textInputReplacement.width = unscaledWidth - 25; textInputReplacement.height = unscaledHeight; } } protected function replaceTextInput():void { if ( !textInputReplacement ) { if ( this.itemRenderer != null ) { //remove the default textInput removeChild(textInput); //create a new itemRenderer to use in place of the text input textInputReplacement = this.itemRenderer.newInstance(); addChild(textInputReplacement); // ADD THIS BINDING: // Bind the data of the textInputReplacement to the selected item BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true); addChild(textInputReplacement); } } } } } </code></pre>
33,898
<p>Given an ordered set of 2D pixel locations (adjacent or adjacent-diagonal) that form a complete path with no repeats, how do I determine the Greatest Linear Dimension of the polygon whose perimeter is that set of pixels? (where the GLD is the greatest linear distance of any pair of points in the set)</p> <p>For my purposes, the obvious O(n^2) solution is probably not fast enough for figures of thousands of points. Are there good heuristics or lookup methods that bring the time complexity nearer to O(n) or O(log(n))?</p>
<p>An easy way is to first find the convex hull of the points, which can be done in O(n log n) time in many ways. [I like <a href="http://en.wikipedia.org/wiki/Graham_scan" rel="noreferrer">Graham scan</a> (see <a href="http://www.cs.princeton.edu/courses/archive/fall08/cos226/demo/ah/GrahamScan.html" rel="noreferrer">animation</a>), but the <a href="http://www.cse.unsw.edu.au/~lambert/java/3d/incremental.html" rel="noreferrer">incremental</a> algorithm is also popular, as are <a href="http://www.cse.unsw.edu.au/~lambert/java/3d/hull.html" rel="noreferrer">others</a>, although some take <a href="http://www.algorithmist.com/index.php/Convex_Hull" rel="noreferrer">more time</a>.]</p> <p>Then you can find the farthest pair (the diameter) by starting with any two points (say x and y) on the convex hull, moving y clockwise until it is furthest from x, then moving x, moving y again, etc. You can prove that this whole thing takes only O(n) time (amortized). So it's O(n log n)+O(n)=O(n log n) in all, and possibly O(nh) if you use gift-wrapping as your convex hull algorithm instead. This idea is called <a href="http://en.wikipedia.org/wiki/Rotating_calipers" rel="noreferrer">rotating calipers</a>, as you mentioned.</p> <p>Here is <a href="http://code.activestate.com/recipes/117225/" rel="noreferrer">code by David Eppstein</a> (computational geometry researcher; see also his <a href="http://www.ics.uci.edu/~eppstein/PADS/" rel="noreferrer">Python Algorithms and Data Structures</a> for future reference).</p> <p>All this is not very hard to code (should be a hundred lines at most; is less than 50 in the Python code above), but before you do that -- you should first consider whether you really need it. If, as you say, you have only "thousands of points", then the trivial O(n^2) algorithm (that compares all pairs) will be run in less than a second in any reasonable programming language. Even with a million points it shouldn't take more than an hour. :-)</p> <p>You should pick the <em>simplest</em> algorithm that works.</p>
<p>You could maybe draw a circle that was bigger than the polygon and slowly shrink it, checking if youve intersected any points yet. Then your diameter is the number youre looking for. Not sure if this is a good method, it sounds somewhere between O(n) and O(n^2)</p>
41,680
<p>Okay still fighting with doing some SqlCacheDependecy in my Asp.net MVC application</p> <p>I got this piece of code from Microsoft to cache LINQtoSQL, basically what it does is it gets the SqlCommand text from the LINQ query and executes that via the System.Data.SqlClient.SqlCommand which SqlDependecy needs...</p> <p>However there is one slight problem with this and that is whenever you do a where clause in LINQ the SQL generated is like so</p> <pre><code>SELECT [t0].[MemberID], [t0].[Aspnetusername], [t0].[Aspnetpassword], [t0].[EmailAddr], [t0].[DateCreated], [t0].[Location], [t0].[DaimokuGoal], [t0].[PreviewImageID], [t0].[LastDaimoku] AS [LastDaimoku], [t0].[LastNotefied] AS [LastNotefied], [t0].[LastActivityDate] AS [LastActivityDate], [t0].[IsActivated] FROM [dbo].[Members] AS [t0] INNER JOIN [dbo].[MemberStats] AS [t1] ON [t0].[MemberID] = [t1].[MemberID] WHERE [t1].[TotalDeterminations] &gt; @p0 </code></pre> <p>Notice the where [t1].[TotalDeterminations] > @p0, the SqlCommand yells at me because it wants me to declare a scalar variable of @p0... which obviously I can't</p> <p>So how the heck does Microsoft which provides this code to cache Linq queries expect people to use where clauses? Anyone have any ideas around this?</p> <p><strong>Edit</strong> Plus how the heck does SQL know what @p is anyhow when just executing the LINQ like normal the above query is whats getting passed in no matter what to the database?</p>
<p><code>@something</code> is a SQL Parameter, which .NET handles by adding to the SqlParameter collection of the SqlCommand object.</p> <p>You can create parameters with any name, Linq to SQL just generates them named <code>p#</code>, where <code>#</code> represents its position on the collection.</p>
<p>Why can't you just add SqlParameter objects to the Parameters collection of SqlCommand object before adding them to the SqlDependecy?</p>
30,469
<p>I would like to learn the best practices to employ when creating a database driven web-application. I prefer to learn from examples. What is a good sample application that I can download and run to learn this:</p> <p>I am looking for:</p> <ol> <li>Should be written in C# (preferably)</li> <li>Should contain a complex database design (parent child relations, etc.)</li> <li>Should implement the best practices for an ASP.net website as well as for database design.</li> <li>Preferably uses Oracle.</li> </ol>
<p>If you don't want to worry about writing your <a href="http://en.wikipedia.org/wiki/Data_access_layer" rel="nofollow noreferrer">DAL</a> (Data Access Layer), then I suggest looking at <a href="http://www.nhibernate.org" rel="nofollow noreferrer">Nhibernate</a>. There are samples with it and ASP.NET <a href="http://www.beansoftware.com/asp.net-tutorials/nhibernate-log4net.aspx" rel="nofollow noreferrer">here</a>, <a href="http://www.hibernate.org/363.html" rel="nofollow noreferrer">here</a>, and <a href="https://stackoverflow.com/questions/259409/database-and-orm-choice-for-an-small-medium-size-net-application#259551">here</a>. Here's a <a href="http://www.oracle.com/technology/tech/windows/odpnet/index.html" rel="nofollow noreferrer">sample with just Oracle</a> and ASP.NET.</p> <p>If you are looking for just sample ASP.NET Applications without an Object Relational Mapper like NHibernate, try <a href="http://www.asp.net/Learn/data-access/" rel="nofollow noreferrer">this</a>.</p> <p>Also, on a higher level, you're looking for an <a href="http://www.developerfusion.com/article/3058/boosting-your-net-application-performance/2/" rel="nofollow noreferrer">N-Tier ASP.NET application design</a>. There are good tutorials on that <a href="http://www.c-sharpcorner.com/UploadFile/tavanover/NTierDevelopmentWithNetP311282005073236AM/NTierDevelopmentWithNetP3.aspx" rel="nofollow noreferrer">here</a>, <a href="http://www.developerfusion.com/article/3058/boosting-your-net-application-performance/2/" rel="nofollow noreferrer">here</a>, and <a href="http://msdn.microsoft.com/en-us/library/ms978384.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>In my opinion best practice would dictate the following:</p> <ol> <li>Use an ORM for your data access layer. This should ideally be in a a separate project so it can be changed if need be.</li> <li>Should use MVC. If you use WebForms then you will surely find that your business logic and the display logic gets mixed together.</li> <li>Learn database design separate and apart from learning to write code.</li> <li>Keep reviewing object oriented design fundamentals.</li> <li>Take time to learn design patterns. Not to become a slave to "The Gang of Four" but so that you can take advantage of proven patterns to solve common problems.</li> </ol>
46,225
<p>I've tried my best and cannot figure out what happened here. It worked fine in Delphi 4. After upgrading to Delphi 2009, I don't know if this is the way it is supposed to work, or if it's a problem:</p> <p>This is what my program's menu looks like in Design Mode under Delphi 2009:</p> <p><a href="https://i.stack.imgur.com/lg57M.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lg57M.gif" alt="enter image description here"></a></p> <p>Notice that every word in the Main Menu and the File submenu have one letter underlined. It is supposed to be like this. This underlined letter is called the Accelerator Key and is standard in Windows applications so that you can use the Alt-key and that letter to quickly select the menu item and then submenu item with the keyboard rather than with your mouse.</p> <p>You get them this way by using the "&amp;" character as part of the caption of the item, for example: Save &amp;As...</p> <p>When I run my application, and use the mouse to open the File menu, it looks like this:</p> <p><a href="https://i.stack.imgur.com/zpw14.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpw14.gif" alt="enter image description here"></a></p> <p>The characters are underlined in the main menu, but are not underlined in the File menu.</p> <p>If instead, I use the Alt-F key to open up the File submenu, then it looks correct like this:</p> <p><a href="https://i.stack.imgur.com/Hxwn0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hxwn0.gif" alt="enter image description here"></a></p> <p>and all the Accelerator Key letters are properly underlined.</p> <p>I've played with the AutoHotKeys option but that's not the problem.</p> <p>Has someone encountered this problem before? Is the example in the 2nd image correct behavior that I don't know of? Or is there some option or coding mistake that I might have missed?</p> <hr> <p>Nov 2009 (one year later): mghie seems to have got to the root of this and figured out the problem. See his accepted answer below.</p>
<p>There is a standard Windows setting (under display properties) to normally hide those accelerators unless the Alt key is held down. That would explain why opening the menu with Alt+F10 shows them for you. Maybe that's the cause?</p> <p>[EDIT]: No, it's not. I just tried, and a simple TForm with a menu item shows the accelerator, but as soon as I add a TImageList and set the ImageIndex of the single menu item, or simply set OwnerDraw to true, then the accelerator underline disappears. I guess that really is a bug in the VCL.</p> <p>BTW, this is on Windows XP.</p> <p><strong>Workaround:</strong></p> <p>I have debugged this using Delphi 2009 on Windows XP 64, and the root cause for the missing accelerators seems to be that Windows sends <code>WM_DRAWITEM</code> messages with the <code>ODS_NOACCEL</code> flag set, which it shouldn't if the system is set to show accelerators at all times. So you could say that it is not a VCL bug, but a Windows problem which the VCL does not work around.</p> <p>However, you can work around it in your own code, you just need to reset the flag before passing the message to the VCL. Override the window proc</p> <pre><code>protected procedure WndProc(var Message: TMessage); override; </code></pre> <p>like so:</p> <pre><code>procedure TYourForm.WndProc(var Message: TMessage); const ODS_NOACCEL = $100; var pDIS: PDrawItemStruct; ShowAccel: BOOL; begin if (Message.Msg = WM_DRAWITEM) then begin pDIS := PDrawItemStruct(Message.LParam); if (pDIS^.CtlType = ODT_MENU) and SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, @ShowAccel, 0) then begin if ShowAccel then pDIS^.itemState := pDIS^.itemState and not ODS_NOACCEL; end; end; inherited; end; </code></pre> <p>This is demonstration code only, you should not call <code>SystemParametersInfo()</code> every time a <code>WM_DRAWITEM</code> message is received, but once at program start, and then every time your program receives a <code>WM_SETTINGCHANGE</code> message. </p>
<p>As Jim McKeeth noted above (correctly), this is "by design" behavior. If the menus are triggered through keyboard action the accelerators should be shown, but if triggered by the mouse the accelerators are intentionally not shown. </p> <p>I have my XP configured to show accelerators at all times, but a quick test with that option changed confirms that the menus should not show underlines either (Visual Studio responded as I expected, no underlines when using the mouse). However, Microsoft Office ignores this setting and always shows the underlines. So it looks like a bug in how the menus are drawn in Delphi (I don't have any experience with Delphi myself). </p> <p>I found the option for Vista as well: <a href="http://www.vistax64.com/vista-general/42125-always-show-menu-underline-keyboard-accelerators.html" rel="nofollow noreferrer">http://www.vistax64.com/vista-general/42125-always-show-menu-underline-keyboard-accelerators.html</a></p> <blockquote> <p>You can turn this on in the new Ease of Access Center (go to Control Panel, click Ease of Access and then click Ease of Access Center). In the Ease of Access Center, click Make the keyboard easier to use, and at the very bottom select the Underline keyboard shortcuts and access keys check box.</p> </blockquote> <p>While doing further research I found this related bug on Delphi forums: <a href="http://qc.codegear.com/wc/qcmain.aspx?d=37403" rel="nofollow noreferrer">http://qc.codegear.com/wc/qcmain.aspx?d=37403</a> </p> <p>It looks like in your case the child windows (the drawn menus) aren't getting or aren't handling WM_UIUPDATESTATE message from their parent window, which is what causes the redraw with accelerators.</p>
35,432
<p>I make a request to an xml web service, and get back a response. This response, being a stream, is then saved to a string. The problem is, the response is full of tags, CDATA, etc (as you would expect). There is no line breaking either, as to be expected.</p> <p>I want to take this string, which represents an xml document, and strip it of all its tags but keep the actual values, and also, make sure that each record is in one line, so:</p> <pre><code>&lt;Record&gt; &lt;name&gt;adam&lt;/name&gt; &lt;telephoneno&gt;000&lt;/telephonenumber&gt; &lt;/Record&gt; &lt;Record&gt; &lt;name&gt;mike&lt;/name&gt; &lt;telephoneno&gt;001&lt;/telephonenumber&gt; &lt;/Record&gt; </code></pre> <p>Will be transformed to:</p> <pre><code>adam 000 mike 001 </code></pre> <p>Headings is an easy issue, but how could I achieve this? I've tried datatables and datasets but I don't think they have great support for achieving what I am trying to do.</p>
<p>This is exactly what XSLT is for! It transforms XML files into a different output. In your case, you could use a relatively simple XSL transformation to output a list.</p> <p>This might do it:</p> <p>records.xml:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;?xml-stylesheet type="text/xsl" href="style.xsl"?&gt; &lt;Records&gt; &lt;Record&gt; &lt;name&gt;adam&lt;/name&gt; &lt;telephonenumber&gt;000&lt;/telephonenumber&gt; &lt;/Record&gt; &lt;Record&gt; &lt;name&gt;mike&lt;/name&gt; &lt;telephonenumber&gt;001&lt;/telephonenumber&gt; &lt;/Record&gt; &lt;/Records&gt; </code></pre> <p>style.xsl</p> <pre><code>&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"&gt; &lt;xsl:output method="text" omit-xml-declaration="yes" indent="no"/&gt; &lt;xsl:template match="Record"&gt; &lt;xsl:value-of select="name"/&gt;&lt;xsl:text&gt; &lt;/xsl:text&gt;&lt;xsl:value-of select="telephonenumber"/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I tested it with <a href="http://www.netcrucible.com/xslt/xslt-tool.htm" rel="nofollow noreferrer">this tool</a> and it works.</p>
<p>Michael Haren's XSLT response is the best answer.</p> <p>But alternatively if you're not actually wanting the response as XML you can return whatever it is that you DO desire from the web service (provided it's yours, rather than a third party service). </p> <p>There's no rule that says a web service must return XML. Just make sure to serve the appropriate MIME-Type.</p>
28,594
<p>I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.</p> <p>What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..</p>
<p>If you have .NET 3.5 you could use LINQ's Reverse?</p> <pre><code>foreach(var item in obEvtArgs.NewItems.Reverse()) { ... } </code></pre> <p>(Assuming you're talking about the generic IList)</p>
<p>NewItems is my List here... This is a bit clunky though. </p> <pre><code>for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper &gt;= 0; iLooper--) { GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos)); } </code></pre>
11,633
<p>I have the following code:</p> <pre><code>class IncidentTag: def __init__(self,tag): self.tag = tag def equals(self,obj): return self.tag.equals(obj.tag) def hashCode(self): return self.tag.hashCode() from java.lang import String from java.util import HashMap from java.util import HashSet tag1 = IncidentTag(String("email")) tag1copy = IncidentTag(String("email")) tag2 = IncidentTag(String("notemail")) print tag1.equals(tag1copy) print tag2.equals(tag2) print "Now with HashSet:" hSet = HashSet() hSet.add(tag1) hSet.add(tag2) print hSet.contains(tag1) print hSet.contains(tag2) print hSet.contains(tag1copy) </code></pre> <p>The output is: 1 1 Now with HashSet: 1 1 0</p> <p>However, I would have expected the last line to be <code>true</code>(1) as well. Is there something obvious that I am missing.</p> <p>(yes, I know that my <code>equals</code> method and <code>hashcode</code> methods do not take some issues into account... they are deliberately simple, but do let me know if the issues there are causing this problem.)</p>
<p>You shouldn't implemented the Java-Style equals and hashCode method, but instead the Python equivaltents <code>__eq__</code> and <code>__hash__</code>. Adding</p> <pre><code>def __hash__(self): return self.hashCode() def __eq__(self, o): return self.equals(o) </code></pre> <p>helps. These python methods are - as far as I know - dynamically bound to hashCode and equals() by Jython. This ensures that you can put Python classes into Java's collections.</p> <p>Now the code prints five "1".</p>
<p>I don't know Python, but it sure looks like the underlying Java object's equals() and hashcode() aren't honoring the required contract.</p> <ul> <li>Two objects if equals() must return the same hashcode(). </li> </ul> <p>It looks like that is violated. HashSets are first going to use the hashcode in the lookup to get the list the matching object would be in, then go through the list to find the one that's equal. If your hashcode isn't honoring the contract and they're returning different hashcodes, then it won't find it in the hashset even if they were equals() comparable.</p> <p>The default Java Object.hashcode() isn't going to return the same hashcode for 2 objects. You've got to override it.</p>
28,542
<p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p> <p>Is there an analogous way to do this in Python?</p>
<p>Yes, there is. The Python way is even better.</p> <p>There are three possibilities:</p> <p><strong>1) Like File.listFiles():</strong></p> <p>Python has the function os.listdir(path). It works like the Java method.</p> <p><strong>2) pathname pattern expansion with glob:</strong></p> <p>The module glob contains functions to list files on the file system using Unix shell like pattern, e.g. <code><pre> files = glob.glob('/usr/joe/*.gif') </pre></code></p> <p><strong>3) File Traversal with walk:</strong></p> <p>Really nice is the os.walk function of Python.</p> <p>The walk method returns a generation function that recursively list all directories and files below a given starting path.</p> <p>An Example: <code><pre> import os from os.path import join for root, dirs, files in os.walk('/usr'): print "Current directory", root print "Sub directories", dirs print "Files", files </pre></code> You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe".</p> <p>listdir and walk are documented <a href="http://docs.python.org/lib/os-file-dir.html" rel="noreferrer">here</a>. glob is documented <a href="http://docs.python.org/lib/module-glob.html" rel="noreferrer">here</a>.</p>
<p>Seeing as i have programmed in python for a long time, i have many times used the os module and made my own function to print all files in a directory.</p> <p>The code for the function:</p> <pre><code>import os def PrintFiles(direc): files = os.listdir(direc) for x in range(len(files)): print("File no. "+str(x+1)+": "+files[x]) PrintFiles(direc) </code></pre>
17,013
<p>What is the best way to disable <kbd>Alt</kbd> + <kbd>F4</kbd> in a c# win form to prevent the user from closing the form?</p> <p>I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.</p>
<p>This does the job:</p> <pre><code>private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; } </code></pre> <p>Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form_closing event before closing the form:</p> <pre><code>this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Close(); </code></pre>
<p>Hide close button on form by using the following in constructor of the form:</p> <pre><code>this.ControlBox = false; </code></pre>
3,573
<p>While writing a file using ofstream, how do I know when the file's size has reached the OS' maximum file size - more specifically linux's maximum file size - ??</p>
<p>First off, maximum file size is a filesystem limit, not an Operating System limit. It will even vary for a particular filesystem, based on how the filesystem was formatted. </p> <p>As for how you'd figure out that you'd reached the limit, your code will likely throw an exception when that happens, which you'll then be able to relate back to the OS error codes.</p> <p>Note that the actual limit is <a href="http://en.wikipedia.org/wiki/Ext2#File_system_limits" rel="noreferrer">pretty darn big</a> for a "typical" EXT2 filesystem - in the Terabytes. You'll likely never reach it, in practice. If you seriously are accumulating Terabytes of data, you might want to consider whether there's a more reasonable way to store it, rather than a single gigantic file.</p>
<p>I think (not 100% sure) that you'd just have to compare the stream's current size after a write to whatever the OS's max file size is. Otherwise I'm guessing the underlying implementation will just let you keep writing until the actual OS io calls fail.</p>
16,286
<p>I am looking for a PHP blog engine which needs to be easy to redesign (CSS, HTML). It also needs to be free and have simple user interface so that the client doesn't struggle to add posts. Any suggestions?</p>
<p><a href="http://www.wordpress.org" rel="noreferrer">Wordpress</a> - I keep trying other blogs and I keep going back to wordpress. It's definitely the easiest I've used for customizing templates, and the admin UI is very nice.</p>
<p>Well, it's hard not to suggest Wordpress. Redesigning it isn't too terribly difficult, a monkey could use it, the admin interface is simple and easy on the eyes, and it has great community support. I'd recommend using the Automatic Upgrade plugin with it as well, so that your customer can always stay up to date as well (for security reasons).</p>
11,612
<p>I am using an Infragistics UltraGrid in a WinForms application.<br> Which event is raised on "check change" of checkbox in Infragistics UltraGrid?</p>
<p>The AfterUpdate event of the checkbox is what you'll want to use.</p> <p>If you're not able to trigger it, though, try adding this as well:</p> <pre><code>Private Sub YourGridcontrol_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseDown YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode) End Sub Private Sub YourGridcontrol_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseUp YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode) End Sub </code></pre> <p>By default, just toggling the checkbox doesn't seem to trigger an Update. By making it enter/exit edit mode, the AfterUpdate should work as you want.</p> <p>UPDATE: Or, like Vincent suggested, doing the PerformAction on the CellChange event should work, too. The gist is the same.</p>
<p>The AfterUpdate event of the checkbox is what you'll want to use.</p> <p>If you're not able to trigger it, though, try adding this as well:</p> <pre><code>Private Sub YourGridcontrol_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseDown YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode) End Sub Private Sub YourGridcontrol_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseUp YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode) End Sub </code></pre> <p>By default, just toggling the checkbox doesn't seem to trigger an Update. By making it enter/exit edit mode, the AfterUpdate should work as you want.</p> <p>UPDATE: Or, like Vincent suggested, doing the PerformAction on the CellChange event should work, too. The gist is the same.</p>
40,556
<p>Is it possible to save a form in VBA as .exe file and then run it.</p>
<p>No, not natively.</p> <p>There are some ways to emulate an EXE:</p> <ul> <li><strong>Excel</strong>: 3rd party tool that claims to be able to compile an workbook to an EXE: <a href="http://www.soft14.com/Business_and_Finance/Spreadsheets/DoneEx_XCell_Compiler_11134_Review.html" rel="noreferrer">DoneEx XCell Compiler</a>. You can also create an automatic marco, Auto_Open, to run when the workbook is opened.</li> <li><strong>Access</strong>: Microsoft used to have a way of delivering an Access database as an executable (the name of the tool escapes me) so you could deploy your database to desktops that didn't have Access installed, but I don't think they offer this anymore. You could convert you MDB to an MDE and set the startup properties to hide the database window and menus and such to emulate an EXE, but your users will need to have Access installed.</li> <li><strong>Word</strong>: You can pass the <code>/m</code> switch to Word on startup with the name of a macro to run.</li> </ul>
<p>No. VBA is an addon to applications to support "scripting" in the form of VB. So unless your application supports a way to save the internal script as en external EXE, you are out of luck.</p>
44,233
<p>Can it be known in general whether or not placing a case within a for loop will result in bad assembly. I'm interested mainly in Delphi, but this is an interesting programming question, both in terms of style and performance. </p> <p>Here are my codez!</p> <pre> case ResultList.CompareType of TextCompareType: begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; end; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; </pre> <p>alternatively I could write </p> <pre> begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin case ResultList.CompareType of TextCompareType: begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; end; end; end; </pre> <p>I don't like the second way because I'm asking a question I know the answer to in a for loop and I don't like the first way because I'm repeating the code I use to figure out which of my objects contain valid information. </p> <p>Perhaps there is a design pattern someone could suggest that would circumvent this all together.</p>
<p>Why not using subclasses? </p> <p>This saves the use of the case statement.</p> <pre><code>TComparer = class protected function Compare(const AItem1, AItem2: TItem): Boolean; virtual; abstract; public procedure DoCompare(ResultList: ...); end; TTextComparer = class (TComparer) protected function Compare(const AItem1, AItem2: TItem): Boolean; override; end; procedure TComparer.DoCompare(ResultList: ...); var LastGoodIndex, I : Integer; begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if Compare(ResultList[LastGoodIndex], ResultList[I]) then Result := TrueEval else Result := FalseEval; end; end; function TTextComparer.Compare(const AItem1, AItem2: TItem): Boolean; begin Result := StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) &gt; 0) end; </code></pre>
<p>I suspect that it's more efficient to use a lambda or closure or even just a function reference. My Pascal's rusted right out, so my example is perl:</p> <pre><code>my %type = ( TextCompareType =&gt; sub { $_[0] lt $_[1] }, NumericCompareType =&gt; sub { $_[0] &lt; $_[1] }, DateCompareType =&gt; sub { ... }, BooleanCompareType =&gt; sub { ... }, ); for (my $i = 1; $i &lt;= $#list; ++$i) { if ( $type{$ResultList{CompareType}}-&gt;($list[$i-1], $list[$i]) ) { $result = 1; # ? } } </code></pre> <p>I'm not really following most of your code, but I think I've captured the essence of the question without fully capturing the code.</p> <p>Another solution is to create comparator objects as subclasses off a base comparator class, and then call the object's compare function, but you do mention trying to stay structured instead of OO.</p>
30,343
<p>I'm reading up on event-driven design. I am having trouble getting my head around some of it in practice. I'm considering using this for a windows service that monitors, parses, and handles information coming from a 3rd party TCP stream. Is the following a decent approach, or am I missing something? </p> <p>My plan is to have a the main service be simply a container for events:</p> <pre><code>public class MyService { public void RegisterAgent(ServiceAgent agent) { Log("Initializing agent " + agent); agent.Initialize(this); Log("Done intializing agent " + agent); } public void Log(string messageText) { OnSimpleLogEventLogged(this, new SimpleLogEventArgs(messageText)); } protected void Raise&lt;T&gt;(EventHandler&lt;T&gt; eventHandler, object sender, T args) where T : EventArgs { var handler = eventHandler; if (handler == null) return; handler(sender, args); } public event EventHandler&lt;SimpleLogEventArgs&gt; SimpleLogEventLogged; protected void OnSimpleLogEventLogged(object sender, SimpleLogEventArgs args) { Raise(SimpleLogEventLogged, sender, args); } public event EventHandler&lt;TextRecievedEventArgs &gt; TextRecieved; public void OnTextRecieved(object sender, TextRecievedEventArgs args) { Raise(TextRecieved, sender, args); } public event EventHandler&lt;TextParsedEventArgs&gt; TextParsed; public void OnTextParsed(object sender, TextParsedEventArgs args) { Raise(TextParsed, sender, args); } ... } </code></pre> <p>Then, using MEF or similar, I'll register "ServiceAgent" instances, which simply handle and/or raise events, optionally doing so on a background thread. For example:</p> <pre><code>public class TextParsingAgent : ServiceAgent { public override void Initialize(MyService service) { service.TextRecieved += TextRecieved; base.Initialize(service); } void TextRecieved(object sender, TextRecievedEventArgs e) { ThreadPool.QueueUserWorkItem(TextRecievedAsync, e); } private void TextRecieved(object state) { var e = (TextRecievedEventArgs)state; //TODO:Parse text into something meaningful and store in textParseEventArgs service.OnTextParsed(textParseEventArgs); } } </code></pre>
<p>You could use <code>libphonenumber</code> from Google. Here's a blog post: </p> <p><a href="http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber" rel="noreferrer">http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber</a></p> <p>Parsing numbers is as easy as installing the <a href="http://nuget.org/packages/libphonenumber-csharp" rel="noreferrer">NuGet package</a> and then doing this:</p> <pre><code>var util = PhoneNumberUtil.GetInstance(); var number = util.Parse("555-555-5555", "US"); </code></pre> <p>You can then format the number like this:</p> <pre><code>util.Format(number, PhoneNumberFormat.E164); </code></pre> <p><code>libphonenumber</code> supports several formats other than E.164.</p>
<p>What you need is list of all country codes and start matching your string first few characters against list of country codes to make sure it's correct then for the rest of the number, make sure it's all digits and of proper length which usually varies from 5-10 digits.</p> <p>To achieve checking against country codes, install <a href="https://github.com/RobThree/NGeoNames" rel="nofollow">NGeoNames nuget</a> which uses website <a href="http://www.geonames.org" rel="nofollow">www.geonames.org</a> to get list of all country codes to use to match against them.</p>
32,343
<p>When you are somewhere between version 1 and version 2, what do you do to maintain your software?</p> <p>The terms Patch, Hotfix, Maintenance Release, Service Pack, and others are all blurry from my point of view, with different definitions depending on who you talk to.</p> <p>What do you call your incremental maintenance efforts between releases?</p>
<p>When I hear those terms this is what comes to mind:</p> <ul> <li>Patch - Publicly released update to fix a known bug/issue </li> <li>Hotfix - update to fix a very specific issue, not always publicly released</li> <li>Maintenance Release - Incremental update between service packs or software versions to fix multiple outstanding issues</li> <li>Service Pack - Large Update that fixes many outstanding issues, normally includes all Patches, Hotfixes, Maintenance releases that predate the service pack</li> </ul> <p>That being said that isn't how we do updates at all. We just increment the version and/or build number (which is based on the date) and just call it an "Update". For most software I find that easier, you can easily see that one computer is running 1.1.50 vs 1.2.25 and know which is newer.</p>
<p>I'd like to point to <a href="http://semver.org/" rel="noreferrer">http://semver.org/</a> for an attempt to define version numbers in sane manner, and the definitions given there actually fit closely to how I use version numbers (or how I wish I used them :))</p> <p>As for the term definitions, I find patch and hotfix very similar, except "hotfix" is usually not broadcast if done to a service. </p> <p>Maintenance Release and Service Pack fit fairly closely to the two denominations of version numbers. if you have a version number structure like X.Y.Z, Maintenance Release would be the Z, Service Pack would be the Y. I've really only heard these terms in big, corporate products, though. I'm more acquainted with the minor/mayor version terms.</p> <p>Of course, every shop has their own use of the terms, and it depends on which type of user you're targeting. For end-users of MMOs, for instance, every update is a "patch" because the user has to "patch their client" to apply it, while for end-users of more common software, you often just have the term "update" and "new version" (new mayor version).</p>
33,830
<p>In a PHP project I'm working on we need to create some DAL extensions to support multiple database platforms. The main pitfall we have with this is that different platforms have different syntaxes - notable MySQL and MSSQL are quite different.</p> <h2>What would be the best solution to this?</h2> <p>Here are a couple we've discussed:</p> <p><strong>Class-based SQL building</strong></p> <p>This would involve creating a class that allows you to build SQL querys bit-by-bit. For example:</p> <pre><code>$stmt = new SQL_Stmt('mysql'); $stmt-&gt;set_type('select'); $stmt-&gt;set_columns('*'); $stmt-&gt;set_where(array('id' =&gt; 4)); $stmt-&gt;set_order('id', 'desc'); $stmt-&gt;set_limit(0, 30); $stmt-&gt;exec(); </code></pre> <p>It does involve quite a lot of lines for a single query though.</p> <p><strong>SQL syntax reformatting</strong></p> <p>This option is much cleaner - it would read SQL code and reformat it based on the input and output languages. I can see this being a much slower solution as far as parsing goes however.</p>
<p>If you use prepared statements, SQL injection will be impossible. You should always use prepared statements.</p> <p>Roborg makes an excellent point though about expensive regexes.</p>
<p>If it is anly for the purposes of display this reg expression then most programs simply Html Encode the value and store in the DB and then the Decode on the way out. Again only for Display purposes though, if you need to use the reg exp that is submitted this won't work. </p> <p>Also know there is a method where the person intent on injecting writes out there SQL, Converts it to varbinary and submits the exec command with the base 64 representation of the query which I have been hit with in the past.</p>
26,596
<p>Does anyone think it is possible to build a Google Docs style PDF document viewer, which will convert a document to a format that doesn't require Adobe Reader on the client machine?</p> <p>If so, any references to point to? Either a place that had done it, or an explanation of how to do it.</p>
<p>I've done a lot of research regarding this matter and I hope I can help.</p> <p>Good old Macromedia used to market Flash Paper, which was supposed to be a PDF Adobe Reader killer as it allowed any webmaster to embed and display PDF docs online using Flash. But that was before they sold out to Adobe and Flash Paper was soon put on a shelf and forgotten in favor of Adobe's priorities.</p> <p>However, Today there are a so many ground-breaking alternatives...</p> <p>As a user has mentioned above you can use <a href="http://www.scribd.com" rel="noreferrer">Scribd.com</a> (the wanna-be YouTube for documents). But they're not the only service (and certainly not the ones most ahead of the curve). </p> <p>Here are my two favorites:</p> <ol> <li>Issuu (<a href="http://www.issuu.com" rel="noreferrer">http://www.issuu.com</a>)</li> <li>Mygazines (<a href="http://www.mygazines.com/" rel="noreferrer">http://www.mygazines.com/</a>)</li> </ol> <p>I enjoy Mygazines's flash user interface the most (it's also faster) but it costs $99. It's pretty impressive. Depending on what you want to do that price tag can be worth it.</p> <p>Issuu however, has won me over recently with their Smartlook Platform: <a href="http://issuu.com/smartlook" rel="noreferrer">http://issuu.com/smartlook</a></p> <p>Here's a sample of Smartlook setup on a website: </p> <p><a href="http://www.ismartlook.com/" rel="noreferrer">http://www.ismartlook.com/</a></p> <p>Plus it's completely free, which is nice.</p> <p>A third alternative, which I've considered using myself is this free and open source code made by this guy named samurajdata. He calls it psview (PostScript Viewer). Anyone can download the source code and see it in action here:</p> <p><a href="http://view.samurajdata.se/" rel="noreferrer">http://view.samurajdata.se/</a></p> <p>The converted PDFs losses quality as it converts to image fie, but it's fast and easy to setup. </p> <p>I hope this helps!</p>
<p>Try converting them from <a href="http://www.google.com.au/search?q=PDF+to+Tiff" rel="nofollow noreferrer">PDF to TIFF</a>. Tiff supports multiple pages and is widely supported.</p> <p>If formatting isn't that important, and your PDFs are structured right (ie actually contain text, not images of text), an alternate could be to convert to HTML. The tools from <a href="http://www.aspose.com/" rel="nofollow noreferrer">Aspose</a> are pretty good.</p>
38,104
<p>We have lots of logging calls in our app. Our logger takes a System.Type parameter so it can show which component created the call. Sometimes, when we can be bothered, we do something like:</p> <pre><code>class Foo { private static readonly Type myType = typeof(Foo); void SomeMethod() { Logger.Log(myType, "SomeMethod started..."); } } </code></pre> <p>As this requires getting the Type object only once. However we don't have any actual metrics on this. Anyone got any idea how much this saves over calling this.GetType() each time we log?</p> <p>(I realise I could do the metrics myself with no big problem, but hey, what's StackOverflow for?)</p>
<p>I strongly suspect that GetType() will take significantly less time than any actual logging. Of course, there's the possibility that your call to Logger.Log won't do any actual IO... I still suspect the difference will be irrelevant though.</p> <p>EDIT: Benchmark code is at the bottom. Results:</p> <pre><code>typeof(Test): 2756ms TestType (field): 1175ms test.GetType(): 3734ms </code></pre> <p>That's calling the method 100 <em>million</em> times - the optimisation gains a couple of seconds or so. I suspect the real logging method will have a lot more work to do, and calling that 100 million times will take a lot longer than 4 seconds in total, even if it doesn't write anything out. (I could be wrong, of course - you'd have to try that yourself.)</p> <p>In other words, as normal, I'd go with the most readable code rather than micro-optimising.</p> <pre><code>using System; using System.Diagnostics; using System.Runtime.CompilerServices; class Test { const int Iterations = 100000000; private static readonly Type TestType = typeof(Test); static void Main() { int total = 0; // Make sure it's JIT-compiled Log(typeof(Test)); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i &lt; Iterations; i++) { total += Log(typeof(Test)); } sw.Stop(); Console.WriteLine("typeof(Test): {0}ms", sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); for (int i = 0; i &lt; Iterations; i++) { total += Log(TestType); } sw.Stop(); Console.WriteLine("TestType (field): {0}ms", sw.ElapsedMilliseconds); Test test = new Test(); sw = Stopwatch.StartNew(); for (int i = 0; i &lt; Iterations; i++) { total += Log(test.GetType()); } sw.Stop(); Console.WriteLine("test.GetType(): {0}ms", sw.ElapsedMilliseconds); } // I suspect your real Log method won't be inlined, // so let's mimic that here [MethodImpl(MethodImplOptions.NoInlining)] static int Log(Type type) { return 1; } } </code></pre>
<p>I get very different results.<br/> For this I created a new console app in another project, and used a class with inheritance.<br/> <br/> I created an empty loop to withdraw from the results, for a clean comparison.<br/> I created a const and a static for the cycles (manually switching which to use).<br/> Something very interesting happend.<br/> <br/> When using the const, the empty loop become slow, but the buffered var test becomes slightly faster.<br/> A change that should affect none or all tests, only affect 2.<br/> <br/> Cycles for each test : 100000000<br/> <br/> Using static cycle:<br/></p> <pre> Object.GetType : 1316 TypeOf(Class) : 1589 Type var : 987 Empty Loop : 799 Clean overview: Object.GetType : 517 TypeOf(Class) : 790 Type var : 188 </pre> <p>Using const cycle:</p> <pre> Object.GetType : 1316 TypeOf(Class) : 1583 Type var : 853 Empty Loop : 1061 Clean overview: Object.GetType : 255 TypeOf(Class) : 522 Type var : -208 </pre> <p>I ran these multiple times, and with some small changes, and with 10 times more cycles, to reduce the risk of background processes affecting results. Almost same results as these 2 above.<br/> <br/> It does seem that <code>Object.GetType()</code> is 1.5-2 times as fast as <code>typeof(class)</code>.<br/> The buffered var seem to be 1.5-2 times as fast as <code>Object.GetType()</code>.<br/> <br/> I the right application, this is not just micro-optimising.<br/> If you sacrifice small things here and there, they will easily slow more than the one big thing you made 30% faster.<br/> <br/> Again as JaredPar answered, these kind of tests, is unreliable for telling about your specific application, as we have proven here.<br/> All our tests giving quite different results, and things seemingly unrelated to the code at hand, can affect the performance.<br/> <br/> The test:</p> <pre>.NetCore 2.1</pre> <pre><code>namespace ConsoleApp1 { class Program { public const int Cycles = 100000000; public static int Cycles2 = 100000000; public static QSData TestObject = new QSData(); public static Type TestObjectType; static void Main(string[] args) { TestObjectType = TestObject.GetType(); Console.WriteLine("Repeated cycles for each test : " + Cycles.ToString()); var test1 = TestGetType(); Console.WriteLine("Object.GetType : " + test1.ToString()); var test2 = TestTypeOf(); Console.WriteLine("TypeOf(Class) : " + test2.ToString()); var test3 = TestVar(); Console.WriteLine("Type var : " + test3.ToString()); var test4 = TestEmptyLoop(); Console.WriteLine("Empty Loop : " + test4.ToString()); Console.WriteLine("\r\nClean overview:"); Console.WriteLine("Object.GetType : " + (test1 - test4).ToString()); Console.WriteLine("TypeOf(Class) : " + (test2 - test4).ToString()); Console.WriteLine("Type var : " + (test3 - test4).ToString()); Console.WriteLine("\n\rPush a button to exit"); String input = Console.ReadLine(); } static long TestGetType() { var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; Cycles; i++) { Type aType = TestObject.GetType(); } stopwatch.Stop(); return stopwatch.ElapsedMilliseconds; } static long TestTypeOf() { var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; Cycles; i++) { Type aType = typeof(QSData); } stopwatch.Stop(); return stopwatch.ElapsedMilliseconds; } static long TestVar() { var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; Cycles; i++) { Type aType = TestObjectType; } stopwatch.Stop(); return stopwatch.ElapsedMilliseconds; } static long TestEmptyLoop() { var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; Cycles; i++) { Type aType; } stopwatch.Stop(); return stopwatch.ElapsedMilliseconds; } } } </code></pre>
46,016
<p>I am having trouble printing a hollow object using Slic3r. On flat slopes on top, there are gaps that I cannot get fixed. The perimeters of successive layers just don't cover each other.</p> <p>Cura however adds filament to cover the gaps.</p> <p>The bottom left bunny is sliced with Slic3r 1.2.9.99. The top right bunny is sliced with Cura 2.5. Take a closer look at the forehead and the back of the bottom left bunny.</p> <p>I have "extra perimeters if needed" turned on. But turning it off makes no difference. What am I missing?</p> <p>So far only adding infill and increase the solid top layer count helps to get a closed surface. But then everything gets stiffer. The bunnies are printed with nylon so they are a bit squishy.</p> <p><a href="https://i.stack.imgur.com/kTkjA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/kTkjA.jpg" alt="Cura and Slic3r Bunnies"></a></p> <p>The printer settings in both Cura and Slic3r are:</p> <ul> <li>0.4 mm nozzel;</li> <li>0.2 mm layer height;</li> <li>No infill;</li> <li>2 perimeter walls, and;</li> <li>3 solid top/bottom layers.</li> </ul>
<p>This seems to be a recurring problem with Slic3r.</p> <p>Slic3r appears to have problems with perimeters that are not attached to infill. I suspect that it is getting confused on what is the inside and what is the outside. I know that seems a bit silly; but as you slice an object with indentations (like the bunny's face) then the perimeter can cease to be a simple closed shape and it gets confused. If you use a viewer to step through the gcode layers around the place it starts having problems you may be able to see what is going wrong.</p> <p>Here are a couple of examples of why I say this is a recurring problem with slic3r. I also recall seeing a video that showed the problem but I can't remember where. That was one of the reasons I don't use slic3r.</p> <ul> <li><a href="https://github.com/alexrj/Slic3r/issues/748" rel="nofollow noreferrer">Reported on Sic3r Git in 2012</a> - Can't tell for sure if this was ever fixed</li> <li><a href="http://forums.reprap.org/read.php?340,512947" rel="nofollow noreferrer">Infill Perimeter issue in 2015</a></li> </ul> <p>Here are three options that may work</p> <ol> <li>Use a different slicer for this specific condition. Every product is going to have vulnerabilities - this may be one of slic3r's.</li> <li>Increase the perimeter and top and bottom layer thicknesses. Making them thick enough it will bridge the problem areas. Use a gcode viewer to inspect that area to see if it fixed the problem. That way you don't waste material on another fail. It sounds like you may have already tried this but you didn't like that it made the model stiffer.</li> <li>Repair the STL file using an application like <a href="http://www.meshmixer.com/" rel="nofollow noreferrer">Meshmixer</a>. Maybe you will have to get the file close then tweak it where it doesn't. Here is good article from <a href="https://pinshape.com/" rel="nofollow noreferrer">PinShape</a> <a href="https://pinshape.com/blog/how-to-repair-your-stl-files/" rel="nofollow noreferrer">repairing and STL file</a>.</li> </ol> <p>Good luck, hope this helps.</p>
<p>What infill are you using? How flexible do you need the object to be?</p> <p>I suggest two or three top and bottom layers, and a second or third solid perimeter as well.</p> <p>The slicer has to determine if a particular path is part of an external perimeter or a top layer, so adding one to each should give a better result.</p> <p>Thinner layers and a fan cooling the deposited material both help with overhangs like this.</p>
608
<p>Working in a medium size project during last 4 months - we are using JPA and Spring - I'm quite sure that JPA is not powerfull for projects that requires more than CRUD screen... Query interface is poor, Hibernate doesn't respect JPA spec all the time and lot of times I need to use hibernate classes, annotations and config. What do you guys think about JPA? Is it not good enough?</p>
<p>Well I think most of the time JPA is "good enough" but I miss the Criteria API a lot (only provided by Hibernate)</p>
<p>Sure any ORM is better than hand-writting SQL for CRUD operations... the thing is: I'm think there is no reason to use JPA instead pure Hibernate because I'm mixing both a lot. If I'm not getting a hidden provider why use JPA anyway?</p>
12,974
<p>I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.</p> <pre><code>declare @ConstraintName varchar(255) set @ConstraintName = 'PK_Whatever' IF LEFT(@ConstraintName, 2) = 'PK' BEGIN --can't drop primary keys END </code></pre> <p>The error I get is:</p> <pre><code>Incorrect syntax near 'END'. </code></pre> <p>If I add something after the comment, i.e. <code>PRINT @ConstraintName</code>, it works fine.</p>
<p>No, you cannot have an empty if block (or one that contains only comments).</p> <p>You don't say why you would want this. If you are just trying to comment out the contents of the if for debugging, you should comment the entire if.</p>
<p>Would it not be better to design your SQL statement around items you do wish to drop constraints for? So If you wish to remove the ability for this then</p> <pre><code>If left(@constraintname,2 &lt;&gt; 'PK' BEGIN -- Drop your constraint here ALTER TABLE dbo.mytable DROP constraint ... -- etc END </code></pre>
16,455
<p>If I give the input from Text Box like</p> <blockquote> <p>AaBbcdCDEb</p> </blockquote> <p>the output should be</p> <blockquote> <p>ABCDE or abcde</p> </blockquote> <p>only unique characters should be there, no repeated characters.</p> <p>How do I do this?</p>
<p>Use the Distinct extention method on the array of characters then recombine them into a string.</p> <pre><code>new string("AaBbcdCDEb".ToLower().Distinct().ToArray()); </code></pre>
<p>foreach char in textbox, if textbox/new string contains char then return, else add to new string?</p>
43,408
<p>I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.</p> <p>Here is the relevant part of my function:</p> <pre><code>Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuff End Function </code></pre> <p>How do I call this function and use the returned dictionary?</p> <p>EDIT: I've tried this:</p> <pre><code>Dim someStuff someStuff = GetSomeStuff </code></pre> <p>and</p> <pre><code>Dim someStuff Set someStuff = GetSomeStuff </code></pre> <p>When I try to access someStuff, I get an error:</p> <pre><code>Microsoft VBScript runtime error: Object required: 'GetSomeStuff' </code></pre> <p>EDIT 2: Trying this in the function:</p> <pre><code>Set GetSomeStuff = stuff </code></pre> <p>Results in this error:</p> <pre><code>Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment. </code></pre>
<p>I wasn't too sure of what was your problem, so I experimented a bit.</p> <p>It appears that you just missed that to assign a reference to an object, you have to use <code>set</code>, even for a return value:</p> <pre><code>Function GetSomeStuff Dim stuff Set stuff = CreateObject("Scripting.Dictionary") stuff.Add "A", "Anaconda" stuff.Add "B", "Boa" stuff.Add "C", "Cobra" Set GetSomeStuff = stuff End Function Set d = GetSomeStuff Wscript.Echo d.Item("A") Wscript.Echo d.Exists("B") items = d.Items For i = 0 To UBound(items) Wscript.Echo items(i) Next </code></pre>
<p>Have you tried:</p> <pre><code>Dim returnedStuff Set returnedStuff = GetSomeStuff() </code></pre> <p>Then "For Each" iterating over the dictionary? There's an example of using the Dictionary (albeit for VB6, the gist of it is the same though!) <a href="http://www.kamath.com/tutorials/tut009_dictionary.asp" rel="nofollow noreferrer">here</a>.</p>
16,939
<p><a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow noreferrer">YUI Compressor</a> does not accept wildcard parameters, so I cannot run it like this: </p> <pre><code>C:&gt;java -jar yuicompressor.jar *.js </code></pre> <p>But I have over 500 files and would rather not have to create a batch file like this:</p> <pre><code>C:&gt;java -jar yuicompressor.jar file1.js -o deploy\file1.js C:&gt;java -jar yuicompressor.jar file2.js -o deploy\file2.js ... C:&gt;java -jar yuicompressor.jar file500.js -o deploy\file500.js </code></pre> <p>And of course my file names are <em>not</em> in such uniform way.</p> <p>Is there way to automate this without writing any code? :)</p>
<p>I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work:</p> <pre><code>for %%a in (*.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a" </code></pre>
<p>You'll need to use some sort of a script to get a list of all the .js files, and then runs the YUI Compressor on all of them. On the windows command prompt, something like this should work:</p> <pre><code>FOR %f IN (*.js) DO java -jar yuicompressor.jar %f -o deploy\%f </code></pre>
28,124
<p>My $SHELL is tcsh. I want to run a C shell script that will call a program many times with some arguments changed each time. The program I need to call is in Fortran. I do not want to edit it. The program only takes arguments once it is executed, but not on the command line. Upon calling the program in the script, the program takes control (this is where I am stuck currently, I can never get out because the script will not execute anything until after the program process stops). At this point I need to pass it some variables, then after several iterations I will need to <kbd>Ctrl</kbd>+<kbd>C</kbd> out of the program and continue with the script.</p> <p>How can this be done?</p>
<p>To add to what @Toybuilder said, you can use a "here document". I.e. your script could have</p> <pre><code>./myfortranprogram &lt;&lt; EOF first line of input second line of input EOF </code></pre> <p>Everything between the "<code>&lt;&lt;EOF</code>" and the "<code>EOF</code>" will be fed to the program's standard input (does Fortran still use "read (5,*)" to read from standard input?)</p> <p>And because I think @ephemient's comment deserves to be in the answer:</p> <blockquote> <p>Some more tips: &lt;&lt;'EOF' prevents interpolation in the here-doc body; &lt;&lt;-EOF removes all leading tabs (so you can indent the here-doc to match its surroundings), and EOF can be replaced by any token. An empty token (&lt;&lt;"") indicates a here-doc that stops at the first empty line.</p> </blockquote> <p>I'm not sure how portable those ones are, or if they're just tcsh extensions - I've only used the <code>&lt;&lt;EOF</code> type "here document" myself.</p>
<p>Not a <code>tcsh</code> user, but if the program runs then reads in commands via <code>stdin</code> then you can use shell redirection <code>&lt;</code> to feed it the required commands. If you run it in the background with <code>&amp;</code> you will not block when it is executed. Then you can <code>sleep</code> for a bit, then use whatever tools you have (<code>ps</code>, <code>grep</code>, <code>awk</code>, etc) to discover the program's PID, then use <code>kill</code> to send it <code>SIGTERM</code> which is the same as doing a <kbd>Ctrl</kbd>-<kbd>C</kbd>.</p>
27,672
<p>Provide Used: Microsoft OLE DB Provider for SQL Server. Can anyone help me with this.. I was trying to connect with LLBLgen</p>
<p>This MSDN blog page has some useful on this...</p> <p><a href="http://blogs.msdn.com/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx</a></p>
<p>I used to get this error sometimes when connecting to my local SQL Server with Windows Authentication. I never fixed it unfortunately - it went away when I reinstalled windows.</p> <p>I think a reboot used to fix it - have you tried that? Not exactly the best solution, I know :P</p>
21,409
<p>In ASP.NET, I have an XML file (within my project) that I would like to deserialize. FileStream objects do not allow you to open a file via URL. </p> <p>What is the easiest way to open the file so that I can deserialize it? </p>
<p>There is an inconsistency in your specification. You say Database.py needs to import all Model classes to do ORM but then you say the User class need access to the Database to do queries.</p> <p>Think of these as layers of an API. The Database class provides an API (maybe object-oriented) to some physical persistence layer (such as DB-API 2.0). The Model classes, like User, use the Database layer to load and save their state. There is no reason for the Database.py class to import all the Model classes, and in fact you wouldn't want that because you'd have to modify Database.py each time you created a new Model class - which is a code smell.</p>
<p>I think you have one issue that should be straightened. Circular references often result from a failure to achieve separation of concerns. In my opinion, the database and model modules shouldn't know much about each other, working against an API instead. In this case the database shouldn't directly reference any specific model classes but instead provide the functionality the model classes will need to function. The model in turn, should get a database reference (injected or requested) that it would use to query and persist itself.</p>
22,419
<p>When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else?</p> <pre><code> function quicksort(array) var list less, greater if length(array) ≤ 1 return array select and remove a pivot value pivot from array for each x in array if x ≤ pivot then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater)) </code></pre> <p>Can someone help me grasp the concept of choosing a pivot and whether or not different scenarios call for different strategies.</p>
<p>Choosing a random pivot minimizes the chance that you will encounter worst-case O(n<sup>2</sup>) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases.</p> <p>Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them).</p>
<p>Ideally the pivot should be the middle value in the entire array. This will reduce the chances of getting worst case performance.</p>
19,845
<p>We're running a web app on Tomcat 6 and Apache mod_proxy 2.2.3. Seeing a lot of 502 errors like this:</p> <blockquote> <p>Bad Gateway! The proxy server received an invalid response from an upstream server.</p> <p>The proxy server could not handle the request GET /the/page.do.</p> <p>Reason: Error reading from remote server</p> <p>If you think this is a server error, please contact the webmaster.</p> <p>Error 502 </p> </blockquote> <p>Tomcat has plenty of threads, so it's not thread-constrained. We're pushing 2400 users via JMeter against the app. All the boxes are sitting inside our firewall on a fast unloaded network, so there shouldn't be any network problems. </p> <p>Anyone have any suggestions for things to look at or try? We're heading to tcpdump next.</p> <p>UPDATE 10/21/08: Still haven't figured this out. Seeing only a very small number of these under load. The answers below haven't provided any magical answers...yet. :)</p>
<p>Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27).</p> <p>For certain URLs the Tomcat server could take perhaps 20 minutes to return a page.</p> <p>I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its proxy operation (with a large over-spill factor in case Tomcat took longer to return a page):</p> <pre><code>Timeout 5400 ProxyTimeout 5400 </code></pre> <hr> <h2>Some backgound</h2> <p><a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html#proxytimeout" rel="noreferrer">ProxyTimeout</a> alone wasn't enough. Looking at the documentation for <a href="http://httpd.apache.org/docs/2.0/mod/core.html#timeout" rel="noreferrer">Timeout</a> I'm <em>guessing</em> (I'm not sure) that this is because while Apache is waiting for a response from Tomcat, there is no traffic flowing between Apache and the Browser (or whatever http client) - and so Apache closes down the connection to the browser.</p> <p>I found that if I left the Timeout setting at its default (300 seconds), then if the proxied request to Tomcat took longer than 300 seconds to get a response the browser would display a "502 Proxy Error" page. I believe this message is generated by Apache, in the knowledge that it's acting as a reverse proxy, before it closes down the connection to the browser (this is my current understanding - it may be flawed).</p> <p>The proxy error page says:</p> <blockquote> <p>Proxy Error</p> <p>The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET.</p> <p>Reason: Error reading from remote server</p> </blockquote> <p>...which suggests that it's the ProxyTimeout setting that's too short, while investigation shows that Apache's Timeout setting (timeout between Apache and the client) that also influences this.</p>
<p>If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of <code>timeout</code>. I try to condense the discussion I found here: <a href="http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html" rel="nofollow noreferrer">http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html</a> :</p> <blockquote> <p>It appears that <code>mod_proxy</code> considers a backend as failed only when the <strong>transport layer connection</strong> to that backend fails. Unless <code>failonstatus/failontimeout</code> is used. ...</p> </blockquote> <p>So, setting <code>failontimeout</code> is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a <em>fail</em> (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:</p> <blockquote> <p>ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50</p> </blockquote> <p>This is a misconfiguration because:</p> <blockquote> <p>You are defining a <code>balancer</code> here, so the <code>timeout</code> parameter relates to the <code>balancer</code> (like the two others). However for a <code>balancer</code>, the <code>timeout</code> parameter is not a <em>connection</em> timeout (like the one used with <code>BalancerMember</code>), but <strong>the maximum time to wait for a free worker/member</strong> (e.g. when all the workers are busy <em>or</em> in error state, the default being to not wait).</p> </blockquote> <p>So, a proper configuration is done like this</p> <ol> <li>set <code>timeout</code> at the <code>BalanceMember</code> level:</li> </ol> <pre class="lang-xml prettyprint-override"><code> &lt;Proxy balancer://mycluster&gt; BalancerMember http://member1:8080/svc timeout=6 ... more BalanceMembers here &lt;/Proxy&gt; </code></pre> <ol start="2"> <li>set the <code>failontimeout</code> on the <code>balancer</code></li> </ol> <pre><code>ProxyPass /svc balancer://mycluster failontimeout=on </code></pre> <p>Restart apache.</p>
20,457
<p>Is the index value of the first record in a dbf file 0 or 1? Is the index zero-based?</p>
<p>DBF's are always count based. I'm not sure what you're after, but given this fact I would have to say 1. Record 1 = first record in the table, not record 0. A goto 0 means goto top.</p>
<p>i'm not sure but this might give you a clue.</p> <p><a href="http://www.dbase.com/knowledgebase/int/db7_file_fmt.htm" rel="nofollow noreferrer">http://www.dbase.com/knowledgebase/int/db7_file_fmt.htm</a></p> <blockquote> <p>1.3.1 Standard Property and Constraint Descriptor Array</p> <blockquote> <p>Table field offset - base one. 01 for the first field in the table, 02 for the second field, etc. Note: this will be 0 in the case of a constraint.</p> </blockquote> </blockquote>
39,847
<p>Is there a redistributable .Net 3.5 installation package that is a silent installer? </p> <p>Or alternatively, is there a switch that can be passed to the main redistributable .Net 3.5 installer to make it silent?</p>
<p>dotnetfx35setup.exe /q /norestart</p> <p>see the .net deployment guide at:</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc160716.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cc160716.aspx</a></p>
<p>For Windows 10 you need to do following</p> <pre><code>DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:"Path\To\microsoft-windows-netfx3-ondemand-package" </code></pre> <p>You can find thoose packages under sources\sxs of a Windows DVD</p>
7,082
<p>I am trying to run this 3D printer:</p> <ul> <li>Fabrikator Mini V2 Turnigy/Malyan M100</li> </ul> <p>Does anyone have the Cura settings?</p>
<p>I googled your machine name and found this HobbyKing page. There is a link here to CURA settings. </p> <p><a href="https://hobbyking.com/en_us/mini-fabrikator-v2-3d-printer-us-plug.html" rel="nofollow noreferrer">Page with CURA settings</a></p>
<p>I thought it better if I included the Cura profile settings, pointed to in <a href="https://3dprinting.stackexchange.com/questions/10157/cura-settings-for-fabrikator-mini-v2-turnigy-or-malyan-m100/10166#10166">cmm's answer</a>, here, in case of link death:</p> <pre><code>[profile] layer_height = 0.2 wall_thickness = 0.8 retraction_enable = True solid_layer_thickness = 1.2 fill_density = 20 nozzle_size = 0.4 print_speed = 60 print_temperature = 200 print_temperature2 = 0 print_temperature3 = 0 print_temperature4 = 0 print_temperature5 = 0 print_bed_temperature = 60 support = Touching buildplate platform_adhesion = Brim support_dual_extrusion = Both wipe_tower = False wipe_tower_volume = 15 ooze_shield = False filament_diameter = 1.75 filament_diameter2 = 0 filament_diameter3 = 0 filament_diameter4 = 0 filament_diameter5 = 0 filament_flow = 100 retraction_speed = 30 retraction_amount = 3 retraction_dual_amount = 16.5 retraction_min_travel = 1.5 retraction_combing = All retraction_minimal_extrusion = 0.02 retraction_hop = 0.0 bottom_thickness = 0.3 layer0_width_factor = 100 object_sink = 0.0 overlap_dual = 0.15 travel_speed = 100 bottom_layer_speed = 20 infill_speed = 0.0 solidarea_speed = 0.0 inset0_speed = 20 insetx_speed = 0 cool_min_layer_time = 3 fan_enabled = True skirt_line_count = 2 skirt_gap = 4.0 skirt_minimal_length = 150.0 fan_full_height = 0.5 fan_speed = 100 fan_speed_max = 100 cool_min_feedrate = 10 cool_head_lift = False solid_top = True solid_bottom = True fill_overlap = 15 perimeter_before_infill = False support_type = Lines support_angle = 60 support_fill_rate = 15 support_xy_distance = 0.7 support_z_distance = 0.15 spiralize = False simple_mode = False brim_line_count = 5 raft_margin = 5.0 raft_line_spacing = 3.0 raft_base_thickness = 0.3 raft_base_linewidth = 1.0 raft_interface_thickness = 0.27 raft_interface_linewidth = 0.4 raft_airgap_all = 0.0 raft_airgap = 0.22 raft_surface_layers = 2 raft_surface_thickness = 0.27 raft_surface_linewidth = 0.4 fix_horrible_union_all_type_a = True fix_horrible_union_all_type_b = False fix_horrible_use_open_bits = False fix_horrible_extensive_stitching = False plugin_config = object_center_x = -1 object_center_y = -1 [alterations] start.gcode = ;Sliced at: {day} {date} {time} ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} ;Print time: {print_time} ;Filament used: {filament_amount}m {filament_weight}g ;Filament cost: {filament_cost} ;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line ;M109 S{print_temperature} ;Uncomment to add your own temperature line G21 ;metric values G90 ;absolute positioning M82 ;set extruder to absolute mode M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z0.2 F{travel_speed} ;move the platform down 15mm G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F{travel_speed} end.gcode = ;End GCode M104 S0 ;extruder heater off M140 S0 ;heated bed heater off (if you have it) G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way M84 ;steppers off G90 ;absolute positioning ;{profile_string} start2.gcode = ;Sliced at: {day} {date} {time} ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} ;Print time: {print_time} ;Filament used: {filament_amount}m {filament_weight}g ;Filament cost: {filament_cost} ;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line ;M104 S{print_temperature} ;Uncomment to add your own temperature line ;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line ;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line G21 ;metric values G90 ;absolute positioning M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z0.2 F{travel_speed} ;move the platform down 15mm T1 ;Switch to the 2nd extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T0 ;Switch to the first extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F{travel_speed} end2.gcode = ;End GCode M104 T0 S0 ;extruder heater off M104 T1 S0 ;extruder heater off M140 S0 ;heated bed heater off (if you have it) G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way M84 ;steppers off G90 ;absolute positioning ;{profile_string} start3.gcode = ;Sliced at: {day} {date} {time} ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} ;Print time: {print_time} ;Filament used: {filament_amount}m {filament_weight}g ;Filament cost: {filament_cost} ;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line ;M104 S{print_temperature} ;Uncomment to add your own temperature line ;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line ;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line G21 ;metric values G90 ;absolute positioning M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z0.2 F{travel_speed} ;move the platform down 15mm T2 ;Switch to the 3rd extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T1 ;Switch to the 2nd extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T0 ;Switch to the first extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F{travel_speed} ;Put printing message on LCD screen M117 Printing... end3.gcode = ;End GCode M104 T0 S0 ;extruder heater off M104 T1 S0 ;extruder heater off M104 T2 S0 ;extruder heater off M140 S0 ;heated bed heater off (if you have it) G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way M84 ;steppers off G90 ;absolute positioning ;{profile_string} start4.gcode = ;Sliced at: {day} {date} {time} ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} ;Print time: {print_time} ;Filament used: {filament_amount}m {filament_weight}g ;Filament cost: {filament_cost} ;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line ;M104 S{print_temperature} ;Uncomment to add your own temperature line ;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line ;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line ;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line G21 ;metric values G90 ;absolute positioning M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z0.2 F{travel_speed} ;move the platform down 15mm T3 ;Switch to the 4th extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T2 ;Switch to the 3rd extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T1 ;Switch to the 2nd extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F200 E-{retraction_dual_amount} T0 ;Switch to the first extruder G92 E0 ;zero the extruded length G1 X75 E10 F{travel_speed} ;extrude 10mm of feed stock G92 E0 ;zero the extruded length again G1 F{travel_speed} ;Put printing message on LCD screen M117 Printing... end4.gcode = ;End GCode M104 T0 S0 ;extruder heater off M104 T1 S0 ;extruder heater off M104 T2 S0 ;extruder heater off M104 T3 S0 ;extruder heater off M140 S0 ;heated bed heater off (if you have it) G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way M84 ;steppers off G90 ;absolute positioning ;{profile_string} support_start.gcode = support_end.gcode = cool_start.gcode = cool_end.gcode = replace.csv = preswitchextruder.gcode = ;Switch between the current extruder and the next extruder, when printing with multiple extruders. ;This code is added before the T(n) postswitchextruder.gcode = ;Switch between the current extruder and the next extruder, when printing with multiple extruders. ;This code is added after the T(n) </code></pre> <p>Note these are some customer uploads, from the HobbyKing page for <a href="https://hobbyking.com/en_us/mini-fabrikator-v2-3d-printer-us-plug.html" rel="nofollow noreferrer">Mini Fabrikator V2 3D Printer - Silver (US Plug)</a>, under the <strong>Upload Files</strong> tab, click the <a href="https://cdn-global-hk.hobbyking.com/media/file/c/u/cura_profile_3.zip" rel="nofollow noreferrer"><code>CURA PROFILE_3.ZIP</code></a> zip file.</p>
1,336