instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I have a Prusa i3 made by Geeetech. My 3D prints keep suffering from warping when printing with PLA.</p> <p>Whenever I print something with a base at about 10 cm x 10 cm, at least one corner of the print would warp up. I've read numerous articles about warping and tried all sorts of methods. My printer's bed is level, and heated to 60°C. My bed is made from clean glass. I've tried all sorts of adhesives. I tried blue tape, and used hair spray. </p> <p>The only way for me to combat this is gluing the base to blue tape with 502 Glue. I used brim and the whole brim just warps up. I sometimes leave the model printing over night. For the first few hours it's perfectly flat. When I go back to it the next morning I'd find one corner warped up. This is very dysfunctional to my prints. </p> <p>Is there a reliable way to stop this warping from happening?</p>
<p>For ABS it will warp unless you build a heat chamber. </p> <p>That said the tricks to reduce warping come down to: </p> <ol> <li>Material, i.e. PLA is less likely to warp; </li> <li>Use a fan, it helps so much; </li> <li>Make sure you have temps calibrated well - Too hot is more warp; </li> <li>Use a raft. The Makerbot uses a raft and no heated bed; </li> <li>Make sure the room is not drafty. Having it by the window will result in warping; </li> <li>Adding a large brim also helps;</li> <li>I find good ol' glue sticks work the best at keeping the print to the bed;</li> <li>SMASH the first layer. This one is controversial. I personally do first layer at 130% and print speed of 30%. You get elephants foot sure, but it's on the bed real good.</li> </ol> <p>Tom is right. It is very very hard to print that big of a piece without warping. That said I have done very large pieces on my Ultimaker, using a fan, glue stick, MatterHackers PRO PLA and no raft. But again that's on an Ultimaker. </p> <p>Note you can build a heat chamber pretty easily. Specifically a passive heat chamber. </p>
<p>Source (at least in part): </p> <ul> <li><a href="http://books.google.co.uk/books?id=MJqoBQAAQBAJ&amp;pg=RA10-PA6" rel="nofollow noreferrer">SolidWorks 2015 Tutorial with Video Instruction, page 11-6</a>, and;</li> <li><a href="https://www.makerbot.com/media-center/2011/06/23/12-ways-to-fight-warping-and-curling" rel="nofollow noreferrer">12 ways to fight warping and curling</a>, June 23, 2011 by MakerBlock</li> </ul> <blockquote> <p>Curling</p> <p>As printed plastic parts cool the different areas of the object can cool at different rates. 1 Depending upon the parts being printed, this effect can lead to warping and curling. Although PLA has a much lower shrinkage factor than ABS, both can warp and curl, potentially ruining a print. There are some very common ways to deal with this potential problem, the most notable being a heated build platform. However, sometimes that might not be enough.</p> <ol> <li><p>Use a heated build platform. A heated build platform helps keep the lowest levels of a print warm as the higher layers are printed. This allows the overall print to cool more evenly. A heated build platform, sometimes abbreviated as HBP, helps tremendously with just about any ABS print and large PLA prints.</p></li> <li><p>Print with a raft. Rafts are a printing option in ReplicatorG and Skeinforge. They’re basically a large flat lattice work of printed material underneath the lower-most layer of your printed object. They’ll also help reduce warping and curling by allowing your printed object to adhere better to your flat build surface. Other variations on this are to print with a larger raft and/or a thicker raft comprised of more layers.</p></li> <li><p>Calibrate your starting Z height. A good first layer makes all the difference. If your starting Z axis height is too high, the extruded filament won’t be able to make a good bond with the platform. If you think your Z axis starting height is too high, try lowering it by 0.05mm increments until you find a good first layer.</p></li> <li><p>Get the right build surface. Some people have experimented with different surfaces such as steel, titanium, glass, different kinds of plastic, different kinds of tape, and foam board. However, I find both ABS and PLA seem to stick really well to hot or warm Kapton tape.</p></li> <li><p>Clean your build surface. ABS and PLA stick better to a clean build surface. Keep it clean of dust, pieces of old prints, and any other debris.</p></li> <li><p>Print slower. Printing slower allows finer detail, better adhesion to the build surface and lower layers, and gives the printed part more time to cool evenly.</p></li> <li><p>Print cooler. Printing at a lower temperature isn’t always an option. Ideally, you should be printing at the lowest temperature required for extrusion and that allows good interlayer adhesion. However, trying lower temperatures isn’t for the faint of heart. Printing at a too low a temperature could cause harm to your extruder motor or extruder.</p></li> <li><p>Eliminate drafts or enclose your robot. Forrest Higgs found that having his 3D printer too close to an open window caused very uneven heating across his build surface. This in turn caused the side of his prints closest to the window to curl. Since keeping the window closed wasn’t an option for him, he compensated for the window drafts by adding a heat lamp. Cupcake and Thing-O-Matic owners might have an easier time of eliminating drafts by simply enclosing two or three of the sides of their robots. It will also have a fortunate side effect of helping to control fumes.</p></li> <li><p>Design with mouse ears. Zach Smith’s solution was to add little discs to corners of an object to help those corners stick to the platform. These essentially serve as “mini-rafts” to give those corners more surface area and better adhesion without having to print an entire raft.</p></li> <li><p>Design with aprons to hold down corners. Forrest Higgs suggested adding “aprons” around an object to be printed, while that object was being printed on a raft. These low thick pieces of plastic help keep the raft flat and help prevent any curling or warping from affecting the desired printed object itself.</p></li> <li><p>Design with surrounding thermal walls. While Forrest Higgs’ apron approach provides a mechanical advantage of essentially holding down corners with a chunk of plastic, Nophead has added thin surrounding walls to his designs to act as baffles to keep warm air around the printed object as it moves around. He’s postulated that a very thin surrounding wall could have the same beneficial effect as printing inside an enclosed build chamber. Interestingly, it seems that Nophead suggests that designing objects with more rounded corners might also help avoid curling and warping at those corners.</p></li> <li><p>Reduce infill. When printing a model you can chose to print it hollow, completely solid, or some percentage between zero and 100. However, as Nophead points out even the plastic inside a model exerts a force on the entire printed object as it cools. It stands to reason that the more plastic you have, the more those pieces of plastic will pull against themselves and the build surface as they cool. By reducing infill there will a reduced amount of internal tension as the object cools. Reducing these internal forces by printing with a lower infill ratio can help reduce curling and warping as well.</p></li> </ol> </blockquote>
510
<p>Having briefly looked at Haskell recently, what would be a <em>brief, succinct, practical</em> explanation as to what a monad essentially is?</p> <p>I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.</p>
<p>First: The term <strong>monad</strong> is a bit vacuous if you are not a mathematician. An alternative term is <strong>computation builder</strong> which is a bit more descriptive of what they are actually useful for.</p> <p>They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different.</p> <p>The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments).</p> <p>Arrays in JavaScript support the pattern, so let’s use that as the first example.</p> <p>The gist of the pattern is we have a type (<code>Array</code> in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an <code>Array</code>).</p> <p>First an example of method chaining which does <em>not</em> use the monad pattern:</p> <pre><code>[1,2,3].map(x =&gt; x + 1) </code></pre> <p>The result is <code>[2,3,4]</code>. The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be:</p> <pre><code>[1,2,3].flatMap(x =&gt; [x + 1]) </code></pre> <p>Here we supply an operation which returns an <code>Array</code>, so now it conforms to the pattern. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap" rel="noreferrer"><code>flatMap</code></a> method executes the provided function for every element in the array. It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array <code>[2,3,4]</code>.</p> <p>(The function argument provided to a method like <code>map</code> or <code>flatMap</code> is often called a &quot;callback&quot; in JavaScript. I will call it the &quot;operation&quot; since it is more general.)</p> <p>If we chain multiple operations (in the traditional way):</p> <pre><code>[1,2,3].map(a =&gt; a + 1).filter(b =&gt; b != 3) </code></pre> <p>Results in the array <code>[2,4]</code></p> <p>The same chaining in monad form:</p> <pre><code>[1,2,3].flatMap(a =&gt; [a + 1]).flatMap(b =&gt; b != 3 ? [b] : []) </code></pre> <p>Yields the same result, the array <code>[2,4]</code>.</p> <p>You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not.</p> <p>Do note that the monad pattern can be combined in a different way:</p> <pre><code>[1,2,3].flatMap(a =&gt; [a + 1].flatMap(b =&gt; b != 3 ? [b] : [])) </code></pre> <p>Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation.</p> <p>The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array.</p> <p>This can be described a bit more formally using Typescript notation. An array has the type <code>Array&lt;T&gt;</code>, where <code>T</code> is the type of the elements in the array. The method <code>flatMap()</code> takes a function argument of the type <code>T =&gt; Array&lt;U&gt;</code> and returns an <code>Array&lt;U&gt;</code>.</p> <p>Generalized, a monad is any type <code>Foo&lt;Bar&gt;</code> which has a &quot;bind&quot; method which takes a function argument of type <code>Bar =&gt; Foo&lt;Baz&gt;</code> and returns a <code>Foo&lt;Baz&gt;</code>.</p> <p>This answers <em>what</em> monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them.</p> <p><strong>Haskell and Do-notation</strong></p> <p>To translate the map/filter example directly to Haskell, we replace <code>flatMap</code> with the <code>&gt;&gt;=</code> operator:</p> <pre><code>[1,2,3] &gt;&gt;= \a -&gt; [a+1] &gt;&gt;= \b -&gt; if b == 3 then [] else [b] </code></pre> <p>The <code>&gt;&gt;=</code> operator is the bind function in Haskell. It does the same as <code>flatMap</code> in JavaScript when the operand is a list, but it is overloaded with different meaning for other types.</p> <p>But Haskell also has a dedicated syntax for monad expressions, the <code>do</code>-block, which hides the bind operator altogether:</p> <pre><code> do a &lt;- [1,2,3] b &lt;- [a+1] if b == 3 then [] else [b] </code></pre> <p>This hides the &quot;plumbing&quot; and lets you focus on the actual operations applied at each step.</p> <p>In a <code>do</code>-block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list.</p> <p>The back-arrow <code>&lt;-</code> looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list.</p> <p><strong>Example: Safe navigation (the Maybe type)</strong></p> <p>Enough about lists, lets see how the monad pattern can be useful for other types.</p> <p>Some functions may not always return a valid value. In Haskell this is represented by the <code>Maybe</code>-type, which is an option that is either <code>Just value</code> or <code>Nothing</code>.</p> <p>Chaining operations which always return a valid value is of course straightforward:</p> <pre><code>streetName = getStreetName (getAddress (getUser 17)) </code></pre> <p>But what if any of the functions could return <code>Nothing</code>? We need to check each result individually and only pass the value to the next function if it is not <code>Nothing</code>:</p> <pre><code>case getUser 17 of Nothing -&gt; Nothing Just user -&gt; case getAddress user of Nothing -&gt; Nothing Just address -&gt; getStreetName address </code></pre> <p>Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for <code>Maybe</code>:</p> <pre><code>do user &lt;- getUser 17 addr &lt;- getAddress user getStreetName addr </code></pre> <p>This <code>do</code>-block invokes the bind-function for the <code>Maybe</code> type (since the result of the first expression is a <code>Maybe</code>). The bind-function only executes the following operation if the value is <code>Just value</code>, otherwise it just passes the <code>Nothing</code> along.</p> <p>Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way.</p> <p>Note that it is the <em>combination</em> of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case.</p> <p><strong>Mutable state</strong></p> <p>Haskell does not support mutable state. All variables are constants and all values immutable. But the <code>State</code> type can be used to emulate programming with mutable state:</p> <pre><code>add2 :: State Integer Integer add2 = do -- add 1 to state x &lt;- get put (x + 1) -- increment in another way modify (+1) -- return state get evalState add2 7 =&gt; 9 </code></pre> <p>The <code>add2</code> function builds a monad chain which is then evaluated with 7 as the initial state.</p> <p>Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally &quot;opt-in&quot; on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this.</p> <p><strong>IO</strong></p> <p>The <code>IO</code> type is used for chaining and executing “impure” functions.</p> <p>Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: <code>putStrLine</code>, <code>readLine</code> and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values.</p> <p>A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value.</p> <p>Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect.</p> <p>This is guaranteed by giving all impure functions the <code>IO</code> type. The entry point in Haskell program is the <code>main</code> function which have the <code>IO</code> type, so we can execute impure functions at the top level.</p> <p>But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an <code>IO</code> value except to assign it to <code>main</code>. So if a function wants to execute an impure function, it has to be connected to <code>main</code> and have the <code>IO</code> type.</p> <p>Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language.</p> <p>This brings us to the first program most people will write in Haskell:</p> <pre><code>main :: IO () main = do putStrLn ”Hello World” </code></pre> <p>The <code>do</code> keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency.</p> <p>The <code>()</code> type means “void”. This special return type is only useful for IO functions called for their side effect.</p> <p>A longer example:</p> <pre><code>main = do putStrLn &quot;What is your name?&quot; name &lt;- getLine putStrLn &quot;hello&quot; ++ name </code></pre> <p>This builds a chain of <code>IO</code> operations, and since they are assigned to the <code>main</code> function, they get executed.</p> <p>Comparing <code>IO</code> with <code>Maybe</code> shows the versatility of the monad pattern. For <code>Maybe</code>, the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For <code>IO</code>, the pattern is used to ensure that all operations of the <code>IO</code> type are sequenced and that <code>IO</code> operations cannot &quot;leak&quot; to pure functions.</p> <p><strong>Summing up</strong></p> <p>In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like:</p> <ul> <li>Avoiding repetitive code (<code>Maybe</code>)</li> <li>Adding language features like mutable state or exceptions for delimited areas of the program.</li> <li>Isolating icky stuff from nice stuff (<code>IO</code>)</li> <li>Embedded domain-specific languages (<code>Parser</code>)</li> <li>Adding GOTO to the language.</li> </ul>
<h2>Explanation</h2> <p>It's quite simple, when explained in C#/Java terms:</p> <ol> <li><p>A monad is a function that takes arguments and returns a special type. </p></li> <li><p>The special type that this monad returns is <strong>also</strong> called monad. (A monad is a combination of #1 and #2)</p></li> <li><p>There's some syntactic sugar to make calling this function and conversion of types easier.</p></li> </ol> <h2>Example</h2> <p>A monad is useful to make the life of the functional programmer easier. The typical example: The <code>Maybe</code> monad takes two parameters, a value and a function. It returns <code>null</code> if the passed value is <code>null</code>. Otherwise it evaluates the function. If we needed a special return type, we would call this return type <code>Maybe</code> as well. A very crude implementation would look like this:</p> <pre><code>object Maybe(object value, Func&lt;object,object&gt; function) { if(value==null) return null; return function(value); } </code></pre> <p>This is spectacularly useless in C# because this language lacks the required syntactic sugar to make monads useful. But monads allow you to write more concise code in functional programming languages.</p> <p>Oftentimes programmers call monads in chains, like so:</p> <pre><code>var x = Maybe(x, x2 =&gt; Maybe(y, y2 =&gt; Add(x2, y2))); </code></pre> <p>In this example the <code>Add</code> method would only be called if <code>x</code> and <code>y</code> are both non-<code>null</code>, otherwise <code>null</code> will be returned.</p> <h2>Answer</h2> <p>To answer the original question: A monad is a function AND a type. Like an implementation of a special <code>interface</code>.</p>
6,675
<p>My Anet A8 suddenly had issues with being unable to heat the bed. After ruling out software issues, I disconnected the connector and found this (sorry for the terrible quality):</p> <p><a href="https://i.stack.imgur.com/7WYfE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7WYfE.jpg" alt="Faulty connector: left male, right female, indicator on the burnt pin"></a></p> <p>The left most pin on the male connector (bed) is also charred. How could I best repair this?</p>
<p>Owning an Anet A8 I confirm that the connectors are not rated for the amount of current that pass through them. <strong>You do not need a new bed unless the heat element has burned through</strong> (but that is pretty uncommon, it usually is the connector). This burning of the bed connectors is a very well known problem of the Anet A8 printers; these connectors are just not rated for the current and the movement of the bed. It is best not to use a connector at all! And yes, the Anet A8 default printer firmware does not have any build in protection for <a href="/q/8466">thermal runaway</a>! It is always advised to immediately flash another firmware, e.g. <a href="https://github.com/MarlinFirmware/Marlin/tree/1.1.x/Marlin" rel="nofollow noreferrer">Marlin firmware</a>. </p> <p>The best repair is to get some high quality silicone AWG 14/16 wires and solder these directly onto the back of the pins of the connector. Also crimp forks to the other end to connect the wires correctly to the printer board.</p> <p>What I did was cutting up the connector to leave only the 2 middle pins (for connecting the bed thermistor, which does not use much power) and soldered the red wire to the left 2 pins and the black to the right 2 pins. You can do that at the back side of the socket where the pins make an angle.</p>
<h1>New Bed (Connection)</h1> <p>You will at least need a new female connector, but as the connector burnt, you have some underlying problem that made the connector burn in the first place: either the board is sending bad signals to the bed, or the bed is not rated for the board or you <em>just</em> had a faulty connector (the most usual culprit). Honestly? Replace the whole connector for a properly rated and intact pair - these pin connectors are not rated for 12 V at all but for 5 V!</p> <p>If you don't use a beefier connector, solder the wires <em>directly</em> to the bed.</p> <h1>Safety first!</h1> <p>Anet isn't known for good firmware implementation of safety, so make twice sure that you <strong>run a firmware that has Thermal Runaway Protection enabled!</strong></p>
1,147
<p>Here is the problem I have:</p> <p>I have a lot (tens of thousands) of mp3 files that my users would like to be able to search. Is there is software out there that you've used or heard good things about that would allow me to index that content and put it in a database so I can search on it later?</p>
<p>I've heard very good reviews of <a href="http://www.nuance.co.uk/naturallyspeaking/" rel="nofollow noreferrer" title="Dragon Naturally Speaking">Dragon Naturally Speaking</a>, by Nuance. They offer a <a href="http://www.nuance.com/naturallyspeaking/products/sdk.asp" rel="nofollow noreferrer">software development kit</a>, but I couldn't find out any information about pricing for small projects.</p>
<p>I've heard very good reviews of <a href="http://www.nuance.co.uk/naturallyspeaking/" rel="nofollow noreferrer" title="Dragon Naturally Speaking">Dragon Naturally Speaking</a>, by Nuance. They offer a <a href="http://www.nuance.com/naturallyspeaking/products/sdk.asp" rel="nofollow noreferrer">software development kit</a>, but I couldn't find out any information about pricing for small projects.</p>
9,799
<p>This one has been bugging me for a while now.</p> <p>Is there a way I can stop Intellj IDEA from reporting missing keys in tags?</p> <p>My messages are not stored in property files so the issue does not apply in my case.</p> <p>I'm using IntelliJ IDEA 7.0.4</p>
<p>I <a href="http://jetbrains.net/jira/browse/IDEADEV-30407" rel="nofollow noreferrer">reported this as an issue</a> to JetBrains and according to their issue report this is fixed in "Diana 8858". AFICT that means this will be fixed in IDEA 8.0.</p>
<p>IMHO you can disable every hint or error marker in IDEA. Please tell us the version of IDEA that you use.</p>
8,994
<p>After I level my Ender 3, the distance between the nozzle and the bed seems fine on both ends, but moving the bed on the Y axis shows that it's increasing and decreasing for three times, which I just cant fix.</p> <p>This only occurs on the left side - the right side is constant from beginning to end. Also I've been using three different beds (the magnetic one and two glasses) to make sure it's really something else.</p> <p>I created <a href="https://www.youtube.com/watch?v=zqLqTGeljyw" rel="noreferrer">this video</a> to demonstrate the problem. </p> <p>I'm sure that this has something to do with the carriage wheel adjustment, but tightening those did not change anything.</p> <p>How do I get rid of this problem?</p>
<p>Your video shows that your bed seems warped somewhat.</p> <h2>Ammount of error</h2> <p>As I assume you did level the bed with a sheet of paper to be 0.1 mm thick, we can estimate the change of thickness. The thickest point seems to be 0.2 mm, the thinnest 0.05. that's in average an error of 0.075 mm for the first layer. If you can live with that, no need to touch it.</p> <h2>Fixing the issue</h2> <p>Basically, if the error is too large for your liking, you need to fix it. To fix it, there are pretty much 2 ways. Remember that <a href="https://3dprinting.stackexchange.com/questions/6342/what-voltage-does-the-creality-ender-3-run-at">the Ender-3 uses 24V</a> when ordering parts!</p> <h3>Fix the part or install a replacement part</h3> <p>If you feel like you need to get it even flatter, you'll need to try to flatten the bed mechanically or replace it. You'll need to be comfortable to remove the BuildTak-clone surface, then remove the leveling screws, open the electronics enclosure, remove some hot glue, unhook the bed.</p> <p>Then you will need to flatten the bed in some way (grinding the upper side perfectly flat or bending it, replacing it for an entirely flat one).</p> <p>Then reinstall it, going through the uninstallation backward, and add a new build surface on it.</p> <h3>Switch to alternate leveling method: Mesh Bed Leveling</h3> <p>If you consider yourself to be able to do some intermediate to advanced modification of your printer, you can change the hotend carriage to one that allows mounting a distance sensor and changing the firmware to mesh-bed-leveling.</p> <p>You'll need to get an induction or capacity sensor (common operation ranges for those are 6-36V, so perfectly fine with 24V) and <a href="https://3dprinting.stackexchange.com/questions/6358/inductive-sensor-in-24-v-machine">some way to couple that to the board</a>, most likely an optocoupler. Print a new mounting for sensor and fans.</p> <p>To install you open the electronics compartment, hook up your chosen 24V-5V coupler as extra to the Z-switch, hook the power supply of the sensor up and run it up to the printhead. Replace the mounting for the hotend cooling fan and part cooling fan and <a href="https://3dprinting.stackexchange.com/a/6660/8884">change your firmware</a>. Calibrate the height of the sensor to trigger correctly.</p> <p>I did flash a bootloader <a href="https://3dprinting.stackexchange.com/questions/6685/how-to-install-new-atmega-firmware-via-the-isp-pins">via the ISP</a> on my ender-3 since then, so I can just flash the new firmware via a direct connection.</p> <h2>Last words</h2> <p>In either way, after fixing, you should run a PID-tune on the machine.</p> <p>Thermal Runaway might or might not be active, depending on your firmware iteration, so you should update it anyway, which might make Mesh Bed Leveling the slightly easier way to go.</p> <p>This has <em>nothing</em> to do with the bed carriage wheels, as the bed hangs onto the carriage only via the screws in the corners.</p>
<p>Blue Painters tape on the left side starting at the center and leaving a band on the far left side and the rear Perfetto side. I checked the before and after and the thickness of the tape shimmed out the deflection on the plate. It sounds like whatever the use to stamp the steel out is creating the bend we are only talking several thousands of an inch but when I put a flat edge on the plate and shined a light from the rear I could see daylight. The blue tape was from Nearys video on creality cr-10 bed leveling. </p>
1,202
<p>Trying to avoid the .net WebBrowser control (I don't need to navigate to a url, print rendered html or any of the other inbuilt goodies). Wrapping the IE dll seems a bit heavyweight.</p> <p>I simply require something that can display basic html marked up text - an html equivalent of <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.aspx" rel="nofollow noreferrer">RichTextBox</a> in effect. Anyone have any experiences / recommendations / war stories?</p>
<p>I developed this <a href="http://www.modeltext.com/html/" rel="noreferrer">HTML control for .NET</a>, which does what you were asking: i.e. display basic html marked up text.</p> <p>It doesn't use IE or any other unmanaged code (except for the .NET framework itself).</p>
<p>While it takes a bit of effort, you can disable almost all of the 'extra' functionality of the built in WebBrowser control.</p> <p>If the built in web browser provides all the functionality you need why look elsewhere?</p>
3,851
<p>I work on an application that uses DCOM to communicate between what are essentially several peers; in the course of normal use, instances on separate machines serve a variety of objects to one another. Historically, for this to work we have used some magic incantations, chief among which is that on every machine the user must log into an account of the same name (note that these are local accounts; there is no domain available). Obviously, this is an aspect of our user experience that could be improved.</p> <p>I would like to better understand how DCOM authentication works, but I am having difficulty assembling the whole story from the MSDN documentation for <a href="http://msdn.microsoft.com/en-us/library/ms693736.aspx" rel="nofollow noreferrer">CoInitializeSecurity()</a>, <a href="http://msdn.microsoft.com/en-us/library/ms692692.aspx" rel="nofollow noreferrer">CoSetProxyBlanket()</a>, and the like. Are there any thorough explanations available of how, exactly, DCOM operations are accepted or denied? Books, journals, web, any format is fine.</p>
<p><em>Programming Windows Security</em> by Keith Brown includes a thorough discussion of DCOM security. I can highly recommend this book.</p>
<p>You could also try to round up a copy of <em>Inside Distributed COM</em> by Guy and Henry Eddon (Microsoft Press) - It is out of print but amazon shows a number of used copies for sale:</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/157231849X" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Inside-Distributed-Com-Mps-Eddon/dp/157231849X/ref=sr_1_5?ie=UTF8&amp;s=books&amp;qid=1231968553&amp;sr=8-5</a></p>
7,229
<p>I want to write an <code>onClick</code> event which submits a form several times, iterating through selected items in a multi-select field, submitting once for each. </p> <p><strong>How do I code the loop?</strong></p> <p>I'm working in Ruby on Rails and using <code>remote_function()</code> to generate the JavaScript for the ajax call.</p>
<p>My quick answer (as I've not coded it yet) would be to create another function that creates a POST using XMLHTTPRequest and the specific parameters for a single call. Then inside your onClick() handler call that function as you loop through your selected items.</p> <p>I would suggest that you do a Proof of Concept just using a dummy HTML page and javascript and then try to figure out how to get it to work in RoR.</p> <p>Also, why are you attempting to make the multiple calls from the browser as opposed to handling the looping conditions in the RoR controller?</p>
<p>Unless you're modifying the browser DOM, I can't think of a reason that you would want to do this. (But without knowing fully what you're trying to do, I could be wrong in this case =)</p> <p>You should be able to send back data from mulitple objects (even nested complex objects in your form) in just one POST.</p> <p>Chances are the rails code will be a lot less complex, easier to write (and easier to debug!) than any javascript you come up with. </p> <p>If you need to update different parts of the page depending on what the user has selected, you can still make multiple updates to the DOM via RJS in your render :update block, so that shouldn't be an issue.</p> <p>You'll also have the (large) benefit of only one server round-trip instead of the multiple trips you would need using multiple POSTS.</p>
8,656
<p>I'm writing an Emacs major mode for an APL dialect I use at work. I've gotten basic font locking to work, and after setting comment-start and comment-start-skip, comment/uncomment region and fill paragraph also work.</p> <p>However, comment blocks often contain javadoc style comments and i would like fill-paragraph to avoid glueing together lines starting with such commands.</p> <p>If I have this (\ instead of javadoc @):</p> <pre><code># This is a comment that is long and should be wrapped. # \arg Description of argument # \ret Description of return value </code></pre> <p>M-q gives me:</p> <pre><code># This is a comment that is long and # should be wrapped. \arg Description # of argument \ret Description of # return value </code></pre> <p>But I want:</p> <pre><code># This is a comment that is long and # should be wrapped. # \arg Description of argument # \ret Description of return value </code></pre> <p>I've tried setting up paragraph-start and paragraph-separate to appropriate values, but fill-paragraph still doesn't work inside a comment block. If I remove the comment markers, M-q works as I want to, so the regexp I use for paragraph-start seems to work.</p> <p>Do I have to write a custom fill-paragraph for my major mode? cc-mode has one that handles cases like this, but it's really complex, I'd like to avoid it if possible. </p>
<p>The problem was that the paragraph-start regexp has to match the entire line to work, including the actual comment character. The following elisp works for the example I gave:</p> <pre><code>(setq paragraph-start "^\\s-*\\#\\s-*\\\\\\(arg\\|ret\\).*$") </code></pre> <p>Here a page that has an example regexp for php-mode that does this: <a href="http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/" rel="nofollow noreferrer">http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/</a></p>
<p>There's other modes that have less complex functions used for <code>fill-paragraph-function</code>. Browsing through my install, it looks like the ones in ada-mode and make-mode are good examples.</p>
9,734
<p>I'm a bit confused here. Microsoft as far as I can tell claims that parametrization is the best way to protect your database from SQL injection attacks. But I find two conflicting sources of information here:</p> <p><a href="http://support.microsoft.com/kb/200190" rel="nofollow noreferrer">This page</a> says to use the ADO command object. But <a href="http://msdn.microsoft.com/en-us/library/ms679836(VS.85).aspx" rel="nofollow noreferrer">this page</a> says that the command object isn't safe for scripting. I seem to recall reading somewhere that the command object shouldn't be used in VBScript or JScript because of security vulnerabilities, but I can't seem to find that article.</p> <p>Am I missing something here, or do those two articles seem to contradict each other?</p>
<p>I could be wrong here, but I think this just means that someone could use the Command object to do bad things. I.e. it's not to be trusted if someone else is scripting it.</p> <p>See <a href="http://www.avdf.com/mar97/art_interface.html" rel="nofollow noreferrer">safe for scripting</a> in this article. Every instance that talks about this phrase online, references it as if you are marking an ActiveX control saying "This control does no I/O or only talks back to the server that it came from" but the Command object doesn't do that. It can be used to do a lot of things which could be unsafe.</p> <p>The "safe" they are talking about and the "safe" to prevent from SQL injection are two different things. The article about using the ADO Command object to parametrize your data is spot on. You should do that.</p> <p>And, Microsoft further confirms this here:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms676585(v=VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms676585(v=VS.85).aspx</a></p>
<p>I think "safe for scripting" means "safe to be run from a webpage we just retrieved from some Nigerian prince". The command object should be safe to run on the server.</p> <p>At work though, back in the day my colleagues didn't trust it so we had an in-house framework that basically did the same thing.</p>
8,180
<p>I have a couple of questions regarding VBScript and ASP Classic:</p> <ol> <li><p>What is the preferred way to access an MS SQL Server database in VBScript/ASP?</p></li> <li><p>What are best practices in regards to separating model from view from controller?</p></li> <li><p>Any other things I should know about either VBScript or ASP?</p></li> </ol> <p>If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 &amp; 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.</p>
<p>ADO is an excellent way to access a database in VBScript/Classic ASP.</p> <pre><code>Dim db: Set db = Server.CreateObject("ADODB.Connection") db.Open "yourconnectionstring -&gt; see connectionstrings.com" Dim rs: Set rs = db.Execute("SELECT firstName from Employees") While Not rs.EOF Response.Write rs("firstName") rs.MoveNext Wend rs.Close </code></pre> <p>More info here: <a href="http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/" rel="noreferrer">http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/</a></p> <p>One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems. (Reference: <a href="http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html" rel="noreferrer">http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html</a> )</p>
<p>way way back in the day when VBScript/ASP were still ok I worked in a utility company with a very mixed DB envrionment, I used to swear by this website: <a href="http://www.connectionstrings.com/" rel="nofollow noreferrer">http://www.connectionstrings.com/</a></p> <p>@michealpryor got it right</p>
4,572
<p>I'm running MAMP 1.7.2 on a Mac and I'd like to install the extension php_gd2. How do I do this? I know that on Windows using WAMP I'd simply select the <code>php_gd2</code> entry in the extensions menu to activate it. How is it done when using MAMP? I know that I can do it using MacPorts but I'd prefer not to make any changes to my default OS X PHP installation. </p>
<p>You shouldn't need to install the extension. I have 1.7.2 installed and running right now and it has GD bundled (2.0.34 compatible).</p> <p>From the MAMP start page, click on phpinfo and you should see a GD section.</p>
<p>php.ini for MAMP 1.7.2 is located: if using <strong>php5</strong>, here: <strong>/Applications/MAMP/conf/php5/php.ini</strong> if <strong>php4</strong>, here: <strong>/Applications/MAMP/conf/php4/php.ini</strong></p> <p>hope that helps...</p>
4,698
<p>I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore.</p> <p>Example:</p> <pre><code>input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] </code></pre> <p>I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.</p> <p>Any help would be greatly appreciated!</p>
<pre><code>var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); </code></pre> <p>... returns the array you're looking for.<br> Note, however:</p> <ul> <li>Bounding quotes are included, so can be removed with <code>replace(/^"([^"]+)"$/,"$1")</code> on the results.</li> <li>Spaces between the quotes will stay intact. So, if there are three spaces between <code>lorem</code> and <code>ipsum</code>, they'll be in the result. You can fix this by running <code>replace(/\s+/," ")</code> on the results.</li> <li>If there's no closing <code>"</code> after <code>ipsum</code> (i.e. an incorrectly-quoted phrase) you'll end up with: <code>['foo', 'bar', 'lorem', 'ipsum', 'baz']</code></li> </ul>
<p>One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like </p> <p><code>"hello my name is 'jon delaware smith fred' I have a 'long name'"</code>....</p> <p>A bit like the answer by AC but a bit neater...</p> <pre><code>function split(input, delimiter, joiner){ var output = []; var joint = []; input.split(delimiter).forEach(function(element){ if (joint.length &gt; 0 &amp;&amp; element.indexOf(joiner) === element.length - 1) { output.push(joint.join(delimiter) + delimiter + element); joint = []; } if (joint.length &gt; 0 || element.indexOf(joiner) === 0) { joint.push(element); } if (joint.length === 0 &amp;&amp; element.indexOf(joiner) !== element.length - 1) { output.push(element); joint = []; } }); return output; } </code></pre>
9,057
<p>I'd like to be able to see what registry keys are used for. A book on the registry would be fine as well. Info on Windows Vista changes would be great!</p>
<p>Oh, how I wish there was a single site where the registry was collectively documented by all who write values there! Keep in mind, any app can create its own set of registry keys and values, so it's not just MS who would be necessary to such an effort. Though they would be a key player!</p> <p>In the meantime, there are two MS sites I use as startng points when I need to know what a particular key/value pair do:</p> <p>Windows 2003 registry reference: <a href="http://technet.microsoft.com/en-us/library/cc778196.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc778196.aspx</a></p> <p>Windows 2000 Registry reference: <a href="http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/default.mspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc974061.aspx</a></p> <p>Keep in mind that since Windows is an evolving thing, even information about older versions can be very helpful. Also note that W2003 bears a lot of resemblance to XP. Sadly, I have not found a link to the Vista/Windows 2008 registries similar to the above.</p> <p>When you need to know what's up with a specific key, and it's not found in one of the above links, try a search of that key's full path at <a href="http://support.microsoft.com" rel="nofollow noreferrer">http://support.microsoft.com</a></p>
<p>I have used <a href="http://www.majorgeeks.com/Mystery_Behind_Windows_Registry_d415.html" rel="nofollow noreferrer">this help file</a> in the past. Very good resource</p>
8,230
<p>VC++ makes functions which are implemented within the class declaration inline functions.</p> <p>If I declare a class <code>Foo</code> as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?</p> <pre><code>class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } </code></pre>
<p>Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the &quot;inline&quot; keyword.</p> <p>In both cases it's a hint to the compiler. An &quot;inline&quot; function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.</p>
<p>To the same extent that we can make any other function inline, yes.</p>
4,154
<p>I get the following error when building my Windows Forms solution: </p> <blockquote> <p>"LC.exe" exited with code -1</p> </blockquote> <p>I use two commercial Windows Forms Libraries: Infragistics and the Gantt-Control from plexityhide.com, that's why I have licenses.licx files in my WinForms Projects. We also use Visual Sourcesafe as our Source Control.</p> <p>When the licenses.licx files are in the Projects I cannot build without the above error. However, when I exclude them from my projects the build works fine. But I need the licenses.licx files when I want to work with the commercial controls in the designer.</p> <p>This is a brand new developer machine with Windows XP SP3 (German) and Visual Studio 2005 Team Edition for Software Developers (German) with SP1. </p> <p>It's Windows XP 32-Bit by the way.</p> <p>Any suggestions?</p>
<p>Problem mainly arises due to license file. Exclude the file <code>licenses.licx</code> from your project</p>
<p>There should be a <code>license.licx</code> file in the properties folder when you use commercial components. It is often corrupted. If you clean its contents, the <code>"LC.EXE" exited with code -1</code> disappears.</p>
5,446
<p>I have a BLTouch clone (3DTouch) on my printer (Artillery Sidewinder X1). I installed it on the printer ages ago and has been working fine since. Recently, I did a BTT smart filament sensor upgrade.</p> <p>I updated and edited both the Marlin firmware and the MKS TFT28 screen firmware to get it to work with the smart filament sensor. The filament sensor runs through the screen not the motherboard so it is enabled in screen firmware instead.</p> <p>The sensor works fine and every other part of the printer is fine as well, except that after the BLTouch does a <code>G29</code> (I have it do that before every print in my start G-code, followed by an <code>M500</code>), It will not adjust the Z-axis to compensate for the unevenness of the bed. I can see the Z motors not move and I cannot feel the lead screws rotate in my hand if I touch my hand against them.</p> <p>I have been through several other forums, videos, etc. on the internet but none of them have the same problem as me and/or their solutions do not fix the problems.</p> <p>I have also tried flashing the display with the original firmware, which did not work so I guess is that I have something wrong with the firmware. I have checked and double-checked my firmware but maybe there is something I missed or do not know about that could be causing my problem.</p> <p>Firmware can be found <a href="https://github.com/Smartich0ke/Artillery-Sidewinder-X1-firmware" rel="nofollow noreferrer">here.</a></p> <hr /> <p><em>I have tried running the original firmware with changes only made to enable the BLTouch. The Z-axis does still not compensate.</em></p> <hr /> <p><em>I have also replaced the mainboard. I don’t know if that could affect the operation or not.</em></p> <hr /> <p><em>Recently, I needed to print a part so I put the default Marlin firmware using the Artillery SWX1 example in Marlin's collection of examples with modifications made only to work with the BLTouch. I can post this copy of the firmware but it is probably identical to the GitHub repo below. This way I could just print with no Z compensation, however, now whenever I try to home the printer or do a <code>G29</code>, the BLTouch doesn't deploy and it will crash into the bed. I posted an unlisted video on YouTube demonstrating the issue <a href="https://www.youtube.com/watch?v=lyyazOalsc8" rel="nofollow noreferrer">here</a>. Also note that in the video, I attempt to move the Z-axis by 1 mm, but instead, the stepper motors spin at full speed and the gantry comes zooming towards the bed.</em></p> <hr /> <p><em>I tried flashing the firmware yet again and for some reason, the BLTouch worked. it could home is and to a probing routine. I have been using the printer without the compensation and it works fine but it is really bizarre that this is happening. I know it is unlikely to solve the problem, but I am thinking of purchasing a replacement BLTouch. They are only 20 bucks to replace and I did accidental slightly bend the plastic probe before the Z stopped compensating. So is it possible the BLTouch is cactus?</em></p> <hr /> <p><em>So recently, I noticed when running a G29 T through Octoprint or Pronterface, etc. that the printer will return a set of numbers for each probing point. Does this indicate that the BLTouch has taken the measurements but the printer will not use them to compensate the bed?</em></p> <p>I have tried all the answers below.</p>
<p>So I discovered that the fade height must have been set to something really off.</p> <p>I didn't know this at the time so I thought I should set the fade height to the default 10 mm just to make sure nothing was wrong and tested it. The printer now levels and compensates perfectly!</p>
<p>Make sure <code>RESTORE_LEVELING_AFTER_G28</code> is uncommented in <code>configuration.h</code>.</p>
1,941
<p>This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity. </p> <pre><code>array( 0 =&gt; '-- SELECT --', 1 =&gt; 'Afghanistan', 2 =&gt; 'Albania', 3 =&gt; 'Algeria', 4 =&gt; 'American Samoa', 5 =&gt; 'Andorra',) </code></pre> <p>The id's need to stay intact. So making them -1 or -2 will unfortunately not work.</p>
<p>What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.</p> <p>-- Kevin Fairchild</p>
<p>You can not change the order of elements within the same array by "moving" an item around. What you can do it to build a new array that first has your favourite items and then adds anything else from the original countries array at the end:</p> <pre><code>$countries = array( 0 =&gt; '-- SELECT --', 1 =&gt; 'Afghanistan', 2 =&gt; 'Albania', 3 =&gt; 'Algeria', 4 =&gt; 'American Samoa', 5 =&gt; 'Andorra', 22 =&gt; 'Canada', 44 =&gt; 'United States',); # tell what should be upfront (by id) $favourites = array(0, 44, 22); # add favourites at first $ordered = array(); foreach($favourites as $id) { $ordered[$id] = $countries[$id]; } # add everything else $ordered += array_diff_assoc($countries, $ordered); # result print_r($ordered); </code></pre> <p><a href="http://codepad.org/YQSfToYj" rel="nofollow">Demo</a></p>
6,600
<p>Whilst starting to learn lisp, I've come across the term <em>tail-recursive</em>. What does it mean exactly?</p>
<p>Consider a simple function that adds the first N natural numbers. (e.g. <code>sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15</code>).</p> <p>Here is a simple JavaScript implementation that uses recursion:</p> <pre class="lang-js prettyprint-override"><code>function recsum(x) { if (x === 0) { return 0; } else { return x + recsum(x - 1); } } </code></pre> <p>If you called <code>recsum(5)</code>, this is what the JavaScript interpreter would evaluate:</p> <pre class="lang-js prettyprint-override"><code>recsum(5) 5 + recsum(4) 5 + (4 + recsum(3)) 5 + (4 + (3 + recsum(2))) 5 + (4 + (3 + (2 + recsum(1)))) 5 + (4 + (3 + (2 + (1 + recsum(0))))) 5 + (4 + (3 + (2 + (1 + 0)))) 5 + (4 + (3 + (2 + 1))) 5 + (4 + (3 + 3)) 5 + (4 + 6) 5 + 10 15 </code></pre> <p>Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.</p> <p>Here's a tail-recursive version of the same function:</p> <pre class="lang-js prettyprint-override"><code>function tailrecsum(x, running_total = 0) { if (x === 0) { return running_total; } else { return tailrecsum(x - 1, running_total + x); } } </code></pre> <p>Here's the sequence of events that would occur if you called <code>tailrecsum(5)</code>, (which would effectively be <code>tailrecsum(5, 0)</code>, because of the default second argument).</p> <pre class="lang-js prettyprint-override"><code>tailrecsum(5, 0) tailrecsum(4, 5) tailrecsum(3, 9) tailrecsum(2, 12) tailrecsum(1, 14) tailrecsum(0, 15) 15 </code></pre> <p>In the tail-recursive case, with each evaluation of the recursive call, the <code>running_total</code> is updated.</p> <p><em>Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support <a href="https://stackoverflow.com/questions/310974/what-is-tail-call-optimization">tail call optimization</a>. However, while tail call optimization is <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls" rel="noreferrer">part of the ECMAScript 2015 spec</a>, most JavaScript interpreters <a href="https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)" rel="noreferrer">don't support it</a>.</em></p>
<p>This question has a lot of great answers... but I cannot help but chime in with an alternative take on how to define "tail recursion", or at least "proper tail recursion." Namely: should one look at it as a property of a particular expression in a program? Or should one look at it as a property of an <em>implementation of a programming language</em>?</p> <p>For more on the latter view, there is a classic <a href="http://www.cesura17.net/~will/professional/research/papers/tail.pdf" rel="nofollow noreferrer" title="Proper Tail Recursion and Space Efficiency (PLDI 1998)">paper</a> by Will Clinger, "Proper Tail Recursion and Space Efficiency" (PLDI 1998), that defined "proper tail recursion" as a property of a programming language implementation. The definition is constructed to allow one to ignore implementation details (such as whether the call stack is actually represented via the runtime stack or via a heap-allocated linked list of frames).</p> <p>To accomplish this, it uses asymptotic analysis: not of program execution time as one usually sees, but rather of program <em>space usage</em>. This way, the space usage of a heap-allocated linked list vs a runtime call stack ends up being asymptotically equivalent; so one gets to ignore that programming language implementation detail (a detail which certainly matters quite a bit in practice, but can muddy the waters quite a bit when one attempts to determine whether a given implementation is satisfying the requirement to be "property tail recursive")</p> <p>The paper is worth careful study for a number of reasons:</p> <ul> <li><p>It gives an inductive definition of the <em>tail expressions</em> and <em>tail calls</em> of a program. (Such a definition, and why such calls are important, seems to be the subject of most of the other answers given here.)</p> <p>Here are those definitions, just to provide a flavor of the text:</p> <blockquote> <p><strong>Definition 1</strong> The <em>tail expressions</em> of a program written in Core Scheme are defined inductively as follows.</p> <ol> <li>The body of a lambda expression is a tail expression</li> <li>If <code>(if E0 E1 E2)</code> is a tail expression, then both <code>E1</code> and <code>E2</code> are tail expressions.</li> <li>Nothing else is a tail expression.</li> </ol> <p><strong>Definition 2</strong> A <em>tail call</em> is a tail expression that is a procedure call.</p> </blockquote></li> </ul> <p>(a tail recursive call, or as the paper says, "self-tail call" is a special case of a tail call where the procedure is invoked itself.)</p> <ul> <li><p>It provides formal definitions for six different "machines" for evaluating Core Scheme, where each machine has the same observable behavior <em>except</em> for the <em>asymptotic</em> space complexity class that each is in.</p> <p>For example, after giving definitions for machines with respectively, 1. stack-based memory management, 2. garbage collection but no tail calls, 3. garbage collection and tail calls, the paper continues onward with even more advanced storage management strategies, such as 4. "evlis tail recursion", where the environment does not need to be preserved across the evaluation of the last sub-expression argument in a tail call, 5. reducing the environment of a closure to <em>just</em> the free variables of that closure, and 6. so-called "safe-for-space" semantics as defined by <a href="http://www.cs.princeton.edu/~appel/papers/stack2.pdf" rel="nofollow noreferrer" title="Empirical and Analytic Study of Stack versus Heap Cost for Languages with Closures. (JFP 1996)">Appel and Shao</a>.</p></li> <li><p>In order to prove that the machines actually belong to six distinct space complexity classes, the paper, for each pair of machines under comparison, provides concrete examples of programs that will expose asymptotic space blowup on one machine but not the other.</p></li> </ul> <hr> <p>(Reading over my answer now, I'm not sure if I'm managed to actually capture the crucial points of the <a href="http://www.cesura17.net/~will/professional/research/papers/tail.pdf" rel="nofollow noreferrer" title="Proper Tail Recursion and Space Efficiency (PLDI 1998)">Clinger paper</a>. But, alas, I cannot devote more time to developing this answer right now.)</p>
5,405
<p>Are there any good references for synchronisation algorithms?</p> <p>I'm interested in algorithms that synchronize the following kinds of data between multiple users:</p> <ul> <li>Calendars</li> <li>Documents</li> <li>Lists and outlines</li> </ul> <p>I'm not just looking for synchronization of contents of directories <em>a la</em> <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">rsync</a>; I am interested in merging the data within individual files.</p>
<p>There's a high-level and very broad overview of all synchronisation algorithms in <em><a href="http://www.ece.cmu.edu/~ece845/docs/optimistic-data-rep.pdf" rel="nofollow noreferrer">Optimistic Replication</a></em> (by Yasushi Saito and Marc Shapiro, <a href="http://en.wikipedia.org/wiki/Portable_Document_Format" rel="nofollow noreferrer">PDF</a> format).</p>
<p>I would have thought that looking at any of the open-source source code control applications would give you the right idea - merging changes between files is exactly what they do...</p>
8,414
<p>In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course).</p> <p>Since I hate coding <a href="https://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete" rel="nofollow noreferrer">CRUD</a> operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any .Net-based OR/M products that can handle this scenario elegantly?</p> <p>The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting.</p> <p>Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time?</p>
<p>I've now researched what it takes to do this in both Entity Framework and LINQ to SQL and <a href="http://theruntime.com/blogs/jacob/archive/2008/08/27/changing-table-names-in-an-orm.aspx" rel="nofollow noreferrer">documented the steps required in each</a>. It's much longer than answers here tend to be so I'll be content with a link to the answer rather than duplicate it here. It's relatively involved for each, but the LINQ to SQL is the more flexible solution and also the easiest to implment.</p>
<p><a href="https://www.mindscape.co.nz/products/LightSpeed/default.aspx" rel="nofollow noreferrer">LightSpeed</a> allows you to specify an <em>INamingStrategy</em> that lets you resolve table names dynamically at runtime.</p>
3,283
<p>We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).</p> <p>I have the code snippet as below. Any help would be appreciated.</p> <pre><code>private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector) { try { if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem) { try { foreach (CommandBar c in inspector.CommandBars) { if (c.Name == "custom") { c.Delete(); } } } catch { } finally { //Add Custom Command bar and command button. CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true); myCommandBar.Visible = true; CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true); myCommandbarButton.Caption = "Add Email"; myCommandbarButton.Width = 900; myCommandbarButton.Visible = true; myCommandbarButton.DescriptionText = "This is Add Email Button"; CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton; btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick); } } } catch (System.Exception ex) { MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector"); } } </code></pre>
<p>I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <a href="http://www.add-in-express.com/add-in-net/" rel="nofollow noreferrer">http://www.add-in-express.com/add-in-net/</a>. I've used this in many projects, including some commercial software and it is completely awesome. </p> <p>It does all the Outlook (and office) integration for you so you just work with it like any toolbar and just focus on the specifics of what you need it to do. You won't ever have to worry about the Outlook extensibility at all. Highly recommended. </p> <p>Anyway, just wanted to mention it as something to look in to. It will definitely save some headaches if you're comfortable with using a 3rd party component in the project.</p>
<p>I don't know, but your code raises two questions:</p> <ol> <li><p>Why are you declaring "CommandBarControl myCommandbarButton" instead of "CommandBarButton myCommandbarButton"?</p></li> <li><p>Why are you setting the width to 900 pixels? That's huge. I never bother with this setting in Excel since it autosizes, and I'm guessing the Outlook would behave the same.</p></li> </ol>
4,387
<p>I am running into an issue I had before; can't find my reference on how to solve it.</p> <p>Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:</p> <pre><code> config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If </code></pre> <p>The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:</p> <pre><code>Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---&gt; System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---&gt; System.Security.Cryptography.CryptographicException: Object already exists </code></pre>
<p>I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the .net framework directory in a commadn prompt and run </p> <pre><code>aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}" </code></pre> <p>it gave the other user permission to access the RSA encryption key container and it then works for the other user(s).</p> <p>Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well. </p>
<p>Sounds like a permissions issue. The (new) user in question has write permissions to the app.config file? Was the previous user a local admin or power user that could have masked this problem? </p>
6,349
<p>I just saw this mentioned in Stack Overflow question <em><a href="http://web.archive.org/web/20090503103538/http://stackoverflow.com:80/questions/7975/best-css-editor" rel="nofollow noreferrer">Best WYSIWYG CSS editor</a></em> and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it?</p> <p>Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code.</p> <p>I'm using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="nofollow noreferrer">Visual Studio 2005</a>.</p>
<p>I prefer using <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="nofollow noreferrer">Firebug</a> for projects I can't use <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2008</a> on.</p>
<p>In Internet&nbsp;Explorer, select <em>View</em> -> <em>Script Debugger</em> -> <em>Open</em>. That should do it.</p>
2,981
<p>Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet"&gt; &lt;link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet"&gt; &lt;div class="input radio"&gt; &lt;fieldset&gt; &lt;legend&gt;What color is the sky?&lt;/legend&gt; &lt;input type="hidden" name="color" value="" id="SubmitQuestion" /&gt; &lt;input type="radio" name="color" id="SubmitQuestion1" value="1" /&gt; &lt;label for="SubmitQuestion1"&gt;A strange radient green.&lt;/label&gt; &lt;input type="radio" name="color" id="SubmitQuestion2" value="2" /&gt; &lt;label for="SubmitQuestion2"&gt;A dark gloomy orange&lt;/label&gt; &lt;input type="radio" name="color" id="SubmitQuestion3" value="3" /&gt; &lt;label for="SubmitQuestion3"&gt;A perfect glittering blue&lt;/label&gt; &lt;/fieldset&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here:</p> <ul> <li><a href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="nofollow noreferrer">reset-fonts-grids.css</a></li> <li><a href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="nofollow noreferrer">base-min.css</a></li> </ul> <p>Documentation for them both here : <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Yahoo! UI Library</a></p> <p>@pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed?</p>
<p>The first part of your question can be solved with just HTML &amp; CSS; you'll need to use Javascript for the second part.</p> <h3>Getting the Label Near the Radio Button</h3> <p>I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into <code>float:</code> territory):</p> <ul> <li>Use <code>&lt;br /&gt;s </code> to split the options apart and some CSS to vertically align them:</li> </ul> <pre><code>&lt;style type='text/css'&gt; .input input { width: 20px; } &lt;/style&gt; &lt;div class="input radio"&gt; &lt;fieldset&gt; &lt;legend&gt;What color is the sky?&lt;/legend&gt; &lt;input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /&gt; &lt;label for="SubmitQuestion1"&gt;A strange radient green.&lt;/label&gt; &lt;br /&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /&gt; &lt;label for="SubmitQuestion2"&gt;A dark gloomy orange&lt;/label&gt; &lt;br /&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /&gt; &lt;label for="SubmitQuestion3"&gt;A perfect glittering blue&lt;/label&gt; &lt;/fieldset&gt; &lt;/div&gt; </code></pre> <ul> <li>Follow <em>A List Apart</em>'s article: <a href="http://www.alistapart.com/articles/prettyaccessibleforms" rel="noreferrer">Prettier Accessible Forms</a></li> </ul> <h3>Applying a Style to the Currently Selected Label + Radio Button</h3> <p>Styling the <code>&lt;label&gt;</code> is why you'll need to resort to Javascript. A library like <a href="http://jquery.com" rel="noreferrer">jQuery</a> is perfect for this:</p> <pre><code>&lt;style type='text/css'&gt; .input label.focused { background-color: #EEEEEE; font-style: italic; } &lt;/style&gt; &lt;script type='text/javascript' src='jquery.js'&gt;&lt;/script&gt; &lt;script type='text/javascript'&gt; $(document).ready(function() { $('.input :radio').focus(updateSelectedStyle); $('.input :radio').blur(updateSelectedStyle); $('.input :radio').change(updateSelectedStyle); }) function updateSelectedStyle() { $('.input :radio').removeClass('focused').next().removeClass('focused'); $('.input :radio:checked').addClass('focused').next().addClass('focused'); } &lt;/script&gt; </code></pre> <p>The <code>focus</code> and <code>blur</code> hooks are needed to make this work in IE.</p>
<p>This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: <a href="http://www.webmasterworld.com/forum83/6942.htm" rel="nofollow noreferrer">http://www.webmasterworld.com/forum83/6942.htm</a></p> <pre><code>&lt;style type="text/css"&gt; .input input { float: left; } .input label { margin: 5px; } &lt;/style&gt; &lt;div class="input radio"&gt; &lt;fieldset&gt; &lt;legend&gt;What color is the sky?&lt;/legend&gt; &lt;input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /&gt; &lt;label for="SubmitQuestion1"&gt;A strange radient green.&lt;/label&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /&gt; &lt;label for="SubmitQuestion2"&gt;A dark gloomy orange&lt;/label&gt; &lt;input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /&gt; &lt;label for="SubmitQuestion3"&gt;A perfect glittering blue&lt;/label&gt; &lt;/fieldset&gt; &lt;/div&gt; </code></pre>
6,524
<p>In the WCF application that I am working on, I need to access the generated source of a particular webpage (after all the AJAX calls on the page are made).</p> <p>I have tried using <code>System.Net.WebRequest</code> but it just brings me back the original source of the page. Is there a way to execute a page and then get the source?</p> <p>Else, is there a way to execute Javascript from within a WCF service? I could use the javascript and JSON response to create the HTML page from within my webservice then!</p>
<p>You could use Javascript to traverse and pass the DOM than make a call into your WCF service from the Javascript when all the Ajax calls are complete. If you are after the data that is stored on the page after all the Ajax calls I would re-think your implementation...</p> <p>Petar</p>
<p>Well, WCF is designed to be consumed by non-browsers, so there really is no way to expect that a WCF response can contain Javascript that will be automatically executed by the client.</p>
9,611
<p>I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with <code>&lt;a&gt;</code> tags seem to truncate surrounding space:</p> <p><a href="https://i.stack.imgur.com/FDA7a.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FDA7a.gif" alt="output"></a></p> <p>Once I place my cursor over the text, it "fixes" itself:</p> <p><a href="https://i.stack.imgur.com/YFbSR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YFbSR.gif" alt="output with mouseover"></a></p> <p>Here is the HTML in the textField:</p> <pre><code>&lt;p&gt;The speeches at both the &lt;a href="http://www.demconvention.com/speeches/" target="_blank"&gt;Democratic National Convention&lt;/a&gt; last week and the &lt;a href="http://www.gopconvention2008.com/videos" target="_blank"&gt;Republican National Convention&lt;/a&gt; this week, have been, for me at least, must see TV.&lt;/p&gt; </code></pre> <p>When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.</p> <p>Any thoughts?</p>
<p>Make sure you styleSheet declares what it is supposed to do with Anchors. You are obviously using htmlText if your using CSS so soon as it sees &lt; in front of "a href" it immedietly looks for the CSS class definition for a and when it doesn't find one, the result is the different looking text you see.</p> <p>Add the following to your CSS and make sure that it has the same settings as the regular style of your text as far as style, wieght, and size. The only thing that should differ is the color.</p> <pre> a:link { font-family: sameAsReg; font-size: 12px; //Note flash omits things like px and pt. color:#FF0000; //Red } </pre> <p>Be sure that the fonts you are embedding are in the library and being instantiated into your code. Embedding each textfield through the UI is silly when you can merely load the font from the library at runtime and then you can use it anywhere. </p> <p>You can also import multiple fonts at compile time and use them in the same textfield with the use of &lt; class span="someCSSClass">Some Text &lt; /span>&lt; class span="someOtherCSSClass">Some Other Text &lt; /span></p> <p>Good luck and I hope this helps.</p>
<p>Does it make any difference if you put non-breaking spaces immediately before and after the anchor element?</p> <pre><code>&lt;p&gt; ... &amp;nbsp;&lt;a ... &gt;Link text&lt;/a&gt;&amp;nbsp; ... &lt;/p&gt; </code></pre> <p>Admittedly a workaround at best but it might buy you some time to research a real solution.</p>
7,263
<p>I am using the code snippet below, however it's not working quite as I understand it should. </p> <pre><code>public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>From reading the Javadoc about <code>readLine()</code> it says: </p> <p>Reads a line of text. A line is considered to be terminated by any one of a line feed (<code>\n</code>), a carriage return (<code>\r</code>), or a carriage return followed immediately by a linefeed. </p> <p><strong>Returns</strong>: A <code>String</code> containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached </p> <p><strong>Throws</strong>: <code>IOException</code> - If an I/O error occurs</p> <p>From my understanding of this, <code>readLine</code> should return null the first time no input is entered other than a line termination, like <code>\r</code>. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?</p>
<blockquote> <p>From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'.</p> </blockquote> <p>That is not correct. <code>readLine</code> will return <code>null</code> if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses.</p> <p>But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (<code>\n</code> or <code>\r\n</code> depending on your OS).</p> <p>So, if you want to break on both the empty string and the end of line, you should do:</p> <pre><code>while (line != null &amp;&amp; !line.equals("")) </code></pre> <p>Also, your current program should work as expected if you pipe some file directly into it, like so:</p> <pre><code>java -cp . Echo &lt; test.txt </code></pre>
<p>There's a nice <a href="http://commons.apache.org/lang/" rel="nofollow noreferrer">apache commons lang</a> library which has a good api for common :) actions. You could use statically import StringUtils and use its method isNotEmpty(String ) to get:</p> <pre><code>while(isNotEmpty(line)) { System.out.println(line); line = br.readLine(); } </code></pre> <p>It might be useful someday:) There are also other useful classes in this lib.</p>
4,467
<p>In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.<br> Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.<br> In "release" mode, you usually have all sorts of optimizations turned on.<br> Why the difference?</p>
<p>Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.<br> For example:</p> <pre><code> void foo() { 1: int i; 2: for(i = 0; i &lt 2; ) 3: i++; 4: return; </code></pre> <p>In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4</p> <p>With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)</p> <p>Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.</p> <p>Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.</p> <p>While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.<br> Here is a simplistic example:<br> <code><pre> int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device *ptr = 0; // setup hardware device while(*ptr == 1) { // loop until hardware device is done // do something } </pre></code></p> <p>With optimization off, this is straightforward, and you kinda know what to expect. However, if you turn optimization on, a couple of things might happen:</p> <ul> <li>The compiler might optimize the while block away (we init to 0, it'll never be 1)</li> <li>Instead of accessing memory, pointer access might be moved to a register->No I/O Update</li> <li>memory access might be cached (not necessarily compiler optimization related)</li> </ul> <p>In all these cases, the behavior would be drastically different and most likely wrong.</p>
<p>If you're debugging at the instruction level rather than the source level, it's an awful lot for you easier to map unoptimized instructions back to the source. Also, compilers are occasionally buggy in their optimizers.</p> <p>In the Windows division at Microsoft, all release binaries are built with debugging symbols and full optimizations. The symbols are stored in separate PDB files and do not affect the performance of the code. They don't ship with the product, but most of them are available at the <a href="http://support.microsoft.com/kb/311503" rel="nofollow noreferrer">Microsoft Symbol Server</a>.</p>
9,465
<p>I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill...</p> <p>So what kind of transformations would you do with them?</p>
<p>If you have data in columns in a text file with <code>M-x delete-rectangle</code> or <code>M-x kill-rectangle</code> you can delete a single column of data. Similarly, <code>M-x yank-rectangle</code> will paste in a column of text.</p> <p>For example, take the following text:</p> <pre><code>1. alligator alphorn 2. baboon bugle 3. crocodile cornet 4. dog didgeridoo 5. elephant euphonium 6. fish flugelhorn 7. gopher guitar </code></pre> <p>Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter <code>M-x kill-rectangle</code> and you immediately have:</p> <pre><code>1. alphorn 2. bugle 3. cornet 4. didgeridoo 5. euphonium 6. flugelhorn 7. guitar </code></pre> <p>Next put the mark at the end of the top line, add a few spaces if required and enter <code>M-x yank-rectangle</code> and ta-da! You have re-ordered the columns:</p> <pre><code>1. alphorn alligator 2. bugle baboon 3. cornet crocodile 4. didgeridoo dog 5. euphonium elephant 6. flugelhorn fish 7. guitar gopher </code></pre>
<p>In emacs24+ there's also function for numbering lines:</p> <pre><code>(rectangle-number-lines START END START-AT &amp;optional FORMAT) Insert numbers in front of the region-rectangle. START-AT, if non-nil, should be a number from which to begin counting. FORMAT, if non-nil, should be a format string to pass to `format' along with the line count. When called interactively with a prefix argument, prompt for START-AT and FORMAT. </code></pre> <p>It is binded to <kbd>C-x r N</kbd> by default. </p>
8,331
<p>I get the following error message in SQL Server 2005:</p> <pre><code>User '&lt;username&gt;' does not have permission to run DBCC DBREINDEX for object '&lt;table&gt;'. </code></pre> <p>Which minimum role do I have to give to user in order to run the command?</p>
<p>You will need to be a member of the <strong>db_ddladmin</strong> or the <strong>db_owner</strong> role AFAIK</p>
<blockquote> <p>Caller must own the table, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms181671(SQL.90).aspx" rel="nofollow noreferrer">DBCC DBREINDEX (Transact-SQL) @ MSDN</a></p>
8,077
<p>After answering on <a href="https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664">this question</a> I thought it would be nice to collect some tips &amp; tricks for working with MSVS solutions and projects. </p> <p>Here is my list: </p> <ul> <li><p>How to avoid saving new projects automatically to reduce garbage in file system.</p> <p>Uncheck <strong>Tools->Options->Projects and Solutions->Save new projects when created</strong></p></li> <li><p>How to add common file to multiple projects without copying it to project’s directory.</p> <p>Right click on a project, select <strong>Add->Existing Item->Add as link</strong> (press on small arrow on Add button)</p></li> <li><p>How to add project to solution without including it in the build process</p> <p>Right click on solution, select <strong>Add->New solution folder</strong>.<br> Right click on created folder, <strong>select Add->Add existing project</strong></p></li> <li><p>How to edit project file from Visual Studio?</p> <p>Right click on project and select <strong>Unload Project</strong>, right click on unloaded project and select <strong>Edit</strong>. Or install <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow noreferrer">Power Commands</a> and select <strong>Edit Project File</strong></p></li> <li><p>How to group files in the project tree (like auto-generated files for WinForms controls)</p> <p>Open project file for editing. </p></li> </ul> <pre> Change</pre> <pre><code>&lt;Compile Include="MainFile.cs" /&gt; &lt;Compile Include="SecondaryFile.cs" /&gt; To &lt;Compile Include="SecondaryFile.cs "&gt; &lt;DependentUpon&gt; MainFile.cs &lt;/DependentUpon&gt; &lt;/Compile&gt; </code></pre> <p>Do you have anything else to add?</p>
<p>First rule of working with Visual Studio:</p> <ul> <li><strong>Install <a href="http://www.jetbrains.com/resharper/" rel="noreferrer">ReSharper</a></strong></li> </ul>
<p>I have a tip regarding the "Track Active Item" option mentioned above, for when working with big projects. It's posted here:</p> <p><a href="https://stackoverflow.com/questions/31163/forcing-the-solution-explorer-to-select-the-file-in-the-editor-in-visual-studio#46193">Forcing the Solution Explorer to select the file in the editor in visual studio 2005</a></p>
6,793
<p>I'm getting this printing where it's not laying the plastic down very well. What could be causing this? I've printed with these settings before, and it turned out just fine. If you need any other info to properly diagnose this, let me know.</p> <p>I'm using a Robo3D R1+</p> <p>[<img src="https://i.stack.imgur.com/cT7dV.jpg" alt="Bad Print[1]"></p>
<p>I´ve seen this in my Prusa due two parameters that may vary your results depending on climate if your printer has not a temperature chamber or having a mechanical issue too.</p> <p>Lack of extrusion is due a cold filament which it can't reach the melting temperature due a fast extrusion feed; I mean in normal conditions we can print @70&nbsp;mm/s with 195&nbsp;°C but on wet or colder days is not possible so I need to slow down the speed (feed rate) with 10&nbsp;% less than normal to get @60&nbsp;mm/s or less until get a good flow with out modifying the G-code. If I try to print faster on normal conditions I will get the same lack of material due 195&nbsp;°C is a low temperature (this is an example).</p> <p>If I set the temperature 200&nbsp;°C or 210&nbsp;°C I will get a better flow and also print faster than @80&nbsp;mm/s (not affected too much on climate on 100&nbsp;% feed rate).</p> <p>For first layer I´m using an speed of 40&nbsp;mm/s to allow a good adhesion and Z height 90&nbsp;% of layer height (0.22 typically or 0.18).</p> <p>Mechanical side: The extruder is not feeding all the filament due a missing pression on the traction gear (filament slip).</p>
<p>I had this problem also. After a few hours of troubleshooting and changing the extruder temp, printing speed, layer height, and infill density. I realized that I had set the PLA diameter at 2.85 mm when it was 1.75 mm. Changing that fixed all my problems.</p>
680
<p>Are PHP variables passed by value or by reference?</p>
<p>It's by value according to the <a href="http://php.net/manual/en/functions.arguments.php" rel="noreferrer">PHP Documentation</a>.</p> <blockquote> <p>By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.</p> <p>To have an argument to a function always passed by reference, prepend an ampersand (<strong>&amp;</strong>) to the argument name in the function definition.</p> </blockquote> <pre><code>&lt;?php function add_some_extra(&amp;$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' ?&gt; </code></pre>
<p>Depends on the version, 4 is by value, 5 is by reference.</p>
2,331
<p>I have an internal enterprise app that currently consumes 10 different web services. They're consumed via old style "Web References" instead of using WCF.</p> <p>The problem I'm having is trying to work with the other teams in the company who are authoring the services I'm consuming. I found I needed to capture the exact SOAP messages that I'm sending and receiving. I did this by creating a new attribute that extends SoapExtensionAttribute. I then just add that attribute to the service method in the generated Reference.cs file. This works, but is painful for two reasons. First, it's a generated file so anything I do in there can be overwritten. Second, I have to remember to remove the attribute before checking in the file.</p> <p><strong>Is There a better way to capture the exact SOAP messages that I am sending and receiving?</strong></p>
<p>This seems to be a common question, as I just asked it and was told to look <a href="https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet">here</a>.</p> <p>You don't have to edit the generated <code>Reference.cs</code>. You can reference the extension in your application's <code>app.config</code>.</p>
<p>I used the following code is an example of how I captured SOAP requests in a application written a while back.</p> <pre><code>&lt;System.Diagnostics.Conditional("DEBUG")&gt; _ Private Sub CheckHTTPRequest(ByVal functionName As String) Dim e As New UTF8Encoding() Dim bytes As Long = Me.Context.Request.InputStream.Length Dim stream(bytes) As Byte Me.Context.Request.InputStream.Seek(0, IO.SeekOrigin.Begin) Me.Context.Request.InputStream.Read(stream, 0, CInt(bytes)) Dim thishttpRequest As String = e.GetString(stream) My.Computer.FileSystem.WriteAllText("D:\SoapRequests\" &amp; functionName &amp; ".xml", thishttpRequest, False) End Sub </code></pre> <p>Setting the conditional attribute like I did makes the compiler ignore the method call for all build types other than debug.</p> <p>Sorry for the VB, it is forced upon me.</p>
7,782
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
<p>James Bennett has a wonderful <a href="http://www.b-list.org/weblog/2008/mar/15/slides/" rel="noreferrer">set of slides</a> on how to organize reusable apps in Django.</p>
<p>An 'app' could be many different things, it all really comes down to taste. For example, let's say you are building a blog. Your app could be the entire blog, or you could have an 'admin' app, a 'site' app for all of the public views, an 'rss' app, a 'services' app so developers can interface with the blog in their own ways, etc.</p> <p>I personally would make the blog itself the app, and break out the functionality within it. The blog could then be reused rather easily in other websites.</p> <p>The nice thing about Django is that it will recognize any models.py file within any level of your directory tree as a file containing Django models. So breaking your functionality out into smaller 'sub apps' within an 'app' itself won't make anything more difficult.</p>
8,976
<p>I maintain an old PC-only application written in Delphi 7. Although Delphi has served me very well in the past I now only use it for this one application and find my skills with the language diminishing. Its syntax is too different from my 'day job' languages of Java/Ruby so it takes me longer to get into the groove of writing new code, plus it is so old I have not used many <strong>interface</strong>s so the code is not managed which seems ancient to me now!</p> <p>Many of my users are moving to Vista which may run the app in compatibility mode or may have GPF problems depending on how their PC is configured by their IT department, so I have to do some maintenance on the application. I'm wondering if I should jump to a more familiar stack.</p> <p>Is there an automated tool that will do the legwork of converting the code base to C#, leaving me to concentrate on the conversion on any non-standard components? I'm using an embedded database component called <a href="http://www.componentace.com/bde_replacement_database_delphi_absolute_database.htm" rel="noreferrer">AbsoluteDatabase</a> which is BDE compatible and using standard SQL throughout, and a native Delphi HTML browser component which can be swapped out with something from the Microsoft world.</p> <p>How good are these conversion tools?</p>
<p>I am not aware of any automated tools for making that conversion. Personally I would suggest you stick with Delphi, maybe just upgrade to a new version. I have seen a couple code DOM's that attempt to convert from Delphi to C#, but that doesn't address the library issue. </p> <p>CodeGear (formally Borland) has a tool for <a href="http://dn.codegear.com/article/32338" rel="noreferrer">going from C# to Delphi</a> that works OK. I would assume the tools that go the other direction will work the same (requiring a lot of editing). Here is a Swedish tool that works on the same CodeDOM principle to go from <a href="http://w1.311.telia.com/~u31115556/desc/programs.htm#BabbelFisken" rel="noreferrer">Delphi to C#</a> (and a number of other languages). There are others, I just can't find them right now.</p> <p>Another option would be to upgrade to a more resent version of Delphi for .NET and port your code to .NET that way. Once you get it working in Delphi for .NET (which will be pretty easy, except for the embedded DB, unless they have a .NET version) you can use <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">.NET Reflector</a> and <a href="http://www.denisbauer.com/NETTools/FileDisassembler.aspx" rel="noreferrer">File Disassembler</a> reverse the IL to C#. You will still be using the VCL, but you can use C# instead of Object pascal.</p> <p>Another similar solution would be to port it to <a href="http://remobjects.com/oxygene" rel="noreferrer">Oxygene by RemObjects</a>. I believe they have a Delphi Win32 migration path to WinForms. Then use <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">.NET Reflector</a> and <a href="http://www.denisbauer.com/NETTools/FileDisassembler.aspx" rel="noreferrer">File Disassembler</a> reverse the IL to C#. </p> <p>In short, no easy answers. Language migration is easier then library migration. A lot of it depends on what 3rd party components you used (beyond AbsoluteDatabase) and if you made any Windows API calls directly in your application.</p> <p>Another completely different option would be too look for an off shore team to maintain the application. They can probably do so cheaply. You could find someone domestically, but it would cost you more no doubt (although with the sagging dollar and poor job market you never know . . . )</p> <p>Good luck!</p>
<blockquote> <p>Many of my users are moving to Vista which may run the app in compatibility mode or may have GPF problems depending on how their PC is configured by their IT department, so I have to do some maintenance on the application. I'm wondering if I should jump to a more familiar stack.</p> </blockquote> <p>Unless you are doing something non standard, D7 applications should run fine in Vista.</p> <p>As for conversion to C#, I would think that most conversion tools would be a waste of time. A better approach may be to rewrite the application from scratch.</p>
8,418
<p>Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control? I know the inherited Control class has the event, but it's not exposed in TextBox. Is there a way to override the event handler?</p> <p>I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.</p> <p>Any suggestions?</p> <hr> <blockquote> <p>What kind of crazy mobile device do you have that has a mouse? :)</p> </blockquote> <p>Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.</p> <p>Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.</p> <hr> <blockquote> <p>According to the .Net Framework, the MouseDown Event Handler on a TextBox is supported. What happens when you try to run the code?</p> </blockquote> <p>Actually, that's only there because it inherits it from "Control", as does <em>every</em> other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.</p> <p>However, you actually can write the code:</p> <pre><code>textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown); </code></pre> <p>and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.</p>
<p>I know this answer is way late, but hopefully it ends up being useful for someone who finds this. Also, I didn't entirely come up with it myself. I believe I originally found most of the info on the OpenNETCF boards, but what is typed below is extracted from one of my applications.</p> <p>You can get a mousedown event by implementing the OpenNETCF.Windows.Forms.IMessageFilter interface and attaching it to your application's message filter.</p> <pre> static class Program { public static MouseUpDownFilter mudFilter = new MouseUpDownfilter(); public static void Main() { Application2.AddMessageFilter(mudFilter); Application2.Run(new MainForm()); } } </pre> <p>This is how you could implement the MouseUpDownFilter:</p> <pre> public class MouseUpDownFilter : IMessageFilter { List ControlList = new List(); public void WatchControl(Control buttonToWatch) { ControlList.Add(buttonToWatch); } public event MouseEventHandler MouseUp; public event MouseEventHandler MouseDown; public bool PreFilterMessage(ref Microsoft.WindowsCE.Forms.Message m) { const int WM_LBUTTONDOWN = 0x0201; const int WM_LBUTTONUP = 0x0202; // If the message code isn't one of the ones we're interested in // then we can stop here if (m.Msg != WM_LBUTTONDOWN && m.Msg != WM_LBUTTONDOWN) { return false; } // see if the control is a watched button foreach (Control c in ControlList) { if (m.HWnd == c.Handle) { int i = (int)m.LParam; int x = i & 0xFFFF; int y = (i >> 16) & 0xFFFF; MouseEventArgs args = new MouseEventArgs(MouseButtons.Left, 1, x, y, 0); if (m.Msg == WM_LBUTTONDOWN) MouseDown(c, args); else MouseUp(c, args); // returning true means we've processed this message return true; } } return false; } } </pre> <p>Now this MouseUpDownFilter will fire an MouseUp/MouseDown event when they occur on a watched control, for example your textbox. To use this filter you add some watched controls and assign to the events it might fire in your form's load event:</p> <pre> private void MainForm_Load(object sender, EventArgs e) { Program.mudFilter.WatchControl(this.textBox1); Program.mudFilter.MouseDown += new MouseEventHandler(mudFilter_MouseDown); Program.mudFilter.MouseUp += new MouseEventHandler(mudFilter_MouseUp); } void mudFilter_MouseDown(object sender, MouseEventArgs e) { if (sender == textBox1) { // do what you want to do in the textBox1 mouse down event :) } } </pre>
<p>According to the .Net Framework, the <a href="http://www.csharpfriends.com/quickstart/aspplus/samples/classbrowser/cs/classbrowser.aspx?assembly=System.Windows.Forms,%20Version=1.0.5000.0,%20Culture=neutral,%20PublicKeyToken=b77a5c561934e089&amp;namespace=System.Windows.Forms&amp;class=TextBox" rel="nofollow noreferrer">MouseDown Event Handler on a TextBox</a> is supported. What happens when you try to run the code?</p>
2,932
<p>Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter". Exactly what do these do, and what are the algorithms for implementing them?</p>
<p>Wikipedia:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/High-pass_filter" rel="noreferrer">High-pass filter</a></li> <li><a href="http://en.wikipedia.org/wiki/Low-pass_filter" rel="noreferrer">Low-pass filter</a></li> <li><a href="http://en.wikipedia.org/wiki/Band-pass_filter" rel="noreferrer">Band-pass filter</a></li> </ul> <p>These "high", "low", and "band" terms refer to <em>frequencies</em>. In high-pass, you try to remove low frequencies. In low-pass, you try to remove high. In band pass, you only allow a continuous frequency range to remain.</p> <p>Choosing the cut-off frequency depends upon your application. Coding these filters can either be done by simulating RC circuits or by playing around with Fourier transforms of your time-based data. See the wikipedia articles for code examples.</p>
<p>They are generally Electrical circuits that tend to pass parts of analog signals. High pass tends to transmit more of the high frequency parts and low pass tends to pass more of the low frequency parts.</p> <p>They can be simulated in software. A walking average can act as a low pass filter for instance and the difference between a walking average and it's input can work as a high pass filter.</p>
5,604
<p>I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries?</p>
<p>If you do not want/need to use a transaction, you could create a stored procedure that first updates the view count and then selects the values and return them to the user.</p>
<p>PostgreSQL's <a href="http://www.postgresql.org/docs/8.3/static/sql-update.html" rel="nofollow noreferrer">UPDATE</a> statement has the RETURNING clause that will return a result set like a SELECT statement:</p> <pre><code>UPDATE mytable SET views = 5 WHERE id = 16 RETURNING id, views, othercolumn; </code></pre> <p>I'm pretty sure this is not standard though. I don't know if any other databases implement it.</p> <p>Edit: I just noticed that your question has the "MySQL" tag. Maybe you should mention it in the question itself. It's a good generic database question though - I would like to see how to do it in other databases.</p>
6,525
<blockquote> <p>HyperTerminal is a program that you can use to connect to other computers, Telnet sites, bulletin board systems (BBSs), online services, and host computers, using either your modem, a null modem cable or Ethernet connection.</p> </blockquote> <p>But My main usage of Hyperterminal is to communicate with hardware through local (virtual )COM ports. I suppose it is removed in Vista for some reason.</p> <p>Are there any other tools that functions similar to Hyperterminal?</p> <p>[I am curious to know even if it is not for vista]</p>
<p>Here are two:</p> <p><a href="http://hp.vector.co.jp/authors/VA002416/teraterm.html" rel="nofollow noreferrer">Tera Term</a></p> <blockquote> <p>Tera Term (Pro) is a free software terminal emulator (communication program) for MS-Windows. It supports VT100 emulation, telnet connection, serial port connection, and so on.</p> </blockquote> <p><a href="http://www.columbia.edu/kermit/k95.html" rel="nofollow noreferrer">Kermit 95</a></p> <blockquote> <p>Kermit 95: Internet and serial communications for Microsoft Windows® 95, Windows 98, Windows ME, Windows NT (4.0 and later), Windows 2000, Windows XP, and IBM OS/2 from the Kermit Project at Columbia University, offers you text-based terminal connections to Unix, VMS, and many other kinds of hosts, allowing you to interact directly with their shells and applications, to transfer files, and, if desired, to automate interactions and file transfers with its built-in platform- and transport-independent scripting language.</p> </blockquote>
<p>Here is a better tool specificaly designed to test serial devices: <a href="http://www.caerustech.com/UDT.php" rel="nofollow noreferrer">http://www.caerustech.com/UDT.php</a> . You can save settings and commands for various devices - I use it often at work.</p>
8,586
<p>Alright, currently I have my SWF hitting a php file that will go and find all the files I specify to it, add their sizes together and return their combined sizes as one number. I then use this number with a ProgressEvent listener to determine the current percentage of files downloading for that particular section of the website.</p> <p>Pretty straightforward right? Well now using that PHP file is out of the question and I'm attempting to do everything inside the SWF instead of having it hit an outside script to get the numbers I need.</p> <p>Is there any good way to get a file's size BEFORE I start loading it into flash? I really need the preloader to be a 0 to 100% preloader so I need the total number of bytes I will be downloading before it actually starts.</p> <p>One thought I had was to just go through the array holding the file URLs, start loading them, getTotalBytes without displaying any loading, kill the load on the first tick, add up all those total bytes numbers, and then start the actual downloading process. This method seems very ugly and it will be a huge time waste as every time the user hits a pre loader on the site it will probably take a second or two to run through all the files, find their total and then actually start downloading. </p> <p>Is there a better solution to this problem without going outside of flash to get the size of those files?</p>
<p>You could do an HTTP HEAD request to the server for the files. This will return the header info (including file size) but not the actual file. You could then make a GET request to load the files.</p> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="nofollow noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a></p> <p>(Check out section 9.4 HEAD)</p> <p>What I would probably do is a two tier progress bar (with 2 progress bars). One showing overall progress (0 to 100%) and one showing per file progress (as each file is downloaded).</p> <p>That way, as long as you know the number of files to load, you can do the total progress without first having to hit the server to get the file sizes.</p> <p>mike chambers</p> <p>mesh@adobe.com</p>
<p>If it's absolutely necessary to control how the files are loaded, then I believe Mike Chambers' suggestion to make an HTTP HEAD request is the way to go.</p> <p>However, unless there's a good reason not to, I'd simply begin loading all the files at once and get my file sizes from each file's getBytesTotal method. Since Flash gets its network stack from the browser, the number of files actually loaded concurrently will conform to the (user-definable) browser settings.</p>
9,309
<p>I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value.</p> <p>I've given him a number of different reasons against this, the main ones being:</p> <ul> <li>random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build)</li> <li>if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was</li> </ul> <p>Another coworker added:</p> <ul> <li>If I am testing an exception, random values will not ensure that the test ends up in the expected state</li> <li>random data is used for flushing out a system and load testing, not for unit tests</li> </ul> <p>Can anyone else add additional reasons I can give him to get him to stop doing this?</p> <p>(Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?)</p>
<p>There's a compromise. Your coworker is actually onto something, but I think he's doing it wrong. I'm not sure that totally random testing is very useful, but it's certainly not invalid.</p> <p>A program (or unit) specification is a hypothesis that there exists some program that meets it. The program itself is then evidence of that hypothesis. What unit testing ought to be is an attempt to provide counter-evidence to refute that the program works according to the spec.</p> <p>Now, you can write the unit tests by hand, but it really is a mechanical task. It can be automated. All you have to do is write the spec, and a machine can generate lots and lots of unit tests that try to break your code.</p> <p>I don't know what language you're using, but see here:</p> <p>Java <a href="http://functionaljava.org/" rel="noreferrer">http://functionaljava.org/</a></p> <p>Scala (or Java) <a href="http://github.com/rickynils/scalacheck" rel="noreferrer">http://github.com/rickynils/scalacheck</a></p> <p>Haskell <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/" rel="noreferrer">http://www.cs.chalmers.se/~rjmh/QuickCheck/</a></p> <p>.NET: <a href="http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx" rel="noreferrer">http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx</a></p> <p>These tools will take your well-formed spec as input and automatically generate as many unit tests as you want, with automatically generated data. They use "shrinking" strategies (which you can tweak) to find the simplest possible test case to break your code and to make sure it covers the edge cases well.</p> <p>Happy testing!</p>
<p>How can your guy run the test again when it has failed to see if he has fixed it? I.e. he loses repeatability of tests.</p> <p>While I think there is probably some value in flinging a load of random data at tests, as mentioned in other replies it falls more under the heading of load testing than anything else. It is pretty much a "testing-by-hope" practice. I think that, in reality, your guy is simply not thinkng about what he is trying to test, and making up for that lack of thought by hoping randomness will eventually trap some mysterious error.</p> <p>So the argument I would use with him is that he is being lazy. Or, to put it another way, if he doesn't take the time to understand what he is trying to test it probably shows he doesn't really understand the code he is writing.</p>
5,239
<p>I have seen mechanical (micro switch), optical and magnetic(magnet + hall sensor) end stops.</p> <p>Are there any differences in how exact they switch at the right location? If so which are the most precise?</p>
<p>There are some different criteria that we should use to select a switch type:</p> <ul> <li>Precision / repeatability: does the switch trigger at the same place every time? How much spread is there in the trigger position? Do environmental changes or machine setting changes affect the trigger position?</li> <li>Contact distance: does the switch register with enough clearance to its hard-stop that the homing axis can stop before colliding with something?</li> <li>Noise-rejection: does the switch ONLY trigger when it is supposed to? </li> </ul> <p>It's important to ask, how much switch precision do we actually need? A typical 3d printer drivetrain using a microstepping stepper motor can only accurately position the moving load within +/- one 1/16th microstep (even if using finer microstepping than that) due to error-inducing effects like friction torque and magnetic detent angle error. That's around +/-0.01mm for most printers. The homing switch only needs to be as precise as the motor's positioning! Nothing is gained by having, say, 0.001mm precision endstops. </p> <p>This precision of +/-0.01mm is achievable for all types of endstop switches, with proper switch selection and configuration. </p> <p>Then there are three "standard" switching types in use in consumer/hobbyist 3d printers:</p> <ul> <li>Mechanical switches, typically dual NO/NC limit switches, which either pull up or pull down a signal pin by connecting an electrical circuit when triggered</li> <li>Optical switches, which use transistors to detect when an obstacle ("flag") is blocking the window between the emitter and sensor</li> <li>Hall effect switches, which use transistors to detect when a magnetic field exceeds a particular field strength cutoff</li> </ul> <p><strong>Mechanical Switches</strong></p> <p>Precision/repeatability depends on the switch quality, length of lever arm attached (longer increases contact distance but is worse for precision), and impact speed of the carriage with the switch. It's possible to have a good mechanical switch or a bad mechanical switch. This is typically a reasonable default choice because it is simple and cheap. </p> <p>A small mechanical switch with a short lever arm (or the lever arm removed) will generally achieve the required +/-0.01mm switching precision. Very cheap switches, high contact speeds, and long lever arms may provide inadequate resolution for Z homing or probing, but will still be adequate for low-precision X and Y homing purposes. </p> <p>Where mechanical switches tend to cause issues is in noise rejection. Different controller boards use different ways of wiring the switch: some use two wires and only send a signal when triggered. When not triggered, the signal wire is left floating or weakly pulled up by the microcontroller, while attached to a long wire that acts as an antenna to pick up EM noise. It is VERY common for heater or stepper wiring to emit nasty EMR due to the PWM current control. Two-wire endstop cables should always be run away from stepper and heater wiring. Shielding and twisting the conductors is a good idea too. </p> <p>A more robust approach is to use three-wire switches that actively pull the signal line high or low depending on the switch position. These will tend to reject noise better. </p> <p>Very cheap mechanical switches may fail within the life of the printer. However, most limit switches are rated for millions of cycles, which is unlikely to occur over any normal printer's lifespan. </p> <p>Mechanical switches are easy to align and easy to trigger by hand during troubleshooting. </p> <p><strong>Optical Switches</strong></p> <p>These rely on a flag blocking a window between a light emitter and a detector. This is non-contact and can be quite reliable, but introduces some challenges. The exact trigger position (and thus precision) may depend on ambient light levels in the room, because the sensor is monitoring for light to decrease below a specific intensity. So it may be very repeatable/precise in the short term but have some drift if the sensor moves in and out of the sun through the day.</p> <p>Switching tends to be more consistent and reliable if the flag enters the window from the side, rather than the top. </p> <p>Optical switches will actively pull the signal line high or low, and thus have good electrical noise rejection.</p> <p><strong>Hall Effect Switches</strong></p> <p>These measure the intensity of the nearby magnetic field and trigger when it exceeds a certain amount in a certain polarity. This is highly precise/repeatable (better than +/-0.01mm) and extremely resistant to noise and environmental conditions. (Unless your printer is next to something that emits large magnetic fields, anyway.) </p> <p>The hall switches I've seen have an adjustable trim pot to tune the trigger distance. That's a nice feature when trying to manually calibrate a Delta or a Z-bed for first layer height. </p> <p>The primary downside to hall switches is that they need a magnet to trigger the switch. This can be difficult to trigger by hand during troubleshooting, and requires attaching a magnet somewhere on the moving carriage. Glue works fine... but don't glue the magnet in place backwards!</p>
<p>A separate issue not addressed in other answers is that the end stops for X/Y axes have different requirements than those for the Z axis.</p> <h3>X/Y Axes</h3> <p>When the printer offers XYZ calibration (like Prusa i3 MK2), the properties of the X and Y switches play a role, since for the Z probing the probe should be centered above the fiducials (copper circles) in the bed. The XY part of the calibration measures the position of the fiducials relative to the end-stop trigger point. Then the Z calibration measures the height of each fiducial.</p> <p>When the XYZ calibration is not offered, there's usually no need for very repeatable positioning relative to the X and Y travel ends, and on most printers you could simply move the motors until they start skipping steps and call that a day - it will be accurate to within a few steps.</p> <h3>Z Axis</h3> <p>The Z axis always has a high requirement on accuracy and repeatability, and there are two general approaches to determining its position:</p> <ol> <li><p>No end-stops on the Z-axis drive system, a probe is mounted on the print head and is used to detect when the head is a certain distance above the print bed. This can be used for 9-point calibration of the bed shape and thus removes the need for bed levelling.</p> </li> <li><p>End-stops used on the Z-axis drive system. No sensor on the print head. The bed needs to be separately leveled in reference to the nozzle - thus the bed leveling screws.</p> </li> </ol> <h3>Delta Z</h3> <p>For Delta, you essentially have three Z axis drivers, and similar to the Cartesian XYZ drive, you don't need any end-stops if you have a probe on the print head. You can also perform multi-point bed leveling with such a probe.</p> <h3>Other Approaches</h3> <p>X and Y endstops become unnecessary once you use closed-loop stepper control, such as <a href="http://tropical-labs.com/index.php/mechaduino" rel="nofollow noreferrer">Mechaduino</a> or linear digital position sensors (e.g. as used in CNC machines).</p> <p>The Z probe is still useful if you don't want to perform bed leveling manually.</p>
278
<p>I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.</p>
<p>Yes, my preferred way of doing this would be via PHP. You'd have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database).</p> <p>For example - in very rough pseudo-code:</p> <p>download.php</p> <pre><code>$file = $_GET['file']; updateFileCount($file); header('Content-Type: image/jpeg'); sendFile($file); </code></pre> <p>Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - <a href="http://elouai.com/force-download.php" rel="nofollow noreferrer">this script</a> is an example of a download script which you could use)</p> <p>Note: I highly recommend avoiding the use of $_GET['file'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question.</p>
<p>You need a gateway script, like ImageDownload.php?picture=me.jpg, or something like that.</p> <p>That page whould return the image bytes, as well as logging that the image is downloaded.</p>
9,603
<p>I administrate several Oracle Apps environment, and currently check profile options in lots of environments by loading up forms in each environment, and manually checking each variable, which requires a lot of time.</p> <p>Is there a snippet of code which will list profile options and at what level and who they are applied to?</p>
<p>You'll want to query <code>APPLSYS.FND_PROFILE_OPTIONS</code> and <code>FND_PROFILE_OPTION_VALUES</code>. For a comprehensive script that you can pick up the SQL from, look here: <a href="http://tipsnscripts.com/?p=16" rel="nofollow noreferrer">http://tipsnscripts.com/?p=16</a></p>
<p>Armed with the knowledge of which tables to get (thanks Sten) and a bit of judicious editing, I have come up with a query which serves my needs:</p> <pre><code>SELECT SUBSTR(e.profile_option_name,1,30) PROFILE, DECODE(a.level_id,10001,'Site',10002,'Application',10003,'Responsibility',10004,'User') L, DECODE(a.level_id,10001,'Site',10002,c.application_short_name,10003,b.responsibility_name,10004,d.user_name) LValue, NVL(a.profile_option_value,'Is Null') Value, SUBSTR(a.last_update_date,1,25) UPDATED_DATE FROM fnd_profile_option_values a INNER JOIN fnd_profile_options e ON a.profile_option_id = e.profile_option_id LEFT OUTER JOIN fnd_responsibility_tl b ON a.level_value = b.responsibility_id LEFT OUTER JOIN fnd_application c ON a.level_value = c.application_id LEFT OUTER JOIN fnd_user d ON a.level_value = d.user_id WHERE e.profile_option_name LIKE '%&amp;1%' ORDER BY profile_option_name; </code></pre>
9,618
<p>I'm a web developer, and I want to make the web sites I develop more accessible to those using screen readers. What limitations do screen readers have that I should be most aware of, and what can I do to avoid hitting these limitations.</p> <p>This question was sparked by reading another question about <a href="https://stackoverflow.com/questions/8472/best-non-image-based-captcha">non-image based captchas</a>. In there, a commenter said that honey pot form fields (form fields hidden with CSS that only a bot would fill in), are a bad idea, because screen readers would still pick them up. </p> <p>Are screen readers really so primitive that they would read text that isn't even displayed on the screen? Ideally, couldn't you make a screen reader that waited until the page was finished loading, applied all css, and even ran Javascript onload functions before it figured out what was actually displayed, and then read that off to the user? You could probably even identify parts of the page that are menus or table of contents, and give some sort of easy way for those parts to be read exclusively or skipped over. I would think that the programming community could come up with a better solution to this problem. </p>
<blockquote> <p>Are screen readers really so primitive that they would read text that isn't even displayed on the screen?</p> </blockquote> <p>What you have to remember is that any HTML parser doesn't read the screen - it reads the source markup. Whta you see on the screen is the browser's attempt to apply CSS to the source code. It's irrelevant.</p> <blockquote> <p>You could probably even identify parts of the page that are menus or table of contents, and give some sort of easy way for those parts to be read exclusively or skipped over.</p> </blockquote> <p>You could, if there were a standard for such a thing.</p> <p>I'm not very hot on the <em>limitations</em> of screen readers, however I've read a lot about them not being ideal. The best thing I can reccommend is to put your source in order - how you'd read it. </p> <p>There are a <a href="http://www.w3schools.com/css/css_ref_aural.asp" rel="nofollow noreferrer">set of CSS properties</a> you should also look at for screen readers.</p>
<p>Have a look at <a href="http://www.w3.org/WAI/" rel="nofollow noreferrer">ARIA</a>, it's a standard for developing accessible rich-web-client applications.</p>
4,651
<p>On my Monoprice Mini Select v2 there is poor adhesion when the print head goes to put down a new layer on the bed as seen in the photo. Does anyone have a fix for this?</p> <p><a href="https://i.stack.imgur.com/NVbXE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NVbXE.jpg" alt="enter image description here"></a></p>
<p>You could try a higher bed temp, but also check to make sure bed is levelled all round as this can sometimes cause this to happen </p>
<p>Things you need to check or do: </p> <ol> <li>Use adhesion layers </li> <li>Set lower speeds at first layer.</li> <li>Increase bed temperature (try 5 degrees steps)</li> <li>Clean the bed</li> <li>Check if the bed is completely leveled up. </li> <li>Increase the thickness of the first layer. </li> </ol>
1,634
<p>I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type <code>double?</code> (or <code>Nullable&lt;double&gt;</code>). It's nullable to support the case where the user doesn't enter anything.</p> <p>The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():</p> <pre><code>this.numericTextBox1.Value = 1; </code></pre> <p>Remember 'Value' is of type <code>Nullable&lt;double&gt;</code>. This generates the following warning whenever I try to reopen the form in the Designer:</p> <pre><code>Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. </code></pre> <p>As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.</p> <p>Any suggestions?</p>
<p>Or, if you don't want the designer adding any code at all... add this to the Property.</p> <pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] </code></pre>
<p>Could it help to setting the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(VS.80).aspx" rel="nofollow noreferrer">DefaultValue attribute</a> on that property to new Nullable(1)?</p> <pre><code>[DefaultValue(new Nullable&lt;double&gt;(1))] public double? Value ... </code></pre>
8,046
<p>I work on a large Visual C++ (MFC) project in VS.NET 2005.</p> <p>I have noticed strange behavior in Visual C++ 2005. Often, I will change one line of code in a .CPP file but many .CPP files will compile as a result of this. I have never seen this until VS.NET 2005. Theortically, changing a line of code in a .CPP file should simply require recompilation of that .CPP file and re-linking of the PE file.</p> <p>What am I not understanding about the build process.</p>
<p>I found <a href="http://untidy.net/blog/2006/07/10/vs-always-builds/" rel="nofollow noreferrer">this link</a> helpful when solving a similar problem, was under pressure at the time, I tried a few things and the issue went away, for the life of me I don't know (or can't remember) which - if any - helped.</p> <p>Hope this helps</p>
<p>This is a strange bug in the VS2005 dependency behavior. To find out one suggestion would be to take the following steps:</p> <ol> <li><p>Go to <strong>Tools</strong> <strong>-> Options -> Projects and Solutions -> Build and Run -> MSBuild Project Build output Verbosity</strong> and select <strong>Detailed</strong></p></li> <li><p>Compile your project.</p></li> </ol> <p>This will give you a detailed output of the build which <strong>"may"</strong> help you arrive at a solution to your problem.</p>
6,706
<p>I am looking for a reliable technique for adding Ajax to a working ASP.NET MVC application. I want to use jQuery, and understand how to use the AJAX functionality from jQuery. </p> <p>What I need to know is how I should write my controller so that I can run the site without JavaScript, but at the same time make AJAX calls possible without the need for a separate view, separate controller, or any kind of route hack. My goal is to have a working application enhanced when JavaScript is enabled without the need to duplicate or recreate elements of the app.</p>
<p>Typically you would create your site so that it works without JavaScript being enabled. Then you would add the <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="nofollow noreferrer">unobtrusive JavaScript</a> needed to enhance your site with Ajax e.g. adding event handlers for links, form submits, etc. to make GET / POST requests and update your UI accordingly.</p> <p>The only changes you would need in your MVC app would be to handle the Ajax requests and return the data as JSON, XML, etc.</p>
<p>in your controller (derived from Controller), you can call Request.IsMvcAjaxRequest() to check if the request is a normal POST or an AJAX request. This will be true if the request was created from a an AjaxForm submit or an AsyncHyperlink. The Ajax form can be made visible by javascript, along with hiding the standard form.</p>
8,039
<p>I just got into 3D printing with an Ender-3 Pro. The test dog printed great, some custom small/thin objects printed good, and now I tried my first big object.</p> <p>Designed in Tinkercad (<a href="https://www.tinkercad.com/things/1JZRKfOQHxr" rel="nofollow noreferrer">link to my (updated) design</a>), exported to .stl, sliced and printed using Cura 4.5.0 with the default 0.2 mm profile (3 layers wall thickness) and 100% infill (for strength), with the extruder at 200 °C and bed at 50 °C. Ambient temperature had been 25-ish °C.</p> <p>The filament is a brand-new Spectrum Premium PLA (Arctic White). On its box it says it prints at 185-215 °C.</p> <p>So I got this:</p> <p><a href="https://i.stack.imgur.com/Z76pt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z76pt.jpg" alt="On the magnetic bed (front)" /></a></p> <p><a href="https://i.stack.imgur.com/7oAAI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7oAAI.jpg" alt="On the magnetic bed (back)" /></a></p> <p><a href="https://i.stack.imgur.com/xjdhi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xjdhi.jpg" alt="One leg - lower layer view" /></a></p> <p><a href="https://i.stack.imgur.com/LY4Li.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LY4Li.jpg" alt="One leg - side view" /></a></p> <p><a href="https://i.stack.imgur.com/3lLI8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3lLI8.jpg" alt="Other leg - side view" /></a></p> <p>The top (thinner) sections look OK-ish (there are some visible lines, but meh), but the transition from the bottom sections (thick) to the top has terrible layer separation and warping problems. One side of the base is actually barely holding together when I'm holding it. There is also a smaller problem mid-way at that side of the base, but it's not catastrophic.</p> <ol> <li>Why did that happen? What did I do wrong? How can I print it again and get it nice and strong?</li> </ol> <p><s>2) I have a handheld &quot;3D print pen&quot;. If I use it to fill the gaps manually, how strong will the part be? The part is meant to &quot;hug&quot; the iPad charging port, so that you can hold the iPad in the bed while charging, without pressing the cable on your body and damaging it.</s> nvm that</p> <hr /> <p>Using wall thickness of 4, layer height 0.16 mm, 30% infill and 205 °C extruder, this is my (successful) result.</p> <p><a href="https://i.stack.imgur.com/518RF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/518RF.jpg" alt="Successful result on the magnetic bed" /></a> <a href="https://i.stack.imgur.com/b3BDb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b3BDb.jpg" alt="Successful result in action" /></a></p> <hr /> <p>I also repaired that broken part. Did it for the aesthetics, but it feels quite strong.</p> <p><a href="https://i.stack.imgur.com/6t2Zb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6t2Zb.jpg" alt="Repaired with 3D pen" /></a></p>
<p>One hundred percent infill is not necessarily stronger than lower values. By having such a high infill figure, the forces on the model as it cools are magnified and not in a particularly good manner.</p> <p>Consider that you could use twenty to thirty percent infill to get the strength you require for this application, saving filament and time for the print. You've not noted how many wall layers used, but for increased strength, four to five would make for a very strong model.</p>
<p>The reason for this sort of error might be either 1) a clogged nozzel, <a href="https://www.youtube.com/watch?v=bg4sOaSvimY" rel="nofollow noreferrer">try doing this </a> 2) disturbed bed level,<a href="https://www.youtube.com/watch?v=lL3Gmy4hh3Y" rel="nofollow noreferrer">resolve this issue </a> 3) poor filament quality,</p>
1,643
<p>Let's say I have a list of categories for navigation on a web app. Rather than selecting from the database for every user, should I add a function call in the application_onStart of the global.asax to fetch that data into an array or collection that is re-used over and over. If my data does not change at all - (Edit - very often), would this be the best way?</p>
<p>You can store the list items in the Application object. You are right about the <code>application_onStart()</code>, simply call a method that will read your database and load the data to the Application object.</p> <p>In Global.asax</p> <pre><code>public class Global : System.Web.HttpApplication { // The key to use in the rest of the web site to retrieve the list public const string ListItemKey = "MyListItemKey"; // a class to hold your actual values. This can be use with databinding public class NameValuePair { public string Name{get;set;} public string Value{get;set;} public NameValuePair(string Name, string Value) { this.Name = Name; this.Value = Value; } } protected void Application_Start(object sender, EventArgs e) { InitializeApplicationVariables(); } protected void InitializeApplicationVariables() { List&lt;NameValuePair&gt; listItems = new List&lt;NameValuePair&gt;(); // replace the following code with your data access code and fill in the collection listItems.Add( new NameValuePair("Item1", "1")); listItems.Add( new NameValuePair("Item2", "2")); listItems.Add( new NameValuePair("Item3", "3")); // load it in the application object Application[ListItemKey] = listItems; } } </code></pre> <p>Now you can access your list in the rest of the project. For example, in default.aspx to load the values in a DropDownList:</p> <pre><code>&lt;asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"&gt;&lt;/asp:DropDownList&gt; </code></pre> <p>And in the code-behind file:</p> <pre><code>protected override void OnPreInit(EventArgs e) { ddList.DataSource = Application[Global.ListItemKey]; ddList.DataBind(); base.OnPreInit(e); } </code></pre>
<p>I use a static collection as a private with a public static property that either loads or gets it from the database.</p> <p>Additionally you can add a static datetime that gets set when it gets loaded and if you call for it, past a certain amount of time, clear the static collection and requery it.</p>
8,980
<p>When is it a good idea to use factory methods within an object instead of a Factory class?</p>
<p>I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.</p> <p>So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.</p> <p>So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually <em>hire</em> someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.</p> <p>In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.</p> <pre><code>public interface IThingFactory { Thing GetThing(string theString); } public class ThingFactory : IThingFactory { public Thing GetThing(string theString) { return new Thing(theString, firstDependency, secondDependency); } } </code></pre> <p>So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.</p>
<p><a href="https://i.stack.imgur.com/wAQvR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wAQvR.png" alt="enter image description here" /></a> Imagine you have a different customers with different preferences. Someone need Volkswagen another one Audi and so on. One thing is common - it's a car.</p> <p>To make our customer happy we need a factory. The factory only should know which car the customer want and will deliver such car to customer. If later we have some another car we can easily extend our car park and our factory.</p> <p>Below you can see an example (ABAP): <a href="https://i.stack.imgur.com/i2AFy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i2AFy.png" alt="enter image description here" /></a></p> <p>Now we will create an instance of the factory and listening for the customers wishes. <a href="https://i.stack.imgur.com/tUNVw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tUNVw.png" alt="enter image description here" /></a></p> <p>We created three different cars with only one create( ) method.</p> <p>Result:</p> <p><a href="https://i.stack.imgur.com/6WM4W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6WM4W.png" alt="enter image description here" /></a></p> <p>Quite often is factory pattern very usefull if you want to make the logic more clean and the program more extensible.</p>
9,525
<p>I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene in an HTML page, by doing something like:</p> <pre><code>&lt;img src="http://www.myserver.com/renderimage?scene=1&amp;x=123&amp;y=123&amp;z=123"&gt; </code></pre> <p>My question is about what technologies to use to do the rendering. In a desktop application I would quite naturally use DirectX, but I'm afraid it might not be ideal for a server-side application that would be creating images for dozens or even hundreds of users in tandem. Does anyone have any experience with this? Is there a 3D API (preferably freely available) that would be ideal for this application? Is it better to write a software renderer from scratch?</p> <p>My main concerns about using DirectX or OpenGL, is whether it will function well in a virtualized server environment, and whether it makes sense with typical server hardware (over which I have little control). </p>
<p>RealityServer by mental images is designed to do precisely what is described here. More details are available on the product page (including a downloadable Developer Edition).</p> <p><a href="http://www.migenius.com/doc/realityserver/latest/" rel="nofollow noreferrer">RealityServer docs</a></p>
<p>Check out <a href="http://www.wgpu.net" rel="nofollow">wgpu.net</a>.</p> <p>I think it's very helpful.</p>
8,982
<p>In my slicing software (Slic3r) some of the vertices/walls of my model seem to have disappeared, so that the inside of the model - which should be solid - is visible, while the surface appears as a thin shell.</p> <p>Why does this happen? Is it still safe to export the model for printing?</p>
<p>My understanding is that this occurs when the object is not a true solid. Since an STL holds the triangulation of each face and spline, the slicing engine is not &quot;smart&quot; enough to determine if there is a gap in the model and therefore if it should be filled in and how. When the slicer encounters a gap, it will either treat the endpoint as the end of the feature or navigate to the next point on the layer, resulting in either gaps in the print or extra inclusions that don't make sense.</p> <p>I've noticed that my models will fail as a true solid when I use complex solid tools such as Union, Subtract, and Trim. A lot of times there will be a rounding error in how these tools interact with the solid model that will result in a small (sometimes not very small) gap in the outer shell of the solid model. When exported to an STL, the gap is retained.</p> <p>@kareem mentioned it in their answer, but Microsoft does provide online tool(s) for 3D Printing including a solid repair tool. Use <a href="https://tools3d.azurewebsites.net/" rel="nofollow noreferrer">Microsoft 3D Tools</a> to upload your STL and try to automatically detect and fix issues with your file(s).</p>
<p>Had similar problems with blender &lt;-> Slic3r, modified a stl in blender then slic3r started acting up, showing strange faces where it shouldn't. The solution was (as suggested by @tbm0115) to solidify the exported object. Just add a Solidify modifier to the object(no need to apply), and when exporting to stl make sure to check the "Apply modifiers".</p>
121
<p>How do I create a windows application that does the following:</p> <ul> <li>it's a regular GUI app when invoked with no command line arguments</li> <li>specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate</li> <li>it must be a single executable. No cheating by making a console app exec a 2nd executable.</li> <li>assume the main application code is written in C/C++</li> <li>bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)</li> </ul> <p>In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.</p>
<p>Microsoft designed console and GUI apps to be mutually exclusive. This bit of short-sightedness means that there is no perfect solution. The most popular approach is to have two executables (eg. cscript / wscript, java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating".</p> <p>You've got two options - to make a "console executable" or a "gui executable", and then use code to try to provide the other behaviour.</p> <ul> <li>GUI executable:</li> </ul> <p><code>cmd.exe</code> will assume that your program does no console I/O so won't wait for it to terminate before continuing, which in interactive mode (ie not a batch) means displaying the next ("<code>C:\&gt;</code>") prompt and reading from the keyboard. So even if you use AttachConsole your output will be mixed with <code>cmd</code>'s output, and the situation gets worse if you try to do input. This is basically a non-starter.</p> <ul> <li>Console executable:</li> </ul> <p>Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.</p> <p>The first is that if you run it from the command line with no arguments (so you want the GUI), <code>cmd</code> will still wait for it to terminate before continuing, so that particular console will be unusable for the duration. This can be overcome by launching a second process of the same executable (do you consider this cheating?), passing the DETACHED_PROCESS flag to CreateProcess() and immediately exiting. The new process can then detect that it has no console and display the GUI.</p> <p>Here's C code to illustrate this approach:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; int main(int argc, char *argv[]) { if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process { MessageBox(0, "Hello GUI world!", "", 0); } else if (argc &gt; 1) // we have command line args { printf("Hello console world!\n"); } else // no command line args but a console - launch child process { DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS; STARTUPINFO startinfo; PROCESS_INFORMATION procinfo; ZeroMemory(&amp;startinfo, sizeof(startinfo)); startinfo.cb = sizeof(startinfo); if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &amp;startinfo, &amp;procinfo)) MessageBox(0, "CreateProcess() failed :(", "", 0); } exit(0); } </code></pre> <p>I compiled it with cygwin's gcc - YMMV with MSVC.</p> <p>The second problem is that when run from Explorer, your program will for a split second display a console window. There's no programmatic way around this because the console is created by Windows when the app is launched, before it starts executing. The only thing you can do is, in your installer, make the shortcut to your program with a "show command" of SW_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO in your program, so don't do that.</p> <p>I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplish it in your install program of choice is up to you.</p> <p>The user can still of course run your program by finding the executable in Explorer and double-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it.</p>
<p>I know my answer is coming in late, but I think the preferred technique for the situation here is the ".com" and ".exe" method. </p> <p>This may be considered "cheating" by your definition of two executables, but it requires very little change on the programmers part and can be done one and forgot about. Also this solution does not have the disadvantages of Hugh's solution where you have a console windows displayed for a split second.</p> <p>In windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will prefer a .com over a .exe.</p> <p>Then you can use tricks to have that ".com" be a proxy for the stdin/stdout/stderr and launch the same-named .exe file. This give the behavior of allowing the program to preform in a command line mode when called form a console (potentially only when certain command line args are detected) while still being able to launch as a GUI application free of a console.</p> <p>There are various articles describing this like "How to make an application as both GUI and Console application?" (see references in link below).</p> <p>I hosted a project called <a href="http://code.google.com/p/dualsubsystem/" rel="nofollow noreferrer" title="dualsubsystem">dualsubsystem on google code</a> that updates an old codeguru solution of this technique and provides the source code and working example binaries.</p> <p>I hope that is helpful!</p>
7,814
<p>Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?</p> <p>In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write <code>Fraction&lt;int&gt; frac = new Fraction&lt;int&gt;(1,2)</code> and/or <code>Fraction&lt;double&gt; frac = new Fraction&lt;double&gt;(0.1, 1.0)</code>.</p> <p>Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?</p>
<p>Here is a way to abstract out the operators that is relatively painless.</p> <pre><code> abstract class MathProvider&lt;T&gt; { public abstract T Divide(T a, T b); public abstract T Multiply(T a, T b); public abstract T Add(T a, T b); public abstract T Negate(T a); public virtual T Subtract(T a, T b) { return Add(a, Negate(b)); } } class DoubleMathProvider : MathProvider&lt;double&gt; { public override double Divide(double a, double b) { return a / b; } public override double Multiply(double a, double b) { return a * b; } public override double Add(double a, double b) { return a + b; } public override double Negate(double a) { return -a; } } class IntMathProvider : MathProvider&lt;int&gt; { public override int Divide(int a, int b) { return a / b; } public override int Multiply(int a, int b) { return a * b; } public override int Add(int a, int b) { return a + b; } public override int Negate(int a) { return -a; } } class Fraction&lt;T&gt; { static MathProvider&lt;T&gt; _math; // Notice this is a type constructor. It gets run the first time a // variable of a specific type is declared for use. // Having _math static reduces overhead. static Fraction() { // This part of the code might be cleaner by once // using reflection and finding all the implementors of // MathProvider and assigning the instance by the one that // matches T. if (typeof(T) == typeof(double)) _math = new DoubleMathProvider() as MathProvider&lt;T&gt;; else if (typeof(T) == typeof(int)) _math = new IntMathProvider() as MathProvider&lt;T&gt;; // ... assign other options here. if (_math == null) throw new InvalidOperationException( "Type " + typeof(T).ToString() + " is not supported by Fraction."); } // Immutable impementations are better. public T Numerator { get; private set; } public T Denominator { get; private set; } public Fraction(T numerator, T denominator) { // We would want this to be reduced to simpilest terms. // For that we would need GCD, abs, and remainder operations // defined for each math provider. Numerator = numerator; Denominator = denominator; } public static Fraction&lt;T&gt; operator +(Fraction&lt;T&gt; a, Fraction&lt;T&gt; b) { return new Fraction&lt;T&gt;( _math.Add( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(b.Numerator, a.Denominator)), _math.Multiply(a.Denominator, b.Denominator)); } public static Fraction&lt;T&gt; operator -(Fraction&lt;T&gt; a, Fraction&lt;T&gt; b) { return new Fraction&lt;T&gt;( _math.Subtract( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(b.Numerator, a.Denominator)), _math.Multiply(a.Denominator, b.Denominator)); } public static Fraction&lt;T&gt; operator /(Fraction&lt;T&gt; a, Fraction&lt;T&gt; b) { return new Fraction&lt;T&gt;( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(a.Denominator, b.Numerator)); } // ... other operators would follow. } </code></pre> <p>If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the <code>MathProvider&lt;T&gt;</code> implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.</p> <p><strong>Edit:</strong> Fixed definitions of add and subtract for <code>Fraction&lt;T&gt;</code>. Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: <a href="http://conal.net/papers/beautiful-differentiation/" rel="noreferrer">http://conal.net/papers/beautiful-differentiation/</a></p>
<p>.NET 7 introduces a new feature - generic math (read more <a href="https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/" rel="nofollow noreferrer">here</a> and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#generic-math-support" rel="nofollow noreferrer">here</a>) which is based on addition of <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members#static-abstract-interface-methods" rel="nofollow noreferrer"><code>static abstract</code> interface methods</a>. This feature introduces a lot of interfaces which allow to generically abstract over number types and/or math operations:</p> <pre class="lang-cs prettyprint-override"><code>class Fraction&lt;T&gt; : IAdditionOperators&lt;Fraction&lt;T&gt;, Fraction&lt;T&gt;, Fraction&lt;T&gt;&gt;, ISubtractionOperators&lt;Fraction&lt;T&gt;, Fraction&lt;T&gt;, Fraction&lt;T&gt;&gt;, IDivisionOperators&lt;Fraction&lt;T&gt;, Fraction&lt;T&gt;, Fraction&lt;T&gt;&gt; where T : INumber&lt;T&gt; { public T Numerator { get; } public T Denominator { get; } public Fraction(T numerator, T denominator) { Numerator = numerator; Denominator = denominator; } public static Fraction&lt;T&gt; operator +(Fraction&lt;T&gt; left, Fraction&lt;T&gt; right) =&gt; new(left.Numerator * right.Denominator + right.Numerator * left.Denominator, left.Denominator * right.Denominator); public static Fraction&lt;T&gt; operator -(Fraction&lt;T&gt; left, Fraction&lt;T&gt; right) =&gt; new(left.Numerator * right.Denominator - right.Numerator * left.Denominator, left.Denominator * right.Denominator); public static Fraction&lt;T&gt; operator /(Fraction&lt;T&gt; left, Fraction&lt;T&gt; right) =&gt; new(left.Numerator * right.Denominator, left.Denominator * right.Numerator); } </code></pre>
8,910
<p>What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?</p> <p>Let's say the screen looks like this ('#' represents filled area):</p> <pre><code>.................... ..............###### ##.................. .................### .................### #####............... #####............... #####............... </code></pre> <p>A probable solution is:</p> <pre><code>.................... ..............###### ##...++++++++++++... .....++++++++++++### .....++++++++++++### #####++++++++++++... #####++++++++++++... #####++++++++++++... </code></pre> <p>Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?</p> <p><strong>Shog9</strong> wrote:</p> <blockquote> <p>Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?</p> </blockquote> <p>Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?</p>
<p>@lassevk</p> <p>I found the referenced article, from DDJ: <a href="http://www.ddj.com/184410529" rel="noreferrer">The Maximal Rectangle Problem</a></p>
<p>Implementation of the stack-based algorithm in plain Javascript (with linear time complexity):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function maxRectangle(mask) { var best = {area: 0} const width = mask[0].length const depth = Array(width).fill(0) for (var y = 0; y &lt; mask.length; y++) { const ranges = Array() for (var x = 0; x &lt; width; x++) { const d = depth[x] = mask[y][x] ? depth[x] + 1 : 0 if (!ranges.length || ranges[ranges.length - 1].height &lt; d) { ranges.push({left: x, height: d}) } else { for (var j = ranges.length - 1; j &gt;= 0 &amp;&amp; ranges[j].height &gt;= d; j--) { const {left, height} = ranges[j] const area = (x - left) * height if (area &gt; best.area) { best = {area, left, top: y + 1 - height, right: x, bottom: y + 1} } } ranges.splice(j+2) ranges[j+1].height = d } } } return best; } var example = [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]] console.log(maxRectangle(example))</code></pre> </div> </div> </p>
2,887
<p>A z-axis homing issue is giving me an ulcer. I'm hoping someone can help with this.</p> <p>As per usual, after the Z endstop is triggered on my TEVO Tarantula the gantry raises a bit then slowly lowers back down to the z=0 point established by the trigger. However, the gantry is now lowering well past the point triggered by the endstop. It's forcing the hotend to press down into the bed, and I need to reset the printer to avoid any damage.</p> <p>I'm at a loss to understand why, and it's making re-leveling the bed impossible. Once I have the bed leveled, an auto home grinds the hotend into the bed.</p> <p>I've done some cable management in the past couple of days but everything is connected where it should be. The endstops are responding, I've even manually triggered them so I know they're working, but the Z refuses to stop where it should.</p> <p>I've printed at least once since organizing my cables but the bed wasn't level and then I noticed this issue when homing the Z for re-leveling.</p> <p>For context, I've had several projects print successfully recently so things <em>had</em> been working fairly well. I haven't made any changes to the Marlin software since originally setting it up months ago. I had been poking around in some settings on the unit but I'm quite sure I reverted everything I tweaked. Regardless, I can't seem to find the menu I had accessed before, and I don't think I've ever had the TEVO successfully save any customizations made via the LCD interface anyway.</p>
<p>The soldering in the Tevo components is very low quality as I replaced/resoldered most of the end-stops.</p> <p>As the gantry goes down - please ensure that the cable is not pulled over (no contact) and there is contact on the edge of the acrylic and the end-stop, also the small acrylic switch holder could bend/slip a bit. Finally, the sensor connection to the main board could be dragged by wires that are connected to the hot-end.</p> <p>To validate micro-switch behavior - lift the Z-axis (about 100mm), then set <code>home position</code> and manually trigger the end-stop switch. That shall lift the Z-axis, so then trigger again to see if that works. You will still have a plenty of time to stop the printer if the switch does not work.</p> <p>If that works, then the reason could be in slipping edge of the black acrylic plate and the micro-switch. Also validate the mechanical connection (if there is a loosening screw (the small on the switch plate)).</p>
<p>I'm not familiar with your particular model, so this may not be directly applicable.</p> <p>For many printer models, a swing thru thingiverse.com will find you a replacement z-stop switch mount that uses a threaded screw to set the z-height at which the microswitch fires. It may well be that you simply need to offset that height by a few mm to get your first layer to mate well with the print bed. </p> <p>Here are three examples, albeit for various models. <a href="https://www.thingiverse.com/thing:12488" rel="nofollow noreferrer">12488</a> , <a href="https://www.thingiverse.com/thing:1829747" rel="nofollow noreferrer">1829747</a> ,<br> <a href="https://www.thingiverse.com/thing:2856144" rel="nofollow noreferrer">2856144</a></p>
1,064
<p>When Visual Studio (2005) has <em>Options -> Text Editor -> C/C++ -> Tabs -> Indenting</em> set to Smart it will automatically indent code blocks and line up squiggly brackets, {}, as expected. However, if you hit enter inside a code block, move the cursor to another line, and then move it back, the inserted tabs are gone and the cursor is positioned all the way to the left. Is there a way to set Visual Studio to keep these tabs?</p>
<p>As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and you'll never see it there until you return to that line.</p> <p>Once VS determines that you've edited a line of text, it won't automatically modify it for you (at least, not in that way that you've described).</p>
<p>This is an annoyance to myself as well. Anytime the code is reformatted the blank lines are de-tabbed. You might look at this: <a href="http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7</a> it's not exactly a solution but a step in the right direction</p>
9,956
<pre><code>std::vector&lt;int&gt; ints; // ... fill ints with random values for(std::vector&lt;int&gt;::iterator it = ints.begin(); it != ints.end(); ) { if(*it &lt; 10) { *it = ints.back(); ints.pop_back(); continue; } it++; } </code></pre> <p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p> <p>Do you have some links about that?</p>
<p>The call to <a href="http://en.cppreference.com/w/cpp/container/vector/pop_back" rel="noreferrer"><code>pop_back()</code></a> removes the last element in the vector and so the iterator to that element is invalidated. The <code>pop_back()</code> call does <em>not</em> invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":</p> <blockquote> <p>Inserting or removing elements invalidates references, pointers, and iterators that refer to the following element. If an insertion causes reallocation, it invalidates all references, iterators, and pointers.</p> </blockquote>
<p>Check out the information <a href="http://www.cplusplus.com/reference/stl/vector/pop_back.html" rel="nofollow noreferrer">here (cplusplus.com)</a>:</p> <blockquote> <p><strong>Delete last element</strong></p> <p>Removes the last element in the vector, effectively reducing the vector size by one and invalidating all iterators and references to it.</p> </blockquote>
8,773
<p>I'm trying to get the <strong>GWTShell</strong> mode to load my <em>context.xml</em> file in which my database is described.</p> <p>The only usable info can be found <a href="http://gwt-maven.googlecode.com/svn/docs/maven-googlewebtoolkit-plugin/configure_tomcatlite.html" rel="nofollow noreferrer">here</a>, but this doesn't seem to work for the <em>context.xml</em> part.</p>
<p>I'm using Eclipse with Cypal Studio (previously called Googlipse). If there is any other <em>better</em> plugin for Eclipse please recommend it.</p> <p>As the Shell mode uses a Tomcat instance, which is the same target server we are using in the final deployment, it should be possible to achieve (or fake) a similar behaviour. </p>
<p>As of version 1.4, I have been running all my server side code, in my container of choice (Glassfish) and hooking up the GWTShell to that. Are you using Netbeans, Eclipse or something else? The Netbeans plugin gwt4nb does this for you out of the box, you just have to start your web project in debug mode. I'm sure the GWT plugin for Eclipse does the same thing.</p> <p>I realise this doesn't directly answer your question -> but my question is, is there a reason you're trying to get GWT to pick up your database settings and not just running your project as normal instead. I find this much better and robust way of running the GWTShell.</p> <p>Edit: Sorry I don't really use Eclipse, so I can't help you with plugins for it. I find Netbeans far superior for J2EE/web type projects. It's a bit slower, but far more functional. The plugin for that is called 'GWT4NB', it's free and it will set up your ant script in such a way that you just have to right-click on your web project and choose debug. I can understand if you don't want to switch IDEs though.</p>
8,451
<p>I always thought Java uses <strong>pass-by-reference</strong>.</p> <p>However, I've seen <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">a blog post</a> that claims that Java uses <strong>pass-by-value</strong>.</p> <p>I don't think I understand the distinction they're making.</p> <p>What is the explanation?</p>
<p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; have special, <a href="https://en.wikipedia.org/w/index.php?title=Pass-by-value" rel="noreferrer">precisely defined</a> meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.</p> <p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; are talking about <em>variables.</em> Pass-by-value means that the <em>value</em> of a variable is passed to a function/method. Pass-by-reference means that a <em>reference</em> to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.</p> <p>By those definitions, Java is always <strong>pass-by-value</strong>. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called <em>references</em> which are passed-by-value as well. This terminology and semantics easily confuse many beginners.</p> <p>It goes like this:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog(&quot;Max&quot;); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the &quot;Max&quot; dog when foo(...) returns aDog.getName().equals(&quot;Max&quot;); // true aDog.getName().equals(&quot;Fifi&quot;); // false aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals(&quot;Max&quot;); // true // change d inside of foo() to point to a new Dog instance &quot;Fifi&quot; d = new Dog(&quot;Fifi&quot;); d.getName().equals(&quot;Fifi&quot;); // true } </code></pre> <p>In the example above <code>aDog.getName()</code> will still return <code>&quot;Max&quot;</code>. The value <code>aDog</code> within <code>main</code> is not changed in the function <code>foo</code> with the <code>Dog</code> <code>&quot;Fifi&quot;</code> as the object reference is passed by value. If it were passed by reference, then the <code>aDog.getName()</code> in <code>main</code> would return <code>&quot;Fifi&quot;</code> after the call to <code>foo</code>.</p> <p>Likewise:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog(&quot;Max&quot;); Dog oldDog = aDog; foo(aDog); // when foo(...) returns, the name of the dog has been changed to &quot;Fifi&quot; aDog.getName().equals(&quot;Fifi&quot;); // true // but it is still the same dog: aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals(&quot;Max&quot;); // true // this changes the name of d to be &quot;Fifi&quot; d.setName(&quot;Fifi&quot;); } </code></pre> <p>In the above example, <code>Fifi</code> is the dog's name after call to <code>foo(aDog)</code> because the object's name was set inside of <code>foo(...)</code>. Any operations that <code>foo</code> performs on <code>d</code> are such that, for all practical purposes, they are performed on <code>aDog</code>, but it is <strong>not</strong> possible to change the value of the variable <code>aDog</code> itself.</p> <p>For more information on pass by reference and pass by value, consult the following answer: <a href="https://stackoverflow.com/a/430958/6005228">https://stackoverflow.com/a/430958/6005228</a>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.</p>
<p>Every single answer here is tying to take pass pointer by reference from other languages and show how it is impossible to do in Java. For whatever reason nobody is attempting to show how to implement pass-object-by-value from other languages.</p> <p>This code shows how something like this can be done:</p> <pre><code>public class Test { private static void needValue(SomeObject so) throws CloneNotSupportedException { SomeObject internalObject = so.clone(); so=null; // now we can edit internalObject safely. internalObject.set(999); } public static void main(String[] args) { SomeObject o = new SomeObject(5); System.out.println(o); try { needValue(o); } catch(CloneNotSupportedException e) { System.out.println(&quot;Apparently we cannot clone this&quot;); } System.out.println(o); } } public class SomeObject implements Cloneable { private int val; public SomeObject(int val) { this.val = val; } public void set(int val) { this.val = val; } public SomeObject clone() { return new SomeObject(val); } public String toString() { return Integer.toString(val); } } </code></pre> <p>Here we have a function <code>needValue</code> and what it does is right away create a clone of the object, which needs be implemented in the class of the object itself and the class needs to be marked as <code>Cloneable</code>. It is not essential to set <code>so</code> to <code>null</code> after that, but i have done so here to show that we are not going to be using that reference after that.</p> <p>It may well be that Java does not have pass-by-reference semantics, but to call the language &quot;pass-by-value&quot; is along the lines of wishful thinking.</p>
6,171
<p>I run a non-profit designed to expose high school students to 3D printing and entrepreneurship. The concept is based on pop-up shop-style sales of 3D printed trinkets, toys, artifacts, etc.</p> <p>Can I legally sell models we print from the many open source and publicly available museum collections that are available on the internet? Example - a 3D scan of Rodin's &quot;The Thinker&quot; or the British Museum's publically available .stl of the Rosetta stone.</p> <p>It is my understanding that these artifacts are in the public domain as they are much older than 1930 though the .stl scans may not be?</p> <p>Keep in mind I am a fully licensed 501c3 non-profit organization.</p> <p>Wondering if there are any good places to find fully licensed models that we could sell without having to worry about copyright infringement.</p>
<h1>Not all museum pieces are out of copyright!</h1> <p>Let's start with a general primer: an Artwork is out of copyright if it was made by someone that died more than about 70 years ago. For items created by companies a different rule applies.</p> <p>When the copyright on an artwork lapses, anyone can reproduce it.</p> <p>However, not all items in museums are out of copyright: Auguste Rodin died in 1917 and thus is <em>free game</em>, but Eva Hesse only died in 1970, so her works will only be out of copyright in 2040 or later!</p> <h2>STLs are all under copyright!</h2> <p>However, the STLs are <strong>not</strong> the artwork, they are a separate artwork that was made by someone that most likely is very much still alive - or at least are still in the protection period.</p> <p>To use the STL you thus need to acquire a license <strong>from the author of the STL.</strong> Most freely available STLs are with a license that is &quot;Non commercial&quot; and bans commercial use, so you need to inquire about a commercial license.</p>
<p>Just read the license that comes with the STL. Most I have seen prohibit commercial use without permission.</p> <blockquote> <p>good places to find fully licensed models that we could sell without having to worry about copyright infringement.</p> </blockquote> <p>Draw them yourself and there's no issues. Or buy the commercial licenses.</p>
2,159
<p>I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish <em>would not</em> be suggested by SpotLight as potential search candidates. I'm not looking for <code>example.log</code>, I'm looking for <code>example.tex</code>!</p> <p>So can Spotlight be configured to ignore, say, all <code>.log</code> files?</p> <p>(I know, I know; I should just use QuickSilver instead…)</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41295">diciu</a> That's an interesting answer. The problem in my case is this:</p> <blockquote> <p>Figure out which importer handles your type of file</p> </blockquote> <p>I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux, .glo, .out, whatever) I think it's improbable that there's an importer that's <em>trying</em> to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.)</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41342">diciu</a> again: <code>TextImporterDontImportList</code> sounds very promising; I'll head off and see if anything comes of it.</p> <p>Like you say, it does seem like the whole UTI system doesn't really allow <em>not</em> searching for something.</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41377">Raynet</a> Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway <code>:)</code> )</p>
<p>@Will - these things that define types are called <a href="http://developer.apple.com/macosx/uniformtypeidentifiers.html" rel="nofollow noreferrer">uniform type identifiers</a>.</p> <p>The problem is they are a combination of extensions (like .txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension.</p> <p>RichText.mdimporter is <i>probably</i> the importer that imports your text file. This should be easily verified by running mdimport in debug mode on one of the files you don't want indexed:</p> <pre> cristi:~ diciu$ echo "All work and no play makes Jack a dull boy" > ~/input.txt cristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter. </pre> <p>The type that matches in my example is public.plain-text.</p> <p>I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in .log).</p> <p>Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever):</p> <pre> cristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text TextImporterDontImportList </pre>
<p>The only option probably is to have them not indexed by spotlight as from some reason you cannot do negative searches. You can search for files with specifix file extension, but you cannot not search for ones that don't match.</p> <p>You could try making those files invisible for Finder, Spotlight won't index invisible files. Command for setting the kIsInvisible flag on files is:</p> <p>SetFile -a v [filename(s)]</p>
6,257
<p>By graphing I mean bar charts, pie charts, line graphs, that sort of thing. I've used a couple over the years, but what is your favourite and why?</p> <p>One tool per answer please (to make the voting easier :o)</p>
<p>I like <a href="http://zedgraph.org/wiki/index.php?title=Main_Page" rel="noreferrer">ZedGraph</a> it is a free library and produces quality output. You can tweak the anti-aliasing to work the way it looks best to you and it supports a variety of charts and graphs.</p>
<p><a href="http://www.steema.com/products/teechart/whatsnew.html" rel="nofollow noreferrer">TeeChart</a>. I've been using this tool for a few years now, although it is not free (~500€) it is packed with features.<br></p> <p>What I prefer:</p> <ul> <li>axes scale automatically</li> <li>automatic colours for different series</li> <li>zoom by selecting an area with the mouse</li> <li>delivered with excellent code examples of all the features</li> <li>and web support for ASP.NET</li> </ul>
9,529
<p>How many possible combinations of the variables a,b,c,d,e are possible if I know that:</p> <pre><code>a+b+c+d+e = 500 </code></pre> <p>and that they are all integers and >= 0, so I know they are finite.</p>
<p>@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose <code>a</code> as <code>1</code> and <code>b</code> as <code>2</code>, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing <code>a</code> as <code>2</code> and <code>b</code> as <code>1</code>. (The number of such coincidences explodes as the numbers grow.)</p> <p>The traditional way to attack such a problem is <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="nofollow noreferrer">dynamic programming</a>: build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of <em>n</em> variables add up to <em>k</em>?" is the sum of the solutions to "how many combinations of <em>n-1</em> variables add up to <em>j</em>?" with 0 &lt;= <em>j</em> &lt;= <em>k</em>). </p> <pre><code>public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j &lt; tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i &lt; tab.length; ++i ) { for( int j=0; j &lt; tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 &lt;= k &lt;= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k &lt;= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum]; } </code></pre> <pre> $ time java Combos 2656615626 real 0m0.151s user 0m0.120s sys 0m0.012s </pre>
<p>Including negatives? Infinite.</p> <p>Including only positives? In this case they wouldn't be called "integers", but "naturals", instead. In this case... I can't really solve this, I wish I could, but my math is too rusty. There is probably some crazy integral way to solve this. I can give some pointers for the math skilled around.</p> <p>being x the end result, the range of a would be from 0 to x, the range of b would be from 0 to (x - a), the range of c would be from 0 to (x - a - b), and so forth until the e.</p> <p>The answer is the sum of all those possibilities.</p> <p>I am trying to find some more direct formula on Google, but I am really low on my Google-Fu today...</p>
8,444
<p>I'm trying to write a regular expression that validates a date. The regex needs to match the following</p> <ul> <li>M/D/YYYY</li> <li>MM/DD/YYYY</li> <li>Single digit months can start with a leading zero (eg: 03/12/2008)</li> <li>Single digit days can start with a leading zero (eg: 3/02/2008)</li> <li>CANNOT include February 30 or February 31 (eg: 2/31/2008)</li> </ul> <p>So far I have </p> <pre><code>^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ </code></pre> <p>This matches properly EXCEPT it still includes 2/30/2008 &amp; 2/31/2008.</p> <p>Does anyone have a better suggestion?</p> <p><strong>Edit:</strong> I found <a href="http://regexlib.com/REDetails.aspx?regexp_id=112" rel="noreferrer">the answer</a> on RegExLib</p> <pre><code>^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ </code></pre> <p>It matches all valid months that follow the MM/DD/YYYY format.</p> <p>Thanks everyone for the help.</p>
<p>This is not an appropriate use of regular expressions. You'd be better off using</p> <pre><code>[0-9]{2}/[0-9]{2}/[0-9]{4} </code></pre> <p>and then checking ranges in a higher-level language.</p>
<p>A slightly different approach that may or may not be useful for you.</p> <p>I'm in php.</p> <p>The project this relates to will never have a date prior to the 1st of January 2008. So, I take the 'date' inputed and use strtotime(). If the answer is >= 1199167200 then I have a date that is useful to me. If something that doesn't look like a date is entered -1 is returned. If null is entered it does return today's date number so you do need a check for a non-null entry first.</p> <p>Works for my situation, perhaps yours too? </p>
7,422
<p>I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing). </p> <p>However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call).</p>
<p>Singletons are evil, what do you expect? ;)</p> <p>Perhaps the most comprehensive approach would be to load the bulk of the applet in a different class loader (use java.net.URLClassLoader.newInstance). Then use a WeakHashMap to associate class loader with an applet. If you could split most of the code into a common class loader (as a parent of each per-applet class loader) and into the normal applet codebase, that would be faster but more work.</p> <p>Other hacks:</p> <p>If you have access to any component, you can use Component.getParent repeatedly or SwingUtilities.getRoot.</p> <p>If you are in a per-applet instance thread, then you can set up a ThreadLocal.</p> <p>From the EDT, you can read the current event from the queue (java.awt.EventQueue.getCurrentEvent()), and possibly find a component from that. Alternatively push an EventQueue with a overridden dispatchEvent method.</p>
<p>If I understand you correctly, the idea is to get a different "singleton" object for each caller object or "context". One thing you can do is to create a thread-local global variable where you write the ID of the current context. (This can be done with AOP.) Then in the singleton getter, the context ID is fetched from the thread-local to use as a key to the correct "singleton" instance for the calling context. </p> <p>Regarding AOP there should be no problem using it in applets since, depending on your point-cuts, the advices are woven at compile time and a JAR is added to the runtime dependencies. Hence, no special evidence of AOP should remain at run time.</p>
2,890
<p>I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!</p> <p>Let's say I have a standard business object "Contact" in the <em>Business</em> namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.</p> <p>Now, I also then create a utility method that takes a "Contact" and does some magic with it, like <code>Utils.BuyContactNewHat()</code> say. Which of course takes the Contact of type <code>Business.Contact</code>.</p> <p>I then go back to my client application and want to utilise the <code>BuyContactNewHat</code> method, so I add a reference to my <em>Utils</em> namespace and there it is. However, a problem arises with:</p> <pre><code>Contact c = MyWebService.GetContact("Rob); Utils.BuyContactNewHat(c); // &lt;&lt; Error Here </code></pre> <p>Since the return type of <code>GetContact</code> is of <code>MyWebService.Contact</code> and not <code>Business.Contact</code> as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.</p> <p>So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.</p>
<p>You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.</p> <p>Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying.</p>
<p>I would recommend that you look at writing a Schema Importer Extension, which you can use to control proxy code generation. This approach can be used to (gracefully) resolve your problem without kludges (such as copying around objects from one namespace to another, or modifying the proxy generated reference.cs class only to have it replaced the next time you update the web reference).</p> <p>Here's a (very) good tutorial on the subject:</p> <p><a href="http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wsproxy.mspx" rel="nofollow noreferrer">http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wsproxy.mspx</a></p>
2,842
<p>Does anyone have battle stories to share trying to use Visual Studio to develop applications for Unix? And I'm not talking using .NET with a Mono or Wine virtual platform running beneath.</p> <p>Our company has about 20 developers all running Windows XP/Vista and developing primarily for Linux &amp; Solaris. Until recently we all logged into a main Linux server and modified/built code the good old fashioned way: Emacs, Vi, dtpad - take your pick. Then someone said, "hey - we're living in the Dark Ages, we should be using an IDE".</p> <p>So we tried out a few and decided that Visual Studio was the only one that would meet our performance needs (yes, I'm sure that IDE X is a very nice IDE, but we chose VS).</p> <p>The problem is, how do you setup your environment to have the files available locally to VS, but also available to a build server? We settled with writing a Visual Studio plugin - it writes our files locally and to the build server whenever we hit "Save" and we have a bit fat "sync" button that we can push when our files change on the server side (for when we update to the latest files from our source control server). </p> <p>The plugin also uses Visual Studio's external build system feature that ultimately just ssh's into the build server and calls our local "make" utility (which is Boost Build v2 - has great dependency checking, but is <em>really</em> slow to start as a result i.e. 30-60 seconds to begin). The results are piped back into Visual Studio so the developer can click on the error and be taken to the appropriate line of code (quite slick actually). The build server uses GCC and cross-compiles all of our Solaris builds.</p> <p>But even after we've done all this, I can't help but sigh whenever I start to write code in Visual Studio. I click a file, start typing, and VS chugs to catch up with me.</p> <p>Is there anything more annoying than having to stop and wait for your tools? Are the benefits worth the frustration?</p> <p>Thoughts, stories, help?</p>
<p><em>VS chugs to catch up with me.</em> <br> Hmmm ... you machine needs more memory &amp; grunt. Never had performance problems with mine.</p> <p>I've about a decade's experience doing exactly what you're proposing, most of it in the finance industry, developing real-time systems for customers in the banking, stock exchanges, stock brokerage niches.</p> <p>Before proceeding further, I need to confess that all this was done in VS6 + CVS, and of late, SVN.</p> <p><strong>Source Code Versioning</strong> </p> <p>Developers have separate sourcesafe repositories so that they can store their work and check it packages of work at logical milestones. When they feel they want to do an integration test, we run a script that checks it into SVN. </p> <p>Once checked into SVN, we've a process that kicks off that will automatically generate relevant makefiles to compile them on the target machines for continuous integration.</p> <p>We've another set of scripts that synchs new stuff from SVN to the folders that VS looks after. There's a bit of gap because VS can't automatically pick up new files; we usually handle that manually. This only happens regularly the first few days of the project.</p> <p>That's an overview of how we maintain codes. I have to say, I've probably glossed over some details (let me know if you're interested).</p> <p><strong>Coding</strong></p> <p>From the coding aspect, we rely heavily on the pre-processors (i.e. #define, etc) and flags in the makefile to shape compilation process. For cross platform portability, we use GCC. A few times, we were force to use aCC on HP-UX and some other compilers, but we did not have much grief. The only thing that is a constant pain, is that we had to watch out for thread heap spaces across platforms. The compiler does not spare us from that.</p> <p><strong>Why?</strong></p> <p>The question is usually, "Why the h*ll would you even what to have such a complicated way of development?". Our answer is usually another question that goes, "Have you any clue how insane it is to debug a multi-threaded application by examining the core dump or using gdb?". Basically, the fact that we can trace/step through each line of code when you're debugging an obscure bug, makes it all worth the effort!</p> <p>Plus!... VS's intellisense feature makes it so easy to find the method/attribute belonging to classes. I also heard the VS2008 has refactoring capabilities. I've shifted my focus to Java on Eclipse that has both features. You'd be more productive focusing coding business logic rather than devote energy making your mind do stuff like <em>remember</em>!</p> <p>Also! ... We'd end up with a product that can run on both Windows and Linux!</p> <p>Good luck!</p>
<p>We are using a similar solution to what you described.</p> <p>We have our code stored on the Windows side of the world and UNIX (QNX 4.25 to be exact) has access though an NFS mount (thanks to UNIX services for Windows). We have an ssh into UNIX to run make and the pipe to output into VS. Accessing the code is fast, builds are a little slower than before, but our longest compile is currently less than two minutes, not a big deal.</p> <p>Using VS for UNIX development has been worth the effort to set it up, because we now have IntelliSense. Less typing = happy developer.</p>
3,640
<p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p> <p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p> <hr/> <p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p> <hr/> <p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p> <hr/> <p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
<p>Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.</p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; public class MyTextBox : TextBox { private bool mScrollbars; public MyTextBox() { this.Multiline = true; this.ReadOnly = true; } private void checkForScrollbars() { bool scroll = false; int cnt = this.Lines.Length; if (cnt &gt; 1) { int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y; if (pos0 &gt;= 32768) pos0 -= 65536; int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y; if (pos1 &gt;= 32768) pos1 -= 65536; int h = pos1 - pos0; scroll = cnt * h &gt; (this.ClientSize.Height - 6); // 6 = padding } if (scroll != mScrollbars) { mScrollbars = scroll; this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None; } } protected override void OnTextChanged(EventArgs e) { checkForScrollbars(); base.OnTextChanged(e); } protected override void OnClientSizeChanged(EventArgs e) { checkForScrollbars(); base.OnClientSizeChanged(e); } } </code></pre>
<p>What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.</p> <p>For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.</p> <p>I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.</p> <p>The following seems to work pretty well, with or without a border, and it works with WordWrap on.</p> <p>Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.</p> <pre><code>public class TextBoxAutoScroll : TextBox { public void AutoScrollVertically(bool recalculateOnResize = false) { SuspendLayout(); if (recalculateOnResize) { Resize -= OnResize; Resize += OnResize; } float linesHeight = 0; var borderStyle = BorderStyle; BorderStyle = BorderStyle.None; int textHeight = PreferredHeight; try { using (var graphics = CreateGraphics()) { foreach (var text in Lines) { var textArea = graphics.MeasureString(text, Font); if (textArea.Width &lt; Width) linesHeight += textHeight; else { var numLines = (float)Math.Ceiling(textArea.Width / Width); linesHeight += textHeight * numLines; } } } if (linesHeight &gt; Height) ScrollBars = ScrollBars.Vertical; else ScrollBars = ScrollBars.None; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } finally { BorderStyle = borderStyle; ResumeLayout(); } } private void OnResize(object sender, EventArgs e) { m_timerResize.Stop(); m_timerResize.Tick -= OnDelayedResize; m_timerResize.Tick += OnDelayedResize; m_timerResize.Interval = 475; m_timerResize.Start(); } Timer m_timerResize = new Timer(); private void OnDelayedResize(object sender, EventArgs e) { m_timerResize.Stop(); Resize -= OnResize; AutoScrollVertically(); Resize += OnResize; } } </code></pre>
9,879
<p>How do I convert function input parameters to the right type?</p> <p>I want to return a string that has part of the URL passed into it removed.</p> <p><strong>This works, but it uses a hard-coded string:</strong></p> <pre><code>function CleanUrl($input) { $x = "http://google.com".Replace("http://", "") return $x } $SiteName = CleanUrl($HostHeader) echo $SiteName </code></pre> <p><strong>This fails:</strong></p> <pre><code>function CleanUrl($input) { $x = $input.Replace("http://", "") return $x } Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'. At M:\PowerShell\test.ps1:13 char:21 + $x = $input.Replace( &lt;&lt;&lt;&lt; "http://", "") </code></pre>
<p>The concept here is correct.</p> <p>The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.</p> <p>PowerShell does have <a href="https://technet.microsoft.com/en-us/library/hh847759.aspx" rel="nofollow noreferrer">a replace operator</a>, so you could make your function into</p> <pre><code>function CleanUrl($url) { return $url -replace 'http://' } </code></pre>
<p>This worked for me:</p> <pre><code>function CleanUrl($input) { return $input.Replace("http://", "") } </code></pre>
3,586
<p>I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?</p>
<p>When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.</p>
<p>The Form class doesn't provide any kind of reference to the 'parent' Form, so there's no direct way to access the parent (unless it happens to be the MDI parent as well, in which case you could access it through the MDIParent property). You'd have to pass a reference to the parent in the constructor of the child, or a property and then remember to set it, and then use that reference to force the parent to close.</p>
6,223
<p>I'm using <b>Struts 2</b>.</p> <p>I'd like to return from an Action to the page which invoked it.</p> <p>Say I'm in page <strong>x.jsp</strong>, I invoke Visual action to change CSS preferences in the session; I want to return to <strong>x.jsp</strong> rather than to a fixed page (i.e. <strong>home.jsp</strong>)<br/></p> <p>Here's the relevant <strong>struts.xml</strong> fragment: <br/></p> <pre> &lt;action name="Visual" class="it.___.web.actions.VisualizationAction"&gt; &lt;result name="home"&gt;/pages/home.jsp&lt;/result&gt; &lt;/action&gt; </pre> <p>Of course my <code>VisualizationAction.execute()</code> returns <strong>home</strong>.</p> <p>Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?<br/></p> <p>Must I use a more involved method (i.e. extracting the request page and forwarding to it)?<br/></p> <p>T.I.A.</p>
<p>You can use a dynamic result in struts.xml. For instance:</p> <pre><code>&lt;action name="Visual" class="it.___.web.actions.VisualizationAction"&gt; &lt;result name="next"&gt;${next}&lt;/result&gt; &lt;/action&gt; </code></pre> <p>Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to.</p> <p>There is a nicer explanation on this post: <a href="https://stackoverflow.com/questions/173846/struts2-how-to-do-dynamic-url-redirects">Stack Overflow</a></p>
<p>I prefer the way when you navigating users by particular actions. </p> <p><a href="http://domain.com/myAction.action" rel="nofollow noreferrer">http://domain.com/myAction.action</a></p> <p>You could use some parameter as indicator, that you want to change current design: i.e.</p> <p><a href="http://domain.com/myAction.action?changeDesign=silver_theme" rel="nofollow noreferrer">http://domain.com/myAction.action?changeDesign=silver_theme</a></p> <p>So then, you write some struts 2 interceptor, which logic is to check the presence of such parameter 'changeDesign', and this interceptor will do nessesary work of changing design and will control workflow. With interceptor you decouple your actions from crosscutting logic.</p>
6,730
<p>I am new at this and maybe my model is not the best, I adapted it for another one actually. Can you tell me why I can't get the holes printed? I already checked the faces and they are all in the correct orientation (I think)</p> <p>What happens is that I start printing with the holes facing down and they are not printed at all. I never let it keep going for long but it seems to be completely filled inside.</p> <p>You can check the file <a href="https://ufile.io/9favbj6e" rel="nofollow noreferrer">here</a>.</p> <p><a href="https://i.stack.imgur.com/lSvn0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lSvn0.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/b1PSD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b1PSD.png" alt="enter image description here" /></a></p>
<h1>The problem is internal geomoetry</h1> <p>The body you modeled consists of a non-manifold shell: There exists a fully enclosed shell on the inside of the item that tries to define an &quot;outside&quot; of the body. In the following picture, I have hidden part of the geometry to better show the problematic internal surfaces in orange:</p> <p><a href="https://i.stack.imgur.com/UWHWH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UWHWH.jpg" alt="internal Geometry" /></a></p> <p>Automatic processes such as Meshmixer or Windows 10 3D builder interpret such an internal, one-sided open cylinder as &quot;This probably is missing a surface on both ends&quot;. This solution leads to two intersecting and manifold shells - <a href="https://3dprinting.stackexchange.com/q/6230/8884">a cylinder overlapping the drilled holes and the body with the drilled holes</a> - which then promptly get treated with a boolean union... and voila! No more holes. Or even no more outer shell as the easiest solution is to just stitch that lower surface and discard the rest. This is what happens when Meshmixer does just that: you are left with the cone half and some inverted artifact areas.</p> <p><a href="https://i.stack.imgur.com/AshxK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AshxK.png" alt="Meshmixer automatic repair removes half the model leaving a few inverted artifacts" /></a></p> <p>So the best solution is to ensure the parts don't contain such volumes encased by a non-manifold surface in the first place. Due to the nature of the part, in this case, it is rather simple: Simply removing the circle of vertices that spans up both the plane, as well as the cylinder, marked orange results in all internal surfaces getting removed. Note that due to the orange parts sharing (at least partially) vertices with the wanted outside, this has to be done manually. Would both surfaces share no vertex, a simple &quot;separate shells&quot; operation could result in a very quick way to remove offending structures.</p> <p><a href="https://i.stack.imgur.com/tEKZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tEKZJ.png" alt="Without internal geometry" /></a></p> <p>Without the internal geometry, the model gets interpreted correctly - the mere presence of such superfluous internal geometry makes the slicer believe that some surfaces are inverted or missing, and thus need to be inverted or stitched - and the solution to the slicing is... utter mess.</p> <p><a href="https://i.stack.imgur.com/Vbix6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vbix6.png" alt="Cura rendition of the defect and cured model" /></a> <a href="https://i.stack.imgur.com/kgC0I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kgC0I.png" alt="Slicing solutions, before and after removal of internal geometry" /></a></p>
<p>The overall appearance is that the normals are &quot;normal,&quot; that you have no reversed facets, but there are discontinuities within the model that Meshmixer and Netfabb show as failure points. Windows 10 3DBuilder also attempts a repair which fills in the holes.</p> <p><a href="https://i.stack.imgur.com/L92T7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L92T7.png" alt="meshmixer failure indicators" /></a></p> <p>The Meshmixer capture image shows red lines and points at the flaws in the model. Both above programs fill the faces, which works fine on the cylinder, but fills in the plane where the holes reside, as well as removes the internal holes/cylinders, preventing a simple plane cut repair.</p> <p>Additional examination of the original model shows an internal cylinder formed axially on the end face red warning markers in the image above. I used Rhino3D v6 to slip inside, select the cylinder and remove it. Because the cylinder is &quot;inside&quot; the overall model, there's no inside face and outside face, causing the software to glitch.</p> <p>On the red line along the circumference of the cylinder, there's an internal disk/disc with an internal diameter to match the previously removed internal cylinder. As it also resides within the overall model, the same trouble applies: no true inside/outside surface for the software to comprehend.</p> <p>Once these were removed, a problematic set of errors appeared. I'm working on that. Work completed. Windows 10 3DBuilder has a pretty amazing repair facility, once the deep stuff is cleaned away. The end result passes the Meshmixer Inspector test and I suspect will work for you. The cylinder appears to be 37 mm in diameter (about an inch and a half) which is rather tiny, but with the flaws repaired, will scale up just fine.</p> <p>It loaded into Simplify3D slicer with no errors and appears will print nicely, although with support required along the beveled portion of the cylinder.</p>
2,125
<p>Browse to a webpage with hyperlinks using IE (I am using IE7) Once on the page, enlarge the fonts using ctl + mouse wheel. Now when you try to hover over the hyperlinks, they are laterally displaced to the right. To click on the link, i have to move the mouse to the right till the cursor turns into a hand. Anyone has a comment on this??</p> <hr> <p><a href="http://blogs.msdn.com/tom/archive/2008/08/19/hyper-v-and-visual-studio-2008-sp1.aspx" rel="nofollow noreferrer">I was browsing the following page</a>.</p> <p>It is the 2nd hyperlink in the body of the article. (the link text is "here")</p>
<p>IE7 doesn't handle Zoom correctly, You can see this error on this page (I mean the page you're reading right now) if you zoom large enough, view the logout | about link at the top, hover over it, hover off to the right, back over.</p>
<p>All of the links on that page are displaced to the right on my copy of IE7 (7.0.6001.18000) even before I enlarge or shrink the fonts. Whereas other pages act normally. (My test page was <a href="http://www.frito-lay.com/fl/flstore/cgi-bin/good_questions.htm" rel="nofollow noreferrer">http://www.frito-lay.com/fl/flstore/cgi-bin/good_questions.htm</a>).</p> <p>It appears to be something specific to the page.</p>
3,795
<p>When I am running the following statement:</p> <pre><code>@filtered = map {s/&amp;nbsp;//g} @outdata; </code></pre> <p>it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of <code>&amp;nbsp;</code> from an array of string (which is an XML file).</p> <p>Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?</p>
<p>Try this:</p> <pre><code>@filtered = map {s/&amp;nbsp;//g; $_} @outdata; </code></pre> <p>The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata.</p>
<p>As a counterpoint to Greg's answer, you could misuse grep:</p> <pre><code>@filtered = grep {s/&amp;nbsp;//g; 1} @outdata; </code></pre> <p><strong>Don't do this.</strong></p>
3,319
<p>I'm trying to modify some parts on <a href="https://www.thingiverse.com/thing:2115095" rel="noreferrer">this</a> thing. I'm kind of new to dealing with the modeling aspects of this.</p> <p>I am attempting to widen the part essentially 3mm. This would involve modifying the chain segments, and the anchor points.</p> <p>I have already attempted this with 3D Builder and the result was less than stellar. I split the part, cloned off about 3mm of the middle of the X-Chain (including the top &amp; bottom bits). The intent was to break the part, translate one of the halves off 3mm, add back the 3mm into the gap.</p> <p>When I put all the parts back together and merged them in 3D Builder, the resultant model, while visually on screen appeared to be one piece, the slicing proved otherwise.</p> <p>Is there a way that I can do the above in FreeCAD? I'm learning this so tutorial links would be more than sufficient. But if there is someone who can explain this process to me in FreeCAD that would also be appreciated.</p>
<p>I found that the answer provided by @Marco was helpful but not the correct answer I was looking for.</p> <p>Here is the general approach I used (Based on <a href="https://open-shelf.appspot.com/FreeCAD/en-US/34.html" rel="nofollow noreferrer">this</a>).</p> <ol> <li>Create new document</li> <li>Import STL file</li> <li>Switch to Part workbench</li> <li>Select imported mesh</li> <li>Part -> Create Shape from Mesh (use default tolerance)</li> <li>Delete imported mesh</li> <li>Select shape</li> <li>Part -> Refine Shape</li> <li>Delete "unrefined" shape</li> <li>Select refined shape</li> <li>Part -> Convert to Solid</li> <li>Follow instructions in <a href="https://open-shelf.appspot.com/FreeCAD/en-US/34.html" rel="nofollow noreferrer">link</a> provided.</li> </ol> <p>Below is the list of instructions from #12</p> <ol> <li>Have shape loaded</li> <li>Switch to a plane that you would like to cut parallel to. e.g. XZ</li> <li>Switch to Draft workbench</li> <li>Draw rectangle around item to cut</li> <li>Upgrade using '^' up arrow (blue) in toobar</li> <li>Adjust the Placement Angle/Position via the "Data" in the property editor lower left side.</li> <li>Switch to the "Arch" workbench</li> <li>Double click the solid to cut in the 3d view</li> <li>Ctrl+click the plane you will cut with</li> <li>Select "cut-plane" and choose which side to capture</li> </ol> <p>You will have to play around with the pattern in 12. The idea is to use the same Face created through 12 to cut the part at the same point twice. To create two halves. Take note of the position of the Face created in 12.</p> <p>In my case, I was attempting to stretch the part along the Y axis, so I was able to cut the part with an XZ plane (created in 12) and offset with a distance in the Y plane.</p> <p>After performing this "split" I created a cross-section of the at the point of the cut and extruded the cross section 3mm.</p> <p>Afterward, I was able to use the Edit -> Alignment tool to attach all three parts back together.</p> <p>Once attached, I selected all three and performed a "union" operation to make them all whole again, then executed the Part -> Refine shape.</p> <p>End result was that I could make the chain links 3mm wider than the original.</p> <p>I'm still working on tweaking out the other components that constitute this feature but still this is an interesting exercise.</p>
<p>I found Dave G's answer to be helpful, however I could only use additive features (e.g. Pad) on the created object, and could not make subtractive features <em>into</em> the object (e.g. Pocket).</p> <p>Here's what worked for me using FreeCAD 0.19 (Instructions from <a href="http://pinter.org/archives/4255" rel="nofollow noreferrer">this site</a>):</p> <ol> <li>Create new document</li> <li>Import STL (File --> Import)</li> <li>Part workbench --> Create shape from mesh</li> <li>Part workbench --> Shape builder...</li> <li>Create shape, select "Solid from shell". Make sure "Refine shape" box is checked. Press "Create" button. (You may need to switch to the "Model" tab in the Combo View and select your shape object.)</li> <li>Change to the PartDesign workbench. Select the newly-created "Solid" in the Combo/Tree View, then select PartDesign --> "Create body"</li> <li>A new Body will be created with your Solid as a BaseFeature that can work with Pad <em>and</em> Pocket features.</li> </ol>
972
<p>I've found many Youtube videos of makers upgrading to BLTouch sensor. </p> <p>I have a Creality CR-10S Pro, so far bed leveling hasn't been an issue (after some days of trial and error). </p> <p>My question is what are the problems/issues users need to face in order to need (or justify) an upgrade?</p>
<p>A touch or an inductive/capacitive sensor is useful when you cannot get prints to stick to the build surface because of a skew bed platform/heated plate or if the plate has a bend, large concave or convex area.</p> <p>Even with such a sensor, you need to provide a bed that is as level (trammed) as you can get. Automatic Bed Levelling (ABL) is not magic, it is just a tool that can help out if you have a problematic bed surface. But, recent versions of Marlin have &quot;manual bed levelling&quot;; i.e. you can map the surface using your printer without a sensor and store that geometry in memory.</p>
<p>I don't know your printer but I don't have BLtouch, and I have to set the height every time because the bed expands with heat.</p> <p>If you print at variable bed temperature (PLA, ABS, PETg, nylon require different values) then that sensor helps a lot.</p> <p>BL touch can also speed up bed calibration: you scan the bed, see the values to be corrected, adjust the bed without having to guess (given the thread pitch and required correction).</p> <p>Also, if you print only in the center it's easy but if you print fully using the size of the bed, I doubt you can get very flat bed. The BLtouch helps for that too.</p> <p>Also, there are clones like 3D touch which were tested and work equally well. Depending on your budget, they may be an interesting alternative.</p>
1,639
<p>In our application, we are using RMI for client-server communication in very different ways:</p> <ol> <li>Pushing data from the server to the client to be displayed.</li> <li>Sending control information from the client to the server.</li> <li>Callbacks from those control messages code paths that reach back from the server to the client (sidebar note - this is a side-effect of some legacy code and is not our long-term intent).</li> </ol> <p>What we would like to do is ensure that all of our RMI-related code will use only a known specified inventory of ports. This includes the registry port (commonly expected to be 1099), the server port and any ports resulting from the callbacks.</p> <p>Here is what we already know:</p> <ol> <li>LocateRegistry.getRegistry(1099) or Locate.createRegistry(1099) will ensure that the registry is listening in on 1099.</li> <li>Using the UnicastRemoteObject constructor / exportObject static method with a port argument will specify the server port.</li> </ol> <p>These points are also covered in this <a href="http://forums.sun.com/thread.jspa?threadID=370039&amp;messageID=1566073" rel="noreferrer">Sun forum post</a>. </p> <p>What we don't know is: how do we ensure that the client connections back to the server resulting from the callbacks will only connect on a specified port rather than defaulting to an anonymous port?</p> <p>EDIT: Added a longish answer summarizing my findings and how we solved the problem. Hopefully, this will help anyone else with similar issues.</p> <p>SECOND EDIT: It turns out that in my application, there seems to be a race condition in my creation and modification of socket factories. I had wanted to allow the user to override my default settings in a Beanshell script. Sadly, it appears that my script is being run significantly after the first socket is created by the factory. As a result, I'm getting a mix of ports from the set of defaults and the user settings. More work will be required that's out of the scope of this question but I thought I would point it out as a point of interest for others who might have to tread these waters at some point....</p>
<p>You can do this with a custom RMI Socket Factory. </p> <p>The socket factories create the sockets for RMI to use at both the client and server end so if you write your own you've got full control over the ports used. The client factories are created on the server, Serialized and then sent down to the client which is pretty neat.</p> <p><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/socketfactory/" rel="nofollow noreferrer">Here's a guide at Sun telling you how to do it.</a></p>
<p>I've been having various problems implementing an RMI Server/Client architecture, with Client Callbacks. My scenario is that both Server and Client are behind Firewall/NAT. In the end I got a fully working implementation. Here are the main things that I did:</p> <h2>Server Side , Local IP: 192.168.1.10. Public (Internet) IP 80.80.80.10</h2> <p>On the Firewall/Router/Local Server PC open port 6620. On the Firewall/Router/Local Server PC open port 1099. On the Router/NAT redirect incoming connections on port 6620 to 192.168.1.10:6620 On the Router/NAT redirect incoming connections on port 1099 to 192.168.1.10:1099</p> <p>In the actual program:</p> <pre><code>System.getProperties().put("java.rmi.server.hostname", IP 80.80.80.10); MyService rmiserver = new MyService(); MyService stub = (MyService) UnicastRemoteObject.exportObject(rmiserver, 6620); LocateRegistry.createRegistry(1099); Registry registry = LocateRegistry.getRegistry(); registry.rebind("FAManagerService", stub); </code></pre> <h2>Client Side, Local IP: 10.0.1.123 Public (Internet) IP 70.70.70.20</h2> <p>On the Firewall/Router/Local Server PC open port 1999. On the Router/NAT redirect incoming connections on port 1999 to 10.0.1.123:1999</p> <p>In the actual program:</p> <pre><code>System.getProperties().put("java.rmi.server.hostname", 70.70.70.20); UnicastRemoteObject.exportObject(this, 1999); MyService server = (MyService) Naming.lookup("rmi://" + serverIP + "/MyService "); </code></pre> <p>Hope this helps. Iraklis</p>
8,073
<p>Simple question: how do you reinsulate the MakerBot Smart Extruders? </p> <p>Backstory: I work at the library. We've recently replaced the MakerBot (extruder connection issues followed by software incompatibility) with a Prusa.</p> <p>As a new hire, I'm obsessed with the 3D printers. I'm trying to make it my mission to get the MakerBot working again, just so we can have two printers running.</p> <p>It takes quite the request chain to get materials in and I had some plumbing tape on hand, so I tried to wrap it with that, per <a href="https://3dprinting.stackexchange.com/questions/1247/efficient-and-easy-way-to-thermally-insulate-the-heat-block-of-the-hotend">this thread</a>. It's not going too well because of the housing around the Smart Extruder, which I cannot figure out to remove (easily and/or without voiding the warranty and taking it completely apart). </p> <p>I imagine even with the cotton + Kapton tape, you'd need better access to the hotend than the housing allows.</p> <p>Any help is appreciated!</p>
<p>I recently wrapped a LOT of hot PLA around my print head and, as a result, had to remove the kapton tape and the fibreglass insulation that came with it.</p> <p>I was reluctant to use fibreglass because of the tissue embedding hazard and the lung hazard (especially on what is effectively an indoor appliance) and kapton tape is very hard to find in Australia.</p> <p>After some research, I wrapped the print head in 100% wool felt that I bought from a fabric store (be very careful, as most craft felt nowadays is either acrylic, polyester or a poly/wool blend) and then bound it all up with teflon thread tape (plumber's thread tape).</p> <p>Cotton has a scorch temperature of 150 to 200°C, while wool won't scorch until 500 to 600°C, and the teflon tape can handle temperatures between 200 to 300°C.</p> <p>Did it work? Well I can now put my finger on the outside of the tape after the element has been at 200°C for 10 minutes, and only feel a little warmth. The print head heats up twice as fast, and I can run my massively oversized print cooling fan at 40% rather than the 10% I could use before. There is no odor of anything cooking off either. Success!</p>
<p>Strictly speaking, you do not require the insulation to be there. It is supposed to keep some of the heat contained in the core to allow more heat to be available for the filament to melt (basically higher print speeds and less chance of burning your fingers :) ). </p> <p>If I go to the Makerbot website and look at the video <p><a href="https://www.makerbot.com/3d-printers/smart-extruder/?wvideo=8adgspxkmv" rel="nofollow noreferrer"></a></p><p><a href="https://www.makerbot.com/3d-printers/smart-extruder/?wvideo=8adgspxkmv" rel="nofollow noreferrer">Smart Extruder+ - 3D Printer Extruder - 3D Printer PLA Extruder</a></p></p> <p>at 1:37, you'll see that the hot end is wrapped in cotton and Kapton tape. Like the stuff that is cheap and easy to buy:</p> <p><a href="https://i.stack.imgur.com/Xu5QN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xu5QN.jpg" alt="enter image description here"></a></p> <p>and that the casing cover is removable, so you should be able to open it to insert new cotton. Why worry about voiding warranty? You can gain a working printer for a few bucks or bite the bullet and buy a new Makerbot Smart Extruder. I guess if you had warranty you could already have it replaced by now.</p>
934
<p>I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used</p> <pre><code>Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" &amp; sDb) </code></pre> <p>instead of</p> <pre><code>DIM conn As New SqlConnection("context connection=true") </code></pre> <p>I'm wondering what the difference since it's localhost on the first?</p>
<p>The context connection uses the user's already established connection to the server. So you inherit things like their database context, connection options, etc.</p> <p>Using localhost will connect to the server using a normal shared memory connection. This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).</p> <p>In most cases you should use the context connection, since it doesn't create a separate connection to the server.</p> <p>Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.</p>
<p>Consider a big office phone systems:</p> <p>My office has an internal phone system. But every phone also has an external phone number (virtual numbers that utilize one of a group of real TELCO lines). I can call another office by dialing their phone extension directly and the call will route through our internal phone system (one hop). Alternatively I could dial that phone's public number and the call routes out from the building's system to the TELCO switching office, then back through the building's system then to the office extension (3 hops).</p> <p>The first SQL connection behaves as any standard SQL connection would when connecting to the server specified in the connection string. A new connection is created using the standard native SQL connectivity. This behaves like dialing the full public phone number of another office phone. Sure, you are connecting to the local machine, but the connection is routed differently.</p> <p>The context connection has the new SqlConnection instance using the existing connection that is executing the SQLCLR object. It's using the existing/local context. This is like dialing my office mate's extension directly. Local context and more efficient.</p> <p>Although I'm not positive, I believe that when using the context connection, the calls to the SQLCLR objects also then participate in the context's transaction. Someone please correct me if I'm wrong.</p> <p>Peter</p>
8,090
<p>Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password?</p>
<p>This URL will give you a count of unread posts per feed. You can then iterate over the feeds and sum up the counts.</p> <p><a href="http://www.google.com/reader/api/0/unread-count?all=true" rel="nofollow noreferrer">http://www.google.com/reader/api/0/unread-count?all=true</a></p> <p>Here is a minimalist example in Python...parsing the xml/json and summing the counts is left as an exercise for the reader:</p> <pre class="lang-py prettyprint-override"><code>import urllib import urllib2 username = 'username@gmail.com' password = '******' # Authenticate to obtain SID auth_url = 'https://www.google.com/accounts/ClientLogin' auth_req_data = urllib.urlencode({'Email': username, 'Passwd': password, 'service': 'reader'}) auth_req = urllib2.Request(auth_url, data=auth_req_data) auth_resp = urllib2.urlopen(auth_req) auth_resp_content = auth_resp.read() auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x) auth_token = auth_resp_dict["Auth"] # Create a cookie in the header using the SID header = {} header['Authorization'] = 'GoogleLogin auth=%s' % auth_token reader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s' reader_req_data = urllib.urlencode({'all': 'true', 'output': 'xml'}) reader_url = reader_base_url % (reader_req_data) reader_req = urllib2.Request(reader_url, None, header) reader_resp = urllib2.urlopen(reader_req) reader_resp_content = reader_resp.read() print reader_resp_content </code></pre> <p>And some additional links on the topic:</p> <ul> <li><a href="http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI" rel="nofollow noreferrer">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a></li> <li><a href="https://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt">How do you access an authenticated Google App Engine service from a (non-web) python client?</a></li> <li><a href="http://blog.gpowered.net/2007/08/google-reader-api-functions.html" rel="nofollow noreferrer">http://blog.gpowered.net/2007/08/google-reader-api-functions.html</a></li> </ul>
<p>In the API posted in [1], the "token" field should be "T"</p> <p>[1] <a href="http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI" rel="nofollow noreferrer">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a></p>
7,622
<p>I've created an Access 2007 form that displays, for example, Products from a Product table. One of the fields in the Product table is a CategoryID that corresponds to this product's parent category.</p> <p>In the form, the CategoryID needs to be represented as a combo box that is bound to the Category table. The idea here is pretty straightforward: selecting a new Category should update the CategoryID in the Product table.</p> <p>The problem I'm running into is that selecting a new Category updates the CategoryName of the Category table instead of updating the CategoryID in the Product table. The reason for this is that it seems that the combo box must be bound only to the CategoryName of the Category table.</p> <p>What happens is if the current product has a CategoryID of 12 which is the CategoryName "Chairs" in the Category table then selecting a new value, let's say "Tables" (CategoryID 13) in the combo box updates the CategoryID of 12 with the new CategoryName "Tables" instead of updating the Product table CategoryID to 13.</p> <p>How can I bind the Category table to a combox box so that the datatextfield (which I wish existed in Access) is the CategoryName and the datavaluefield is the CategoryID and only the CategoryID of the Product will be updated when the selected combo box item is changed?</p> <p><strong>Edit:</strong> See the accepted answer below. I also needed to change the column count to 2 and everything started to work perfectly. </p>
<p>You need to use both values in the query for the combo box.<br> e.g. SELECT CategoryId, CategoryName FROM CategoryTable... Bind the combo box to the fist column, CategoryId. Set the column widths for the combo box to 0in (no second value need, so there is no limit). This will hide the first column which contains your selected value; all that shows it the description value, which is all you want to see. So now when you select a different option in the combobox, the value returned by the combo box will be the bound value, CategoryId, not CategoryName.</p> <p>Ah, yes Alison, sorry, I forgot about setting the combobox columncount = 2.</p>
<p>You should also check that your categories table has a primary key on the CategoryName field. You original configuration should have thrown an error or message saying the update would violate the key. As it is it seems you can have 2 categories with the same name.</p>
9,449
<p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
<pre><code>import ctypes import os import platform import sys def get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value / 1024 / 1024 else: st = os.statvfs(dirname) return st.f_bavail * st.f_frsize / 1024 / 1024 </code></pre> <p>Note that you <em>must</em> pass a directory name for <code>GetDiskFreeSpaceEx()</code> to work (<code>statvfs()</code> works on both files and directories). You can get a directory name from a file with <code>os.path.dirname()</code>.</p> <p>Also see the documentation for <a href="https://docs.python.org/3/library/os.html#os.fstatvfs" rel="noreferrer"><code>os.statvfs()</code></a> and <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx" rel="noreferrer"><code>GetDiskFreeSpaceEx</code></a>.</p>
<p>I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.</p> <p>For Windows, there's the <a href="http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetDiskFreeSpaceEx_meth.html" rel="nofollow noreferrer">GetDiskFreeSpaceEx</a> method in the win32 extensions.</p>
7,484
<p>As far as I know, in gcc you can write something like:</p> <pre><code>#define DBGPRINT(fmt...) printf(fmt); </code></pre> <p>Is there a way to do that in VC++?</p>
<p>Yes but only since VC++ 2005. The syntax for your example would be:</p> <pre><code>#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__) </code></pre> <p>A full reference is <a href="http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx" rel="noreferrer">here</a>.</p>
<p>Almost. It's uglier than that though (and you probably don't want a trailing semi-colon in the macro itself:</p> <pre><code>#define DBGPRINT(DBGPRINT_ARGS) printf DBGPRINT_ARGS // note: do not use '(' &amp; ')' </code></pre> <p>To use it:</p> <pre><code>DBGPRINT(("%s\n", "Hello World")); </code></pre> <p>(was missing a pair of parens).</p> <p>Not sure why all the negatives, the original question didn't state a version of VC++, and variadic macros aren't supported by all compilers.</p>
9,075
<p>I work with Fusion360 for designing lots of things. Recently I learned how to work with parameters that I can easily modify all at once, allowing to pretty much make easily customizable pieces.</p> <p>Now, Thingiverse wants customizer pieces in the shape of <code>.SCAD</code> files, and some people just can't work with Fusion360 (<code>.F3D</code>) or proper <code>.STEP</code> files that can be imported by most CAD programs.</p> <p>I have no experience with OpenSCAD. Can I import my <code>.STEP</code> into openSCAD, retain my parameters and export it as a <code>.SCAD</code>, and if yes, how?</p>
<p>Even though OpenSCAD can import a variety of formats, the file structure will not be accepted by Thingiverse in the manner presented by the OP.</p> <p>OpenSCAD is a text-based description language. One creates parameters assigned to specific aspects of a model and implements those parameters to create the desired shapes/components by typing in a text editor. The native editor for OpenSCAD provides for some management, but notepad or equivalent would work just as well.</p> <p>The file format of OpenSCAD is text. None of the CAD type modeling programs will provide equivalent text output.</p> <p>For your objective, you'd have to learn the basics of OpenSCAD (not particularly difficult) and reference the parameters in the STEP files, then assign them to the appropriate labels in OpenSCAD.</p> <p>If you have particularly complex designs, it can be a handful. It can also be rewarding when you change a parameter as a test and the complete model follows as expected.</p>
<p>No, you cannot import STEP nor Fusion360 files in OpenSCAD.</p> <p>OpenSCAD <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Importing_Geometry" rel="nofollow noreferrer">currently supports</a>:</p> <p><strong>3D formats</strong></p> <ul> <li>STL (both ASCII and Binary)</li> <li>OFF</li> <li>AMF [Note: Requires version 2019.05]</li> <li>3MF [Note: Requires version 2019.05]</li> </ul> <p><strong>2D formats</strong></p> <ul> <li>DXF</li> <li>SVG [Note: Requires version 2019.05]</li> </ul> <p><strong>Other</strong></p> <ul> <li>CSG can be imported using <code>include&lt;&gt;</code> or loaded like an SCAD file, PNG can be imported using <code>surface()</code></li> </ul>
1,619
<p>Let's suppose you deploy a network-attached appliances (small form factor PCs) in the field. You want to allow these to call home after being powered on, then be identified and activated by end users.</p> <p>Our current plan involves the user entering the MAC address into an activation page on our web site. Later our software (running on the box) will read the address from the interface and transmit this in a "call home" packet. If it matches, the server response with customer information and the box is activated.</p> <p>We like this approach because it's easy to access, and usually printed on external labels (FCC requirement?).</p> <p>Any problems to watch out for? (The hardware in use is small form factor so all NICs, etc are embedded and would be very hard to change. Customers don't normally have direct acccess to the OS in any way). </p> <p>I know Microsoft does some crazy fuzzy-hashing function for Windows activation using PCI device IDs, memory size, etc. But that seems overkill for our needs.</p> <p>--</p> <p>@Neall Basically, calling into our server, for purposes of this discussion you could call us the manufacturer. </p> <p>Neall is correct, we're just using the address as a constant. We will read it and transmit it within another packet (let's say HTTP POST), not depending on getting it somehow from Ethernet frames.</p>
<p>I don't think there's anything magic about what you're doing here - couldn't what you're doing be described as:</p> <p>"At production we burn a unique number into each of our devices which is both readable by the end user (it's on the label) and accessible to the internal processor. Our users have to enter this number into our website along with their credit-card details, and the box subsequently contacts to the website for permission to operate"</p> <p>"<em>Coincidentally</em> we also use this number as the MAC address for network packets as we have to uniquely assign that during production anyway, so it saved us duplicating this bit of work"</p> <p>I would say the two obvious hazards are:</p> <ol> <li><p>People hack around with your device and change this address to one which someone else has already activated. Whether this is likely to happen depends on some relationship between how hard it is and how expensive whatever they get to steal is. You might want to think about how easily they can take a firmware upgrade file and get the code out of it.</p></li> <li><p>Someone uses a combination of firewall/router rules and a bit of custom software to generate a server which replicates the operation of <em>your</em> 'auth server' and grants permission to the device to proceed. You could make this harder with some combination of hashing/PKE as part of the protocol. </p></li> </ol> <p>As ever, some tedious, expensive one-off hack is largely irrelevant, what you don't want is a class-break which can be distributed over the internet to every thieving dweep.</p>
<p>From a security perspective, I know that it is possible to spoof a MAC, though I am not entirely sure how difficult it is or what it entails.</p> <p>Otherwise, if the customers don't have easy access to the hardware or the OS, you should be fairly safe doing this... probably best to put a warning sticker on saying that messing with anything will disrupt communication to the server.</p>
5,000
<p>I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>
<p>Windows still lacks a convention for per-user installation.</p> <ul> <li>When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide <code>%PROGRAMFILES%</code>.</li> <li>Microsoft's own ClickOnce works around this by creating a completely non-standard <code>%USERPROFILE%\Local Settings\Apps</code> (<code>%USERPROFILE%\AppData\Roaming</code> on Vista / Server 2008) directory, with both program files and configuration data in there.</li> </ul> <p>(I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a <code>~/Applications</code>, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.)</p> <p>What you probably <em>should</em> do: if the user is not an admin, install in the user directory; if they do, give them both options.</p>
<p>Just so you people know, Google has created an MSI installer for global system installation and management. It's located here:</p> <p><a href="https://www.google.com/intl/en/chrome/business/browser/" rel="nofollow">https://www.google.com/intl/en/chrome/business/browser/</a></p>
6,989
<p>Reading <a href="https://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem">this question</a> I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). </p> <pre><code>100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* </code></pre> <p>Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies?</p> <p>Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only <strong>after</strong> you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.</p>
<p>My process for situations where I think performance may be an issue:</p> <ol> <li>Make it work.</li> <li>Make it clear.</li> <li>Test the performance.</li> <li>If there are meaningful performance issues: refactor for speed.</li> </ol> <p>Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.</p>
<p>at times when optimization is necessary, i'd rather sacrifice compactness and keep the performance enhancement. perl obviously has some deep waters to plumb in search of the conciseness/performance ratio, but as cute as it is to write one-liners, the person who comes along to maintain your code (who in my experience, is usually myself 6 months later) might prefer something more in the expanded style, as documented here:</p> <p><a href="http://www.perl.com/pub/a/2004/01/16/regexps.html" rel="nofollow noreferrer">http://www.perl.com/pub/a/2004/01/16/regexps.html</a></p>
5,061
<p>I see them all the time and always ignore them. Can someone explain to me why they have become so prevalent? If I'm using a site that allows me to explore it via tags (e.g., this one, del.icio.us, etc.) that's what I will do. Why would I need a "cloud" of tags upon which to click? I can just type that tag(s) into a search box. What am I missing?</p>
<p>It's more of a browse assist than a search assist. If you see a large or bold tag in a tag cloud that interests you it my lead to some knowledge discovery that wouldn't have otherwise been sought out with a deliberate search. When I am browsing del.ico.us or stackoverflow I appreciate the tags as they sometimes lead me to discover related topics.</p> <p>Wikipedia has an interesting <a href="http://en.wikipedia.org/wiki/Tag_cloud" rel="nofollow noreferrer">definition</a>:</p> <blockquote> <p>A tag cloud or word cloud (or weighted list in visual design) is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. <a href="http://en.wikipedia.org/wiki/Tag_cloud" rel="nofollow noreferrer">1</a> Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.</p> </blockquote>
<p>Tags give a way of explicitly labelling something with what it is about instead of relying on computers to extract this information.</p> <p>For example, you might be interested in on questions about stackoverflow. If you search for "stackoverflow" you will get all kinds of questions that are not about stackoverflow at all (e.g. they only contain the word "stackoverflow" because there is some link to another question). By selecting questions that are tagged with "stackoverflow" you get only those post that people have explicitly identified as being about stackoverflow.</p>
8,519
<p>This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly <em>spamish</em> terminology.</p> <p>Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.</p> <p>This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam</p> <p>I figure this is a big topic in which I am essentially an ignorant simpleton.</p>
<p>Use email authentication methods, such as <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework" rel="nofollow noreferrer">SPF</a>, and <a href="https://help.ubuntu.com/community/Postfix/DKIM" rel="nofollow noreferrer">DKIM</a> to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.</p> <p><a href="http://remote.12dt.com/" rel="nofollow noreferrer">Check</a> your <a href="http://en.wikipedia.org/wiki/Reverse_DNS_lookup" rel="nofollow noreferrer">reverse DNS</a> to make sure the IP address of your mail server points to the domain name that you use for sending mail.</p> <p>Make sure that the IP-address that you're using is <a href="http://www.spamhaus.org/lookup.lasso" rel="nofollow noreferrer">not on a blacklist</a></p> <p>Make sure that the reply-to address is a valid, existing address.</p> <p>Use the full, real name of the addressee in the To field, not just the email-address (e.g. <code>&quot;John Smith&quot; &lt;john@blacksmiths-international.com&gt;</code> ).</p> <p>Monitor your abuse accounts, such as <code>abuse@yourdomain.example</code> and <code>postmaster@yourdomain.example</code>. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.</p> <p>Finally, make it <strong>really</strong> easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the <strong>spam</strong> button, and that will affect your reputation.</p> <p>That said, getting Hotmail to accept your emails remains a black art.</p>
<p>To allow <strong>DMARC</strong> checks for SPF to pass and also be <strong>aligned</strong> when using sendmail, make sure you are setting the envelope sender address (<code>-f</code> or <code>-r</code> parameter) to something that matches the domain in the <code>From:</code> header address.</p> <h2>With PHP:</h2> <p>Using PHP's built-in <code>mail()</code> function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the <a href="https://www.rfc-editor.org/rfc/rfc5321" rel="nofollow noreferrer">RFC5321</a>.MailFrom / Return Path header.</p> <p>For example, say you are hosting your website <code>domain.com</code> on the <code>host.com</code> web server. If you do not set the additional parameters parameter:</p> <pre class="lang-php prettyprint-override"><code>mail($to,$subject,$message,$headers); // Wrong way </code></pre> <p>The email recipient will receive an email with the following mail headers:</p> <pre><code>Return-Path: &lt;your-website-user@server.host.com&gt; From: &lt;your-website-user@domain.com&gt; </code></pre> <p>Even though this passes SPF checks, it will be unaligned (since domain.com and host.com do not match), which means that DMARC SPF check will fail as unaligned.</p> <p>Instead, you <strong>must</strong> pass the envelope sender address to sendmail by including the 5th parameter in the PHP <code>mail()</code> function, for example:</p> <pre class="lang-php prettyprint-override"><code>mail($to,$subject,$message,$headers, '-r bounce_email@domain.com'); // Right way </code></pre> <p>In this case, the email recipient will receive an email with the following mail headers:</p> <pre><code>Return-Path: &lt;bounce_email@domain.com&gt; From: &lt;your-website-user@domain.com&gt; </code></pre> <p>Since both of these headers contain addresses from <code>domain.com</code>, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.</p>
2,286
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
<p>@Mark Harrison's answer:</p> <pre><code>for x in iter(next_, END): .... </code></pre> <p>Here's an excerpt from <a href="http://docs.python.org/library/functions.html" rel="noreferrer">Python's documentation</a>:</p> <pre><code>iter(o[, sentinel]) </code></pre> <blockquote> <p>Return an iterator object. <em>...(snip)...</em> If the second argument, <code>sentinel</code>, is given, then <code>o</code> must be a callable object. The iterator created in this case will call <code>o</code> with no arguments for each call to its <code>next()</code> method; if the value returned is equal to <code>sentinel</code>, <code>StopIteration</code> will be raised, otherwise the value will be returned.</p> </blockquote>
<p>What are you trying to do here? If you're iterating over a list, you can use <code>for e in L</code> where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. <code>[ e for e in L if e % 2 == 0 ]</code> to get all the even numbers in a list).</p>
4,817
<p>We are using <a href="http://en.wikipedia.org/wiki/JetBrains" rel="nofollow noreferrer">JetBrains</a>' <a href="http://en.wikipedia.org/wiki/DotTrace" rel="nofollow noreferrer">dotTrace</a>. What other profiling tools can be recommended that are better for profiling C# <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> applications?</p>
<p>No. I have tried pretty much every .NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application.</p> <p>If and only if your application is relatively light, I could recommend <a href="http://www.red-gate.com/products/ants_profiler/index.htm" rel="noreferrer">ANTS Profiler</a>. Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency.</p>
<p><a href="http://nprof.sourceforge.net/Site/Description.html" rel="nofollow noreferrer">nProf</a> is a good tool if you're looking for something free. It's kind of finicky at points, and a little buggy, but if you're on a tight budget, it'll do the job.</p>
7,251
<p>Actually, this question seems to have two parts:</p> <ul> <li>How to implement pattern matching?</li> <li>How to implement <a href="http://erlang.org/doc/reference_manual/expressions.html#6.9" rel="noreferrer">send and receive</a> (i.e. the Actor model)?</li> </ul> <p>For the pattern matching part, I've been looking into various projects like <a href="http://members.cox.net/nelan/app.html" rel="noreferrer">App</a> and <a href="http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html" rel="noreferrer">Prop</a>. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The <a href="http://felix-lang.org/" rel="noreferrer">Felix</a> language also seems to support pattern matching pretty well, but isn't really C++.</p> <p>As for the <a href="http://en.wikipedia.org/wiki/Actor_model" rel="noreferrer">Actor model</a>, there are existing implementations like ACT++ and <a href="http://theron.ashtonmason.net/" rel="noreferrer">Theron</a>, but I couldn't find anything but papers on the former<strike>, and the latter is single-threaded only</strike> [see answers].</p> <p>Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.</p> <p>Right now, I can use the following code to send a message:</p> <pre><code>(new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); </code></pre> <p>And the following to do simple pattern matching (<code>qDebug</code> and <code>qPrintable</code> are Qt-specific):</p> <pre><code>receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive </code></pre> <p>However, this looks a bit hackish to me, and isn't very robust.</p> <p>How would you do it? Did I miss any existing work?</p>
<p>One of the important things about erlang is how the features are used to make robust systems.</p> <p>The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads.</p> <p>If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.</p> <p>If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.</p> <p>Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.</p> <p>Although if you are not careful you end up with xml over pipes :)</p> <p>Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet.</p> <p>The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.</p>
<p>I would definitely be interested in looking at your "acedia" library and would love to help in any way that I could. Erlang has some wonderful constructs and C++ could definitely benefit from such a library.</p>
6,166
<p>I have Sun webserver iws6 (iplanet 6) proxying my bea cluster. My cluster is under /portal/yadda. I want anyone who goes to </p> <pre><code>http://the.domain.com/ </code></pre> <p>to be quickly redirected to </p> <pre><code>http://the.domain.com/portal/ </code></pre> <p>I have and index.html that does a post and redirect, but the user sometimes sees it. Does anyone have a better way?</p> <p>Aaron</p> <p>I have tried the 3 replies below. None of them worked for me. Back to the drawing board. A</p>
<p>Does this help? <a href="http://docs.sun.com/source/816-5691-10/essearch.htm#25618" rel="nofollow noreferrer">http://docs.sun.com/source/816-5691-10/essearch.htm#25618</a></p> <hr> <p>To map a URL, perform the following steps:</p> <p>Open the Class Manager and select the server instance from the drop-down list.</p> <p>Choose the Content Mgmt tab.</p> <p>Click the Additional Document Directories link. The web server displays the Additional Document Directories page. (Optional) Add another directory by entering one of the following.</p> <p>URL prefix. For example: plans. Absolute physical path of the directory you want the URL mapped to. For example: C:/iPlanet/Servers/docs/marketing/plans Click OK.</p> <p>Click Apply.</p> <p>Edit one of the current additional directories listed by selecting one of the following: Edit</p> <p>Remove If editing, select edit next to the listed directory you wish to change.</p> <p>Enter a new prefix using ASCII format.</p> <p>(Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory: For more information about styles, see Applying Configuration Styles. Click OK to add the new document directory.</p> <p>Click Apply.</p> <p>Choose Apply Changes to hard start /restart your server.</p>
<p>You should be able to configure the webserver to do a header redirect (301 or 302 depending on your situation) so it redirects without ever loading an HTML page. This can be done in PHP as well:</p> <pre><code>&lt;?php header("Location: http://www.example.com/"); /* Redirect browser */ /* Make sure that code below does not get executed when we redirect. */ exit; ?&gt; </code></pre> <p>If you don't want to modify your server configuration.</p> <p>If your server uses the .htaccess file, insert a line similar to the following:</p> <pre><code>Redirect 301 /oldpage.html http://www.example.com/newpage.html </code></pre> <p>-Adam</p>
8,880
<p>I would love to re-use my failed prints by re-extruding the plastic to be used in the 3D printer once again. One thing that stands in my way is finding an effective way to shred the plastic into smaller bits for the extrude to use. What is a good thing to look for to accomplish this? Maybe a really big 'paper' shredder?</p>
<p>there is a project called <code>precious plastic</code> and there is a <a href="https://bazar.preciousplastic.com/en/listings/572981-star-international-shipping-star-shredder-kit" rel="nofollow noreferrer">plastic shredder</a>, but it is a rather expensive solution.</p> <p>As I am waiting for parts for my <a href="https://www.thingiverse.com/thing:380987" rel="nofollow noreferrer">Lyman extruder</a>, my plan is to hammer the parts and then process in old kitchen robot with steel working area, an <a href="https://youtu.be/9a_ZYDcQV0w?t=44s" rel="nofollow noreferrer">example here</a></p> <p>The paper shredder will be ok as long as you can feed it with plastic.</p>
<p>there is a project called <code>precious plastic</code> and there is a <a href="https://bazar.preciousplastic.com/en/listings/572981-star-international-shipping-star-shredder-kit" rel="nofollow noreferrer">plastic shredder</a>, but it is a rather expensive solution.</p> <p>As I am waiting for parts for my <a href="https://www.thingiverse.com/thing:380987" rel="nofollow noreferrer">Lyman extruder</a>, my plan is to hammer the parts and then process in old kitchen robot with steel working area, an <a href="https://youtu.be/9a_ZYDcQV0w?t=44s" rel="nofollow noreferrer">example here</a></p> <p>The paper shredder will be ok as long as you can feed it with plastic.</p>
899