instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Unbalanced_binary_tree.svg/251px-Unbalanced_binary_tree.svg.png" alt="alt text"></p>
<p>The image above is from <a href="http://en.wikipedia.org/wiki/AVL_tree" rel="nofollow noreferrer">"Wikipedia's entry on AVL trees"</a> which Wikipedia indicates is unbalanced.
How is this tree not balanced already?
Here's a quote from the article:</p>
<blockquote>
<p>The balance factor of a node is the height of its right subtree minus the height of its left subtree and a node with balance factor 1, 0, or -1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.</p>
</blockquote>
<p>Both the left and right subtrees have a height of 4. The right subtree of the left tree has a height of 3 which is still only 1 less than 4. Can someone explain what I'm missing?</p>
|
<p>To be balanced, every node in the tree must, either,</p>
<ul>
<li>have no children, (be a "leaf" node)</li>
<li>Have two children.</li>
<li><p>Or, if it has only one child, that child must be a leaf.</p>
<p>In the chart you posted, 9, 54 & 76 violate the last rule.</p></li>
</ul>
<p>Properly balanced, the tree would look like:</p>
<pre><code>Root: 23
(23) -> 14 & 67
(14) -> 12 & 17
(12) -> 9
(17) -> 19
(67) -> 50 & 72
(50) -> 54
(72) -> 76
</code></pre>
<p>UPDATE: (after almost 9 years, I created a cool online chart for the graph at <a href="https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=SO_Balanced_AVL_Tree%20.xml#Uhttps%3A%2F%2Fraw.githubusercontent.com%2Fjamescurran%2FHonestIllusion%2Fmaster%2FSO_Balanced_AVL_Tree%2520.xml" rel="nofollow noreferrer">draw.io</a>)<a href="https://i.stack.imgur.com/n6KwW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n6KwW.png" alt="enter image description here"></a></p>
|
<p>Intuitively, it's because it's not as small as possible. e.g., 12 should be the parent of 9 and 14. As it is, 9 has no left sub-tree so it's out of balance. A tree is a hierarchical data structure so a rule like "balanced" often apply to every node and not just the root node.</p>
<p>You're correct the root node is balanced, but not all the nodes of the tree are.</p>
| 28,572
|
<p>I have a strange issue: I am using SPContext.Current.Web in a .aspx page, but at the end, I get a "Trying to use an SPWeb object that has been closed or disposed and is no longer valid." error message.</p>
<p>From what I see, SPContext.Current.Web is Disposed by someone, <strong>but I have no idea where</strong>. I just wonder: With Visual Studio 2005's Debugger, can I somehow see where/who disposed an Object? As I neither create nor have the source code, setting breakpoints is a problem.</p>
<p>What would be a good approach for finding out who disposes a given object where, without just randomly commenting out lines?</p>
<p>(Note: The Issue has been resolve, but the question itself also applies outside of Sharepoint)</p>
|
<p>Check if this helps:</p>
<ol>
<li>Add a new breakpoint using <strong>Debug > New Breakpoint > Break at Function... (Ctrl+B)</strong>.</li>
<li>Enter <strong>Microsoft.SharePoint.SPWeb.Dispose</strong> in the Function edit box.</li>
<li>Dismiss the dialog box that says that Intellisense could not find the specified location.</li>
<li>Run under the debugger.</li>
<li>When the breakpoint is hit you can see on the call stack who called the Dispose method. Hopefully for some of the times the breakpoint is hit one stack frame is in your source code.</li>
</ol>
<p>If a dialog appears saying that <em>There is no source code available for the current location</em> when the breakpoint is hit dismiss it.</p>
<hr>
<p><strong>Note:</strong> Because I do not have SharePoint installed I have tested this with <code>System.IO.StreamReader.Dispose</code> but I am guessing that this should also work for SPContext.Current.Web. Drop a note on this.</p>
|
<p>You should read this: <a href="http://msdn.microsoft.com/en-us/library/aa973248.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa973248.aspx</a></p>
<p>To be quick: you should dispose all your SPWeb and SPSite using either</p>
<pre><code>using(SPWeb web = ...)
{
....
}
</code></pre>
<p>or</p>
<pre><code>SPWeb web = ...
...
web.Dispose()
</code></pre>
| 24,603
|
<p>Does anyone have sample code to copy open (in-use and locked by another program) files using Volume Shadow Copy Service (VSS) API?</p>
<p>There was an article about this in The Delphi Magazine (September 2005). But that code is no longer available and even if it was, it's not current.</p>
<p>I am looking for sample code that works with current version of Volume Shadow Copy service libraries.</p>
|
<p>there is a digital edition on usb stick of the "The Delphi Magazine".
you can order that on their webpage.</p>
<p>maybe someone has created a torrent of that stick.</p>
<p><strong>update</strong></p>
<p><strike>i found that sample here:
<a href="http://www.google.com/codesearch/p?hl=de#XIdFp1PskBE/VSS/VssAPI.pas" rel="nofollow noreferrer">http://www.google.com/codesearch/p?hl=de#XIdFp1PskBE/VSS/VssAPI.pas</a></strike></p>
<p>Upper link is outdated, the header-files can also found here:
<a href="http://www.delphipraxis.net/998560-post3.html" rel="nofollow noreferrer">http://www.delphipraxis.net/998560-post3.html</a></p>
|
<p>I found a working (XE2) example here:
<a href="http://www.rathlev-home.de/sources/delphi.html#progsxe2" rel="nofollow">http://www.rathlev-home.de/sources/delphi.html#progsxe2</a></p>
<p>For compilation with XE8 get the latest "gnugettext.pas"</p>
<p>This package contains all units necessary for compiling a delphi program which creates a volume shadow copy. In addition there is a example application VsToolkit available. I compiled it with XE2 and XE8 and it works just fine... </p>
| 36,031
|
<p>My <code>C#</code> program has a list of files that can be dragged from it and dropped into another program. My requirements are that the file be copied to a different directory first.</p>
<p>So, can I be notified of the drop operation so that I can only copy the file if operation succeeds? I'd rather wait till I know it needs to be copied before actually performing the copy.</p>
<p>Also, is it possible to know what program the drop operation is occurring in? Ideally I'd like to alter the filepath based on who or what its being dropped.</p>
<p>The solution to this can be in any .NET language or <code>C/C++</code> with <code>COM</code>.</p>
|
<p>There are a few ambiguities in your question. What operation needs to be successful?</p>
<p>For everything you want to know about drag and drop, browse through these search results (multiple pages worth):</p>
<p><a href="http://www.google.com/search?q=drag+drop+site%3Ablogs.msdn.com%2Foldnewthing&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1" rel="nofollow noreferrer">Raymond Chen on drag and drop</a></p>
|
<p>So, you intend to modify the data being dropped based on the drop target? I don't think this is possible; after all, you populate the data when the drag is initiated.</p>
| 4,331
|
<p>I have a vba macro which runs a loop for about 200 iterations, using up the ram page file as it runs.</p>
<p>I need some kind of quick fix to clear the page file after every iteration. I know the best fix would be to clean up the code, but time is a constraint here.</p>
|
<p>At the end of each loop iteration set any objects that will be re-created to <code>Nothing</code>.</p>
<p>This <a href="http://www.vbi.org/Items/article.asp?id=106" rel="nofollow noreferrer">article</a> explains it in detail.</p>
|
<p>I've never seen this happen. It sounds like you have an ever-expanding array and may be running out of memory. I would stop it in a few places during the run, to see what is happening.</p>
| 30,508
|
<p>What's the best way to implement a classic curry function in actionscript with a nice syntax?</p>
<p>I've tried:</p>
<pre><code>Function.prototype.curry = function()
{
return "helloWorld";
}
trace((function():void {}).curry());
</code></pre>
<p>...approach but that didn't work. </p>
<p>I guess I'm stuck with a ugly approach such as:</p>
<pre><code>FunctionUtils.curry(fp, ... args)
</code></pre>
<p>???</p>
|
<p>I must admit I've never understood the difference between "curry" and "partial". I use the following function to do more or less what you want to do:</p>
<pre><code>package {
public function partial( func : Function, ...boundArgs ) : Function {
return function( ...dynamicArgs ) : * {
return func.apply(null, boundArgs.concat(dynamicArgs))
}
}
}
</code></pre>
<p>Usage examples:</p>
<pre><code>var multiply : Function = function( a : Number, b : Number ) : Number { return a * b; }
var multiplyByFour : Function = partial(multiply, 4);
trace(multiplyByFour(3)); // => 12
</code></pre>
|
<p>Ended up with (heavily inspired by dojo's implementation):</p>
<pre><code>public static function curry(func:Function, ... args:Array):*
{
var arity:int = func.length;
var currying:Function = function(func:Function, arity:int, args:Array):*
{
return function(... moreArgs:Array):* {
if(moreArgs.length + args.length < arity)
{
return currying(func, arity, args.concat(moreArgs));
}
return func.apply(this, args.concat(moreArgs));
}
}
return currying(func, arity, args);
}
</code></pre>
<p>Request in the comments section to show an example of how to use this:</p>
<pre><code>function foo(i:int, j:int):void
{
trace(i+j);
}
function bar(fp:Function):void
{
fp(2);
}
bar(FunctionUtils.curry(foo, 1)); //trace==3
</code></pre>
<p>Silly example, I know, but curry:ing is extremely useful. Have a look at <a href="http://www.svendtofte.com/code/curried_javascript/" rel="nofollow noreferrer">http://www.svendtofte.com/code/curried_javascript/</a> for theory.</p>
| 46,914
|
<p>What are the maximum allowed number of columns in a query in access 2003?</p>
|
<p>255 I believe. You can check by going to <em>Help > Specifications > Query</em> within Access.</p>
|
<h2>From Access Help File</h2>
<p>Thank you Ben</p>
<p>Number of enforced relationships: 32 per table minus the number of indexes that are on the table for fields or combinations of fields that are not involved in relationships<br>
Number of tables in a query: 32<br>
Number of fields in a recordset: 255<br>
Recordset size: 1 gigabyte<br>
Sort limit: 255 characters in one or more fields<br>
Number of levels of nested queries: 50
Number of characters in a cell in the query design grid: 1,024<br>
Number of characters for a parameter in a parameter query: 255<br>
Number of ANDs in a WHERE or HAVING clause: 99<br>
Number of characters in an SQL statement: approximately 64,000 </p>
| 22,851
|
<p>We are developing a new web service and are looking into the "best practice" for returning errors in the soap response. </p>
<p>We were looking into creating a error response object which every response would contain as a property. This seems a little heavy however and are wondering if it is possible to use the SOAP header to carry this information? How do you normally deal with custom errors using SOAP?</p>
|
<p>Soap already uses custom headers for error info, all you need to do is throw an exception on the server side, and exception is raised on the client side as a <a href="http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception.aspx" rel="nofollow noreferrer">SoapException</a>.</p>
<p>You can thrown SoapExceptions on the serverside if you want more control over the exception message/info.</p>
<p>Edit:
For extra information along with the request, custom soap headers can be used. Here's an <a href="http://www.codeproject.com/KB/webservices/SOAPHeaderAuthentication.aspx" rel="nofollow noreferrer">example article on CodeProject</a> that used custom soap headers for authentication, but custom soap headers can be used for other purposes like sending extra info that is not necessarily an error condition (can be business logic info) </p>
|
<p>I've used similar techniques in the past for complex operations. Especially when you need (multiple?) error descriptions as well as as error code.</p>
| 30,074
|
<p>jQuery's <code>draggable</code> functionality doesn't seem to work on tables (in FF3 or Safari). It's kind of difficult to envision how this <em>would</em> work, so it's not really surprising that it doesn't.</p>
<pre><code><html>
<style type='text/css'>
div.table { display: table; }
div.row { display: table-row; }
div.cell { display: table-cell; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>
<script src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.draggable.js"></script>
<script>
$(document).ready(function(){
$(".row").draggable();
});
</script>
<body>
<div class='table'>
<div class='row'>
<div class='cell'>Foo</div>
<div class='cell'>Bar</div>
</div>
<div class='row'>
<div class='cell'>Spam</div>
<div class='cell'>Eggs</div>
</div>
</div>
<table>
<tr class'row'><td>Foo</td><td>Bar</td></tr>
<tr class='row'><td>Spam</td><td>Eggs</td></tr>
</table>
</body>
</html>
</code></pre>
<p>I'm was wondering a) if there's any specific reason why this doesn't work (from a w3c/HTML spec perspective) and b) what the right way to go about getting draggable table rows is.</p>
<p>I like real tables because of the border collapsing and row height algorithm -- any alternative that can do those things would work fine.</p>
|
<p>If you have truly tabular data, you should stick with table indeed.</p>
<p>And if you want to drag rows <em>within</em> a table, this <strong><a href="http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/" rel="noreferrer">JQuery + "draggable row table" library</a></strong> works perfectly in FireFox3</p>
|
<p>One can also set css <code>tr.ui-draggable-dragging {display: block}</code> - this way one can drag the rows, however, their coordinates are poorly calculated. I haven't found a good solution for this issue yet.</p>
| 39,642
|
<p>I have built a 3D printer with Marlin bugfix-2.0.x forked from github.</p>
<p>I am attempting to set the default value for junction deviation so that I don't have to change it through the printer's screen/interface every time I power cycle the printer, but what I thought would set it properly isn't doing the trick.</p>
<p>My thought was that uncommenting this in Configuration_adv.h would work:</p>
<pre><code>#define JUNCTION_DEVIATION_MM 0.02
</code></pre>
<p>I have tried setting this define inside of and outside of the default <code>if</code> block in which it appears, just to make sure the issue wasn't because I didn't have something else set, and I get the same behavior when this <code>define</code> statement is either protected or unprotected by an <code>if</code></p>
<p>Also, the default <code>if</code> block is this:</p>
<pre><code>#if ENABLED( JUNCTION_DEVIATION )
#define JUNCTION_DEVIATION_MM 0.02
#endif
</code></pre>
<p>Uncommenting <code>#define JUNCTION_DEVIATION</code> leaves me with a compiler error telling me that I don't need to do that, so I'm not seeing anything that I am supposed to enable to get it to use the JUNCTION_DEVIATION_MM setting. In other words, I can't actually enable "JUNCTION_DEVIATION" any more, so I HAVE to break the JUNCTION_DEVIATION_MM setting out of the <code>if</code> but it still has no effect.</p>
<p>After setting this parameter, when I power cycle the printer, the junction deviation is set to 0 (although one touch of the adjustment knob makes it jump to 0.010, so I think that what is displayed as "0" may actually mean "unset"), which is causing a significant stop/start jerk on every angle change until I manually set the junction deviation.</p>
<p>My current <a href="https://github.com/appideasDOTcom/Marlin/blob/printerx/Marlin/Configuration.h" rel="nofollow noreferrer">Configuration.h</a> and <a href="https://github.com/appideasDOTcom/Marlin/blob/printerx/Marlin/Configuration_adv.h" rel="nofollow noreferrer">Configuration_adv.h</a> are taken from <a href="https://github.com/appideasDOTcom/Marlin/tree/printerx/Marlin" rel="nofollow noreferrer">this Marlin fork</a>.</p>
<p>In case it matters, I'm running this on an SKR V1.3 with TMC2208 drivers at 24V.</p>
<p>Any ideas what I'm missing? I'm sure it's something simple, I just haven't found it.</p>
<p><strong>UPDATE:</strong> Still no solution after 10 days. Here is additional information from another forum where I posted this request:</p>
<blockquote>
<p>Did you run <code>M502</code> and <code>M500</code> after updating your firmware?</p>
</blockquote>
<p>I dug into this a little more, and I am either running into a bug, or I'm simply not understanding what I'm supposed to be seeing.</p>
<p>I send this command:</p>
<p><code>M205 J0.020</code></p>
<p>Then verify that junction deviation is set correctly (it is)
Then this:</p>
<p><code>M500</code></p>
<p>And that responds with:</p>
<p><code>Settings Stored (616 bytes; crc 51371)</code></p>
<p>Then I send this:</p>
<p><code>M503</code></p>
<p>And the report for M205 is missing the setting I just confirmed to have changed and been working:</p>
<p><code>...
M205 B20000.00 S0.00 T0.00
...</code></p>
<p>And power cycling or resetting the controller leads to the same result: Junction Deviation is reset to 0.</p>
<p>Shouldn't I see "J0.020" in the M205 line immediately after changing the setting, and verifying that it works?</p>
|
<p>I've bought an SKR Pro V1.1 which is suffering from the same problem. It has actually to do with a shortcoming or design flaw (of the "HAL" or "Hardware Abstraction Layer" addressing of SPI devices) of Marlin and access to the SD card; I <a href="https://github.com/MarlinFirmware/Marlin/pull/16260" rel="nofollow noreferrer">quote</a>:</p>
<blockquote>
<p>The problem: On board SD-Card on SKR-PRO 1.1 can't be used. </p>
</blockquote>
<p>After the SD card has been inserted, the firmware binary is loaded into memory, and all access to the SD card is gone. The initial connection is by hardware design of the SKR boards.</p>
<p>Basically, there is a bug in the Marlin code/SKR boards preventing storing (to the SD card) any alterations after the firmware is loaded. There is a <a href="https://github.com/MarlinFirmware/Marlin/pull/16260" rel="nofollow noreferrer">PR on Marlin</a> that fixes it, but it has not been merged into Marlin yet.</p>
<p>There are 2 options, </p>
<ol>
<li>Every change to the firmware has to be compiled and uploaded to the board by placing a hex (firmware.bin) on the SD card;</li>
<li>Compile a firmware version from the sources from the fore mentioned PR.</li>
</ol>
|
<p>For the SKR, to store the new Marlin definitions it is necessary to send the comand <code>M502</code> to restore to the factory settings (will use the configuration on the SD card) and send the comand <code>M500</code> to save the configurations.</p>
| 1,497
|
<p>For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.</p>
<p>The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.</p>
<pre><code>[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}</code></pre>
<p>The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.</p>
<p>Following is a snippet of my web.config:</p>
<p><pre><code><profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile></pre></code></p>
<p>The MembershipProvider is working without a hitch, so I know that the connection string is good.</p>
<p>Just in case it's helpful, here is my ProfileCommon class:</p>
<pre><code>public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}</code></pre>
<p>Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?</p>
<p>Thank you in advance...</p>
|
<p>Here's what you need to do:</p>
<p>1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings:</p>
<pre><code><profile inherits="MySite.Models.ProfileCommon" defaultProvider="....
</code></pre>
<p>2) Remove entire <code><properties></code> section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step</p>
<p>3) Change the code of your ProfileCommon.GetProfile() method to </p>
<pre><code>public virtual ProfileCommon GetProfile(string username)
{
return Create(username) as ProfileCommon;
}
</code></pre>
<p>Hope this helps.</p>
|
<p>The web.config file in the MVC Beta is wrong. The SqlProfileProvider is in System.Web.Profile, not System.Web.Security. Change this, and it should start working for you.</p>
| 10,451
|
<p>Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?</p>
<p>Something like this would work perfect:</p>
<pre><code>Public Property FirstName() As String
Get
Set
End Property
</code></pre>
<p><strong>UPDATE:</strong> VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: <a href="https://web.archive.org/web/20200119055303/http://geekswithblogs.net:80/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx</a></p>
<p>In VB.NET 10 Automatic Properties will be defines like this:</p>
<pre><code>Public Property CustomerID As Integer
</code></pre>
|
<p>One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by <a href="http://www.panopticoncentral.net/archive/2008/03/27/23050.aspx" rel="noreferrer">Paul Vick's post</a> on the matter. This is unfortunate because it means a delay in many cases (automatic properties, iterator methods, multiline lambdas, to name but a few) but on the other hand, the VB developers usually get a much more mature feature in the long run (looking at the discussion, this will be especially true for iterator methods).</p>
<p>So, long story short: VB 10 will (hopefully!) see automatic properties.</p>
|
<p>automatic properties are not necessary in vb
the concession one makes by using an automatic property is that you can not modify the Get and Set. </p>
<p>If you dont require those, just make a public data field. </p>
<p>VB has had automatic properties for years. They just called them something else. </p>
| 14,880
|
<p>Is it Oracle or MySQL or something they have built themselves?</p>
|
<h2>Bigtable</h2>
<p><a href="http://research.google.com/archive/bigtable.html" rel="noreferrer">A Distributed Storage System for Structured Data</a></p>
<blockquote>
<p>Bigtable is a distributed storage
system (built by Google) for managing structured data
that is designed to scale to a very
large size: petabytes of data across
thousands of commodity servers.</p>
<p>Many projects at Google store data in
Bigtable, including web indexing,
Google Earth, and Google Finance.
These applications place very
different demands on Bigtable, both in
terms of data size (from URLs to web
pages to satellite imagery) and
latency requirements (from backend
bulk processing to real-time data
serving). </p>
<p>Despite these varied
demands, Bigtable has successfully
provided a flexible, high-performance
solution for all of these Google
products.</p>
</blockquote>
<p><strong>Some features</strong></p>
<ul>
<li>fast and extremely large-scale DBMS</li>
<li>a sparse, distributed multi-dimensional sorted map, sharing characteristics of both row-oriented and column-oriented databases.</li>
<li>designed to scale into the petabyte range</li>
<li>it works across hundreds or thousands of machines</li>
<li>it is easy to add more machines to the system and automatically start taking advantage of those resources without any reconfiguration</li>
<li>each table has multiple dimensions (one of which is a field for time, allowing versioning)</li>
<li>tables are optimized for GFS (Google File System) by being split into multiple tablets - segments of the table as split along a row chosen such that the tablet will be ~200 megabytes in size.</li>
</ul>
<p><strong>Architecture</strong></p>
<p>BigTable is not a relational database. It does not support joins nor does it support rich SQL-like queries. Each table is a multidimensional sparse map. Tables consist of rows and columns, and each cell has a time stamp. There can be multiple versions of a cell with different time stamps. The time stamp allows for operations such as "select 'n' versions of this Web page" or "delete cells that are older than a specific date/time." </p>
<p>In order to manage the huge tables, Bigtable splits tables at row boundaries and saves them as tablets. A tablet is around 200 MB, and each machine saves about 100 tablets. This setup allows tablets from a single table to be spread among many servers. It also allows for fine-grained load balancing. If one table is receiving many queries, it can shed other tablets or move the busy table to another machine that is not so busy. Also, if a machine goes down, a tablet may be spread across many other servers so that the performance impact on any given machine is minimal.</p>
<p>Tables are stored as immutable SSTables and a tail of logs (one log per machine). When a machine runs out of system memory, it compresses some tablets using Google proprietary compression techniques (BMDiff and Zippy). Minor compactions involve only a few tablets, while major compactions involve the whole table system and recover hard-disk space.</p>
<p>The locations of Bigtable tablets are stored in cells. The lookup of any particular tablet is handled by a three-tiered system. The clients get a point to a META0 table, of which there is only one. The META0 table keeps track of many META1 tablets that contain the locations of the tablets being looked up. Both META0 and META1 make heavy use of pre-fetching and caching to minimize bottlenecks in the system.</p>
<p><strong>Implementation</strong></p>
<p>BigTable is built on <strong>Google File System</strong> (GFS), which is used as a backing store for log and data files. GFS provides reliable storage for SSTables, a Google-proprietary file format used to persist table data.</p>
<p>Another service that BigTable makes heavy use of is <strong>Chubby</strong>, a highly-available, reliable distributed lock service. Chubby allows clients to take a lock, possibly associating it with some metadata, which it can renew by sending keep alive messages back to Chubby. The locks are stored in a filesystem-like hierarchical naming structure.</p>
<p>There are three primary <strong>server types</strong> of interest in the Bigtable system:</p>
<ol>
<li>Master servers: assign tablets to tablet servers, keeps track of where tablets are located and redistributes tasks as needed. </li>
<li>Tablet servers: handle read/write requests for tablets and split tablets when they exceed size limits (usually 100MB - 200MB). If a tablet server fails, then a 100 tablet servers each pickup 1 new tablet and the system recovers. </li>
<li>Lock servers: instances of the Chubby distributed lock service. Lots of actions within BigTable require acquisition of locks including opening tablets for writing, ensuring that there is no more than one active Master at a time, and access control checking.</li>
</ol>
<p><strong>Example from Google's research paper:</strong></p>
<p><img src="https://i.stack.imgur.com/oN41X.png" alt="alt text"></p>
<blockquote>
<p>A slice of an example table that
stores Web pages. The row name is a
<strong>reversed URL</strong>. The contents column
family contains the <strong>page contents</strong>, and
the anchor column family contains the
<strong>text of any anchors</strong> that reference the
page. CNN's home page is referenced by
both the Sports Illustrated and the
MY-look home pages, so the row
contains columns named
<code>anchor:cnnsi.com</code> and
<code>anchor:my.look.ca</code>. Each anchor cell
has <strong>one version</strong>; the contents column
has <strong>three versions</strong>, at timestamps
<code>t3</code>, <code>t5</code>, and <code>t6</code>.</p>
</blockquote>
<p><strong>API</strong></p>
<p>Typical operations to BigTable are creation and deletion of tables and column families, writing data and deleting columns from a row. BigTable provides this functions to application developers in an API. Transactions are supported at the row level, but not across several row keys.</p>
<hr>
<p>Here is the <a href="http://research.google.com/archive/bigtable-osdi06.pdf" rel="noreferrer">link to the PDF of the research paper</a>. </p>
<p>And here you can find a <a href="http://norfolk.cs.washington.edu/htbin-post/unrestricted/colloq/archive.cgi?id=437" rel="noreferrer">video showing Google's Jeff Dean in a lecture at the University of Washington</a>, discussing the Bigtable content storage system used in Google's backend.</p>
|
<p>Google services have a polyglot persistence architecture. BigTable is leveraged by most of its services like YouTube, Google Search, Google Analytics etc. The search service initially used MapReduce for its indexing infrastructure but later transitioned to BigTable during the Caffeine release. </p>
<p>Google Cloud datastore has over 100 applications in production at Google both facing internal and external users. Applications like Gmail, Picasa, Google Calendar, Android Market & AppEngine use Cloud Datastore & Megastore.</p>
<p>Google Trends use MillWheel for stream processing. Google Ads initially used MySQL later migrated to F1 DB - a custom written distributed relational database. Youtube uses MySQL with Vitess. Google stores exabytes of data across the commodity servers with the help of the Google File System. </p>
<p>Source: <a href="https://www.8bitmen.com/google-database-how-do-google-services-store-petabyte-exabyte-scale-data/" rel="nofollow noreferrer">Google Databases: How Do Google Services Store Petabyte-Exabyte Scale Data?</a></p>
<p><a href="https://www.8bitmen.com/youtube-database-how-does-it-store-so-many-videos-without-running-out-of-storage-space/" rel="nofollow noreferrer">YouTube Database – How Does It Store So Many Videos Without Running Out Of Storage Space?</a></p>
<p><a href="https://i.stack.imgur.com/nOHXD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nOHXD.jpg" alt="enter image description here"></a></p>
| 47,377
|
<p>Can anyone explain in simple words what First and Second Level caching in Hibernate/NHibernate are?</p>
|
<p>1.1) First-level cache</p>
<blockquote>
<p><strong>First-level cache</strong> always Associates with the <strong>Session object</strong>. Hibernate uses this cache by default. Here, it processes one
transaction after another one, means wont process one transaction many
times. Mainly it reduces the number of SQL queries it needs to
generate within a given transaction. That is instead of updating after
every modification done in the transaction, it updates the transaction
only at the end of the transaction.</p>
</blockquote>
<p>1.2) Second-level cache</p>
<blockquote>
<p><strong>Second-level cache</strong> always associates with the <strong>Session Factory object</strong>. While running the transactions, in between it loads the
objects at the Session Factory level, so that those objects will be
available to the entire application, not bound to single user. Since
the objects are already loaded in the cache, whenever an object is
returned by the query, at that time no need to go for a database
transaction. In this way the second level cache works. Here we can use
query level cache also.</p>
</blockquote>
<p>Quoted from: <a href="http://javabeat.net/introduction-to-hibernate-caching/" rel="noreferrer">http://javabeat.net/introduction-to-hibernate-caching/</a></p>
|
<p>In a second level cache, domain hbm files can be of key mutable and value false.
For example,
In this domain class some of the duration in a day remains constant as the universal truth. So, it can be marked as immutable across application.</p>
| 43,734
|
<p>I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: </p>
<p>1) creating each destination database<br>
2) using the "<a href="http://msdn.microsoft.com/en-us/library/ms140052.aspx" rel="noreferrer">Tasks->Export Data</a>" command to create and populate tables for each database individually<br>
3) rebuilding all of the indexes for each database with a SQL script </p>
<p>Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?</p>
|
<p>Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.</p>
<p>This is a backup script that i keep around.
Get it working for one file and then modify it for many.</p>
<pre><code>(on source server...)
BACKUP DATABASE Northwind
TO DISK = 'c:\Northwind.bak'
(target server...)
RESTORE FILELISTONLY
FROM DISK = 'c:\Northwind.bak'
(look at the device names... and determine where you want the mdf and
ldf files to go on this target server)
RESTORE DATABASE TestDB
FROM DISK = 'c:\Northwind.bak'
WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf',
MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'
GO
</code></pre>
|
<p>use backups to restore the databases to the new server with the new names.</p>
| 10,507
|
<p>If I have the following code,</p>
<pre><code>Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
</code></pre>
<p>Did I create a memory leak?
I guess so, but the word <em>erase</em> gives the feeling that it is deleting it. </p>
<p>Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?</p>
|
<p>Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.</p>
<p>It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:</p>
<pre><code>{
boost::shared_ptr<foo> f(new foo);
std::vector< boost::shared_ptr<foo> > v;
v.push_back(f);
v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */
</code></pre>
<p>The next C++ standard (called C++1x and C++0x commonly) will include <code>std::shared_ptr</code>. There, you will also be able to use <code>std::unique_ptr<T></code> which is faster, as it doesn't allow copying. Using <code>std::unique_ptr</code> with containers in c++0x is similar to the <code>ptr_container</code> library in boost.</p>
|
<p>It is definitely not a mistake to point a pointer into a standard container (it's a mistake to make a container of auto_ptr's however). Yes, you do need to explicitly delete to free the memory pointed to by the individual elements, or you can use one of the boost <a href="http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm" rel="nofollow noreferrer">smart pointers</a>.</p>
| 35,599
|
<p>I am using WCF to upload data to a server.</p>
<p>If the communication fails, is there any way to resume the upload?</p>
|
<p>This</p>
<pre><code>eval {
qr/$re/;
};
if ( $@ ) {
# do something
}
</code></pre>
<p>compiles an expression, and lets you recover from an error. </p>
<p>You can watch for malicious expression, since you're only going to do matching, by looking for these patterns, which would allow arbitrary code to be run:</p>
<pre><code>(?: \( \?{1,2} \{ # '(' followed by '?' or '??', and then '{'
| \@ \{ \s* \[ # a dereference of a literal array, which may be arbitrary code.
)
</code></pre>
<p>Make sure you compile this with the <code>x</code> flag. </p>
|
<p>Would the <a href="http://perldoc.perl.org/Safe.html" rel="nofollow noreferrer" title="Safe">Safe</a> module be of any use with regard to compiling/executing untrusted regular expressions?</p>
| 29,972
|
<p>How do I convert between big-endian and little-endian values in C++?</p>
<p>For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.</p>
<hr />
<p>Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.</p>
|
<p>If you're using <strong>Visual C++</strong> do the following: You include intrin.h and call the following functions:</p>
<p>For 16 bit numbers:</p>
<pre><code>unsigned short _byteswap_ushort(unsigned short value);
</code></pre>
<p>For 32 bit numbers:</p>
<pre><code>unsigned long _byteswap_ulong(unsigned long value);
</code></pre>
<p>For 64 bit numbers:</p>
<pre><code>unsigned __int64 _byteswap_uint64(unsigned __int64 value);
</code></pre>
<p>8 bit numbers (chars) don't need to be converted.</p>
<p>Also these are only defined for unsigned values they work for signed integers as well.</p>
<p>For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.</p>
<p>Other compilers have similar intrinsics as well. </p>
<p>In <strong>GCC</strong> for example you can directly call <a href="https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html" rel="noreferrer">some builtins as documented here</a>:</p>
<pre><code>uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
</code></pre>
<p>(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.</p>
<p>16 bit swap it's just a bit-rotate.</p>
<p>Calling the intrinsics instead of rolling your own gives you the best performance and code density btw.. </p>
|
<p>Look up bit shifting, as this is basically all you need to do to swap from little -> big endian. Then depending on the bit size, you change how you do the bit shifting.</p>
| 13,079
|
<p>I want to highlight C/C++/Java/C# etc source codes in my website.</p>
<p>How can I do this?</p>
<p>Is it a CPU intensive job to highlight the source code?</p>
|
<p>You can either do this server-side or client-side. It's not very processor intensive, but if you do it client side (using Javascript) there will be a noticeable lag. Most client side solutions revolve around Google Code's syntax highlighting engine. This seems to be the most popular one: <a href="http://alexgorbatchev.com/SyntaxHighlighter/" rel="nofollow noreferrer">SyntaxHighlighter</a></p>
<p>Server-side solutions tend to be more flexible, especially in the way of defining new languages and configuring how they are highlighted (e.g. colors used). I use GeSHi, which is a PHP solution with a moderately nice plugin for Wordpress. There are also a few libraries built for Java, and even some that are based upon VIM (usually requiring a Perl module to be installed from CPAN).</p>
<p>In short: you have quite a few options, what are your criteria? It's hard to make a solid recommendation without knowing your requirements.</p>
|
<p>I use <a href="http://code.google.com/p/syntaxhighlighter/wiki/Usage" rel="nofollow noreferrer">SyntaxHighligher</a> on <a href="http://bradwilson.typepad.com" rel="nofollow noreferrer">my blog</a>.</p>
| 9,557
|
<p>Ages ago when I was a java developer I could make separate ant scripts that I would call from my main ant script. I would put properties unique to each environment where my main script would run. I want to do the same thing in MSBuild but I can't find out how to chain MSBuild scripts together.</p>
|
<p>You need to <a href="http://msdn.microsoft.com/en-us/library/92x05xfs.aspx" rel="nofollow noreferrer">Import</a> them.</p>
<pre><code> <Import Project="MyTargets" Condition="Exists('MyTargets')"/>
</code></pre>
|
<p>The import is definitely useful, you can also actively invoke other projects:</p>
<pre><code><MSBuild Projects="Other.proj" Properties="SomeProp=$(MyProperty)" />
</code></pre>
| 33,847
|
<p>If I am to send a message to a mobile device from a website and viceversa, how can that be done?</p>
<p>What I know: A couple of years ago I developed a simple enrollment system on J2ME platform(just for trying J2ME out). I had a mysql database that I setup in a pc/server, and for the communication I used the static IP of that server. I had a bridge, a mobile phone which was connected to the internet, where clients would send a formatted message. That bridge then would send the message to the server, after verification and validation, the server would respond back to the bridge, and finally the bridge will forward that message to the client. (I know..I know..!)</p>
|
<p>It can be done by using a mobile phone connected to your computer, but a more robust way would be to use an SMS aggregator - well known ones are <a href="http://www.mblox.com/" rel="nofollow noreferrer">Mblox</a> or <a href="http://www.hslsms.com/" rel="nofollow noreferrer">Hay</a>, but a google search will show many more.</p>
<p>They will support both sending and receiving SMS messages</p>
<p>(Disclaimer: no connection with either, although my employer does use Hay)</p>
|
<p>The short answer is that you have 4 options: </p>
<ul>
<li>Having your own SMS server </li>
</ul>
<p>OR</p>
<ul>
<li>Having to use the webportal for each provider you want to sent the message</li>
</ul>
<p>OR</p>
<ul>
<li>Some provider let you send SMS with email to SMS</li>
</ul>
<p>OR</p>
<ul>
<li>Use some services that let you send SMS via their webservices (this usually cost some money to subscribe).</li>
</ul>
| 42,274
|
<p>So I want to trigger an event (pausing/unpausing some media) whenever the user presses spacebar anywhere in the my Swing app.</p>
<p>Since there are so many controls and panels that could have focus, its not really possible to add keyevents to them all(not to mention gross).</p>
<p>So I found </p>
<pre><code>KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher()
</code></pre>
<p>which is awesome, you can register global keypress pre-handlers. There's a major problem though - spaces will be typed all the time in input fields, table cells, etc, and I obviously dont want to trigger the pause event then!</p>
<p>So any ideas?
Perhaps there is way to detect globally whether the cursor is focused on something that allows text input, without having to check through a list of all the editable controls(vomit!)? </p>
|
<p>I think you answered that yourself - yes I think you can find out the current element that has focus, and if it is an instanceof a certain field class, you ignore the space for the purpose of pause event. If it seams heavy handed, don't worry, instanceof is VERY fast for the JVM (and in any cause you are talking human scale events which are an eon to a processor).</p>
|
<p>Ok...
Well im trying to filter based on source. Problem is my editable ComboBoxes...
They are instanceof </p>
<pre><code>javax.swing.plaf.basic.BasicComboBoxEditor$BorderlessTextField
</code></pre>
<p>And since BorderlessTextField is a private inner class, I apparently cant do an instanceof check against it.</p>
<p>ideas?</p>
<p>EDIT:
ok so this works....</p>
<pre><code> KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor() {
public boolean postProcessKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
Object s = e.getComponent();
if (!(s instanceof JTextField) &&
!(s instanceof JTable && ((JTable) s).isEditing())
) {
music_player.pauseEvent();
}
//System.out.println(s.getClass().toString());
}
return true;
}
});
</code></pre>
<p>Its totally gross and I hate it.
I wish I could figure out a way to check if the keypress has been consumed by any component - then I could only perform the pause event when the keypress was not actioned by any component.</p>
| 33,163
|
<p>I have the .net framework 3.5 on my development machine and also am using the AJAX toolkit in my code. In order to publish this code to a server for my users, do I need anything on the server in order for my AJAX code to operate correctly? </p>
|
<p>You need only the .NET framework 3.5.</p>
<p>If you publish your project, the AJAX Toolkit used will be also copied over. If you only reference the AJAX Toolkit via file, not via project, then be sure you set the dll to "Copy always" in the properties window.</p>
|
<p>Of course, you will need to install the .NET Framework on your server. If you are using the AJAX Toolkit you will want to copy over the AjaxControlToolkit.dll to the bin folder of your web application on your server. </p>
<p>Also want to make sure that you set your web application to use .NET Framework 2.0. In IIS you go to the properties of your web site, then the ASP.NET tab and make sure ASP.NET version is set to 2.0. </p>
| 14,679
|
<p>Is it possible to define a timestamp column in a MySQL table that will automatically be updated every time a field in the same row is modified? Ideally this column should initially be set to the time a row was inserted.</p>
<p>Cheers,
Don</p>
|
<p>That is the default functionality of the <strong><a href="http://dev.mysql.com/doc/refman/5.0/en/timestamp.html" rel="noreferrer">timestamp</a></strong> column type. However, note that the format of this type is yyyymmddhhmmss (all digits, no colons or other separation).</p>
<p><strong>EDIT:</strong> The above comment about the format is only true for versions of MySQL < 4.1... Later versions format it like a <strong>DateTime</strong></p>
|
<p>A MySQL timestamp is set with creation or update time only if their default value is set as it. <code>ALTER TABLE some_table ADD when TIMESTAMP DEFAULT CURRENT_TIMESTAMP</code>.<br>
Otherwise it works just like a DateTime field, only that it's relative to 1970/01/01 UTC, so it's an absolute point in time not depending on a specific timezone as is DateTime.</p>
| 18,743
|
<p>I have a program that writes to a FILE *cgiOut and just after it has written to the stream, I need to fork and run a background process. The trouble is that after the fork, the FILE * stream seems to flush out sometimes and I get duplicated output (after the fork, all open files are closed which I guess causes the buffers to be flushed). How can I avoid this? I don't want to close the file in the master process as it is opened in a library and it is a socket or pipe I think.</p>
|
<p>Not quite sure I understand your question, but if you want to make sure your <code>cgiOut</code> buffers are empty before you <code>fork()</code> you can use <code>fflush()</code> on the stream just before you <code>fork()</code>. That should force the buffers to be flushed.</p>
<p>It maybe suitable to use an unbuffered stream, by changing the buffering settings via <code>setvbuf()</code> and friends. This way you won't (read: shouldn't) have any buffering issues, but it might not be what you want.</p>
|
<p><a href="http://opengroup.org/onlinepubs/007908775/xsh/fflush.html" rel="nofollow noreferrer"><code>fflush(file)</code></a></p>
| 44,602
|
<p>I've been trying to run a jar file - let's call it test.jar - that uses the Sybase jconn3.jar on a Unix system.</p>
<p>I have created a MANIFEST.MF file that has the following:</p>
<pre><code>Class-Path: $SYBASE/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar
</code></pre>
<p>This gives a ClassNotFoundError. $SYBASE is the system variable that points to /opt/sybase13; I've also tried the following:</p>
<pre><code>Class-Path: /opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar
</code></pre>
<p>and</p>
<pre><code>Class-Path: opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar
</code></pre>
<p>However, if I copy the jconn3.jar file from the $SYBASE/jConnect-6_0/classes to the same directory as test.jar, and update my MANIFEST.MF to read as follows:</p>
<pre><code>Class-Path: jconn3.jar commons-net-1.3.0.jar
</code></pre>
<p>The application runs as expected.</p>
<p>Now, I've been able to verify the jconn3.jar file works by copying it locally; my MANIFEST.MF file includes the path to my Main-Class, so that's not at issue here.</p>
<p>What do you think could be the problem? I've been looking at this thing for too long now.
Thanks!</p>
|
<p>The entries in the class-path are either relative to the JAR in which they are embedded (which you have working) or are URLs. To make your absolute paths work, you'll need to convert them to URLs, e.g., </p>
<p><code>file:/opt/sybase13/...</code></p>
<p>There's no mechanism for using variables.</p>
<p>Although the JAR specification doesn't say it clearly, absolute <code>file:</code> scheme URLs do work in the class-path attribute.</p>
|
<p>Environment variables are not readed by the classloader AFAIK. However you could add the jar in a configuration script</p>
<p>Accoding to the specification the entries are relatives to the jar not absolute:</p>
<blockquote>
<p>Class-Path :</p>
<p>The value of this attribute specifies the relative URLs of the extensions or libraries that this application or extension needs. URLs are separated by one or more spaces. The application or extension class loader uses the value of this attribute to construct its internal search path.</p>
</blockquote>
<p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html</a> #Manifest Specification</p>
| 43,077
|
<p>How do I clear the cin buffer in C++?</p>
|
<p>Possibly:</p>
<pre><code>std::cin.ignore(INT_MAX);
</code></pre>
<p>This would read in and ignore everything until <code>EOF</code>. (you can also supply a second argument which is the character to read until (ex: <code>'\n'</code> to ignore a single line).</p>
<p>Also: You probably want to do a: <code>std::cin.clear();</code> before this too to reset the stream state.</p>
|
<p>fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement.</p>
<p>fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement.
The following should work:</p>
<p>cin.flush();
On some systems it's not available and then you can use:</p>
<p>cin.ignore(INT_MAX);
Both Windows and Linux define the behaviour of fflush() on an input stream,
and even define it the same way (miracle of miracles).
The POSIX, C and C++ standards for fflush() do not define the behaviour,
but none of them prevent a system from defining it.
If you're coding for maximum portability, avoid fflush(stdin);
if you're coding for platforms that define the behaviour, use it — but be aware that it is not portable
portable code does not use fflush(stdin). Code that is tied to Microsoft's platform may use it and
it may work as expected, but beware of the portability issues.</p>
| 32,078
|
<p>My only problem is making them line up three-across and have equal spacing. Apparently, spans can not have width and divs (and spans with display:block) don't appear horizontally next to each other. Suggestions?</p>
<p><code><div style='width:30%; text-align:center; float:left; clear:both;'></code> Is what I have now.</p>
|
<p>You can use divs with the <code>float: left;</code> attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap. </p>
|
<p>Look at the css Float property. <a href="http://w3schools.com/css/pr_class_float.asp" rel="nofollow noreferrer">http://w3schools.com/css/pr_class_float.asp</a></p>
<p>It works with block elements like div. Alternatively, what are you trying to display, tables aren't evil if you're really trying to show a table of some information.</p>
| 27,934
|
<p>I'm printing a cylindrical piece but at any moment it breaks down. I tried it two times, both have break down in different place. I'm using a 1.75 mm PLA filament in my Anet A8. I'm using Cura 2.6.2 to export to a <code>.gcode</code> file.</p>
<p>This is the original model: </p>
<p><a href="https://i.stack.imgur.com/mglT8.png" rel="nofollow noreferrer" title="Original model"><img src="https://i.stack.imgur.com/mglT8.png" alt="Original model" title="Original model"></a></p>
<p>And this is the result:</p>
<p><a href="https://i.stack.imgur.com/mtYyb.jpg" rel="nofollow noreferrer" title="Printed result"><img src="https://i.stack.imgur.com/mtYyb.jpg" alt="Printed result" title="Printed result"></a></p>
<p>Here is the <a href="https://mega.nz/#!1hkyhLBA!xmt7s38vrb7fEh9SkiSYWfgwLxg4WaYED1h6vzUpghg" rel="nofollow noreferrer">G-code file</a>.</p>
|
<p>The first thought that pops into my mind is insufficient cooling. Consider to either slow down the nozzle speed or to construct a toss-away model nearby. I prefer the toss-away or duplicate model method. It allows the material printed on the first column to cool more effectively while the material on the second column is being deposited. </p>
<p>If the problem persists, add a third column or slow the print speed about 10 mm / second</p>
|
<p>The first thought that pops into my mind is insufficient cooling. Consider to either slow down the nozzle speed or to construct a toss-away model nearby. I prefer the toss-away or duplicate model method. It allows the material printed on the first column to cool more effectively while the material on the second column is being deposited. </p>
<p>If the problem persists, add a third column or slow the print speed about 10 mm / second</p>
| 744
|
<p>How do I load a true color image into a CImageList?</p>
<p>Right now I have</p>
<pre><code>mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255));
</code></pre>
<p>Where <code>IDB_IMGLIST_BGTASK</code> is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.</p>
|
<p>Needs 4 lines of code, but this works:</p>
<pre><code>CBitmap bm;
bm.LoadBitmap(IDB_IMGLIST_BGTASK);
mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4);
mImageList.Add(&bm, RGB(255,0,255));
</code></pre>
|
<pre><code>CImageList::Create(int cx, int cy, UINT nFlags, int nInitial, int nGrow)
</code></pre>
<p>allows to specify different flags with the <code>nFlags</code> parameter. You can try to use something like <code>ILC_COLOR32 | ILC_MASK</code>.</p>
| 27,947
|
<p>I have a string which starts with <code>//#...</code> goes upto the newline characater. I have figured out the regex for the which is this <code>..#([^\n]*)</code>.</p>
<p>My question is how do you remove this line from a file if the following condition matches</p>
|
<p>Your regex is badly chosen on several points:</p>
<ol>
<li><p>Instead of matching two slashes specifically, you use <code>..</code> to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match <em>almost</em> anything, as we’ll see in #3.)</p>
<p>Within a slash-delimited regex literal, <code>//</code>, you can match slashes simply by protecting them with backslashes, eg. <code>/\/\//</code>. The nicer variant, however, is to use the longer form of regex literal, <code>m//</code>, where you can choose the delimiter, eg. <code>m!!</code>. Since you use something other than slashes for delimitation, you can then write them without escaping them: <code>m!//!</code>. See <a href="http://p3rl.org/op#Quote-and-Quote-like-Operators" rel="noreferrer">perldoc perlop</a>.</p></li>
<li><p>It’s not anchored to the start of the string so it will match anywhere. Use the <code>^</code> start-of-string assertion in front.</p></li>
<li><p>You wrote <code>[^\n]</code> to match “any character except newline” when there is a much simpler way to write that, which is just the <code>.</code> wildcard. It does exactly that – match any character except newline.</p></li>
<li><p>You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous.</p></li>
</ol>
<p>Altogether, that makes it <code>m!^//#.*!</code>. But putting an uncaptured <code>.*</code> (or anything with a <code>*</code> quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the <code>*</code> is happy to match nothing at all.</p>
<p>So that leaves you with <code>m!^//#!</code>.</p>
<p>As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily:</p>
<pre><code>perl -ni.bak -e'print unless m!^//#!' somefile.txt
</code></pre>
<p>Here, the <code>-n</code> switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The <code>-i</code> switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The <code>.bak</code> parameter to the <code>-i</code> option tells perl to keep a backup of the original file in a file named after the original file name with <code>.bak</code> appended. For all of these bits, see <a href="http://p3rl.org/run" rel="noreferrer">perldoc perlrun</a>.</p>
<p>If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with <a href="http://p3rl.org/IO::AtomicFile" rel="noreferrer">IO::AtomicFile</a>, another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed.</p>
|
<p>Read the file line by line and only write those lines to a new file that don't match the regex.
You cannot just remove a line.</p>
| 10,588
|
<p>As a programmer I have no idea how one would go about programming menus for a DVD, I have heard that this is possible, and even seen basic games using DVD menus - although it may very well be a closed-system. Is it even possible and if so, what language, compilers etc exist for this?</p>
|
<p>There are a couple of open source projects that can create DVDs plus menus. I recently used <a href="https://web.archive.org/web/20201109023628/http://dvd-slideshow.sourceforge.net/wiki/Main_Page" rel="nofollow noreferrer">dvd-slideshow</a> to create a simple dvd with menus etc. Another one is <a href="http://www.dvdstyler.de/" rel="nofollow noreferrer">DVD Styler</a>. All of these programs are basically a front-end for various command-line tools for encoding, menu creation etc. Since these are open source projects you can have a look at the source and check out how they accomplish this.</p>
|
<p>Looks like <a href="http://dvdauthor.sourceforge.net/" rel="nofollow">http://dvdauthor.sourceforge.net/</a> is able to help here since you can use command line interface and feed xml files. </p>
<p>You may need to write a framework which can generate xml files (and other content) from your game authoring tool.</p>
| 8,930
|
<p>I'm programming in C++ on Visual Studio 2005. My question deals with .rc files. You can manually place include directives like (#include "blah.h"), at the top of an .rc file. But that's bad news since the first time someone opens the .rc file in the resource editor, it gets overwritten. I know there is a place to make these defines so that they don't get trashed but I can't find it and googling hasn't helped. Anyone know?</p>
|
<p>Add your #include to the file in the normal way, but also add it to one the three "TEXTINCLUDE" sections in the file, like so:</p>
<pre><code>2 TEXTINCLUDE
BEGIN
"#include ""windows.h""\r\n"
"#include ""blah.h\r\n"
"\0"
END
</code></pre>
<p>Note the following details:</p>
<ul>
<li>Each line is contained in quotes</li>
<li>Use pairs of quotes, <em>e.g.</em>, "" to place a quote character inline</li>
<li>End each line with \r\n</li>
<li>End the TEXTINCLUDE block with "\0"</li>
</ul>
<p>Statements placed in the "1 TEXTINCLUDE" block will be written to the beginning of the .rc file when the file is re-written by the resource editor. Statements placed in the 2 and 3 blocks follow, so you can guarantee relative include file order by using the appropriately numbered block.</p>
<p>If your existing rc file does not already include TEXTINCLUDE blocks, use the new file wizard from the Solution Explorer pane to add a new rc file, then use that as a template.</p>
|
<p>I'm not completely sure why you're trying to do, but modifying the resource files manually probably isn't a good idea.</p>
<p>I believe general practice for VC++ for globally-accessible values is to define them in stdafx.h (at least that's how I've seen it done), or to create something like a "globals.h" header file and include that wherever you need it. It really depends on what you're trying to accomplish though.</p>
| 12,094
|
<p>I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?</p>
|
<p>We have had to make a similar modifiaction. We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows.</p>
<p>Code added to jCarousel function...</p>
<p>Add to default options: </p>
<pre><code>moduleWidth: null,
rows:null,
</code></pre>
<p>Then set when creating jCarousel:</p>
<pre><code>$('.columns2.rows2 .mycarousel').jcarousel( {
scroll: 1,
moduleWidth: 290,
rows:2,
itemLoadCallback: tonyTest,
animation: 'slow'
});
</code></pre>
<p>The find and edit the lines in: </p>
<pre><code>$.jcarousel = function(e, o) {
if (li.size() > 0) {
...
moduleCount = li.size();
wh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows );
wh = wh + this.options.moduleWidth;
this.list.css(this.wh, wh + 'px');
// Only set if not explicitly passed as option
if (!o || o.size === undefined)
this.options.size = Math.ceil( li.size() / this.options.rows );
</code></pre>
<p>Hope this helps,</p>
<p>Tony Dillon</p>
|
<p>I tried the above solutions and found changing the original jCarousel code to be troublesome - it introduced buggy behaviour for me because it didn't play nice with some of the features of jCarousel such as the continous looping etc.</p>
<p>I used another approach which works great and I thought others may benefit from it as well. It is the JS code I use to create the li items to support a jCarousel with multiple rows with elegant flow of items, i.e. fill horizontally, then vertically, then scrollpages:</p>
<p>123 | 789<br>
456 | 0AB</p>
<p>It will add (value of var carouselRows) items to a single li and as such allows jCarousel to support multiple rows without modifying the original jCarousel code.</p>
<pre><code>// Populate Album photos with support for multiple rows filling first columns, then rows, then pages
var carouselRows=3; // number of rows in the carousel
var carouselColumns=5 // number of columns per carousel page
var numItems=25; // the total number of items to display in jcarousel
for (var indexpage=0; indexpage<Math.ceil(numItems/(carouselRows*carouselColumns)); indexpage++) // for each carousel page
{
for (var indexcolumn = 0; indexcolumn<carouselColumns; indexcolumn++) // for each column on that carousel page
{
// handle cases with less columns than value of carouselColumns
if (indexcolumn<numItems-(indexpage*carouselRows*carouselColumns))
{
var li = document.createElement('li');
for (var indexrow = 0; indexrow < carouselRows; indexrow++) // for each row in that column
{
var indexitem = (indexpage*carouselRows*carouselColumns)+(indexrow*carouselColumns)+indexcolumn;
// handle cases where there is no item for the row below
if (indexitem<numItems)
{
var div = document.createElement('div'), img = document.createElement('img');
img.src = imagesArray[indexitem]; // replace this by your images source
div.appendChild(img);
li.appendChild(div);
}
}
$ul.append(li); // append to ul in the DOM
}
}
}
</code></pre>
<p>After this code has filled the ul with the li items jCarousel should be invoked.</p>
<p>Hope this helps someone.</p>
<p>Jonathan</p>
| 26,268
|
<p>I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:</p>
<pre><code>$doc->addChild('myToken');
</code></pre>
<p>This generates (what I know as) a self-closing or single tag:</p>
<pre><code><myToken/>
</code></pre>
<p>However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:</p>
<pre><code><myToken></myToken>
</code></pre>
<p>The question is, how do I do this, outside of running the generated XML through a <strong>preg_replace</strong>?</p>
|
<p>From the documentation at <a href="http://www.php.net/manual/en/function.simplexml-element-construct.php" rel="nofollow noreferrer">SimpleXMLElement->__construct</a> and <a href="http://cz2.php.net/manual/en/libxml.constants.php" rel="nofollow noreferrer">LibXML Predefined Constants</a>, I think this should work:</p>
<pre><code><?php
$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);
// some processing here
$out = $sxe->asXML();
?>
</code></pre>
<p>Try that and see if it works. Otherwise, I'm afraid, it's preg_replace-land.</p>
|
<p>May be not the best solution but got same problem and solved it with using pre_replace to change all the self closing tags to full form...</p>
<pre><code>$xml_reader = new XMLReader;
$xml_reader->open($xml_file);
$data = preg_replace('/\<(\w+)\s*\/\s*\>/i', '<$1></$1>', $xml_reader->readOuterXML());
</code></pre>
| 32,452
|
<p>Using strictly SQL (no PHP or anything else), is it possible to create a table <strong>and insert default data into that table</strong> only if that table doesn't exist?</p>
|
<p>Use the CREATE TABLE ... SELECT format:</p>
<pre>create table if not exists tablename as
select * from defaultdata;</pre>
|
<p>Here is one way of doing it:</p>
<pre><code>CREATE TABLE IF NOT EXISTS T (
ID int(10) unsigned NOT NULL primary key,
NAME varchar(255) NOT NULL
);
REPLACE INTO T SELECT 1, 'John Doe';
REPLACE INTO T SELECT 2, 'Jane Doe';
</code></pre>
<p>REPLACE is a MySQL extension to the SQL standard that either inserts, or deletes and inserts.</p>
| 37,194
|
<p>When using Lucene.Net with ASP.NET, I can imagine that one web request can trigger an update to the index while another web request is performing a search. Does Lucene.Net have built in it the ability to manage concurrent access, or do I have to manage it, to avoid "being used by another process" errors?</p>
<p>EDIT: After reading docs and experimentation, this is what I think I've learned: There are two issues, thread safety and concurrency. Multithreading is "safe" in that you can't do anything bad to the index. But, it's safe at the cost of just one object having a lock on the index at one time. The second object will come along and throw an exception. So, you can't leave a search open and expect a writer in another thread to be able to update the index. And if a thread is busy updating the index, then trying to create a searcher will fail.</p>
<p>Also, Searchers see the index as it was at the time that they open it, so if you keep them around, and update the index, they won't see the updates. </p>
<p>I wanted my searchers to see the latest updates. </p>
<p>My design, and it seems to be working so far, is that my writers and searchers share a lock, so that they don't fail - they just wait - until the current write or search is done.</p>
|
<p>According to <a href="http://darksleep.com/lucene/" rel="noreferrer">this page</a>,</p>
<blockquote>
<p>Indexing and searching are not only
thread safe, but process safe. What
this means is that:</p>
<ul>
<li>Multiple index searchers can read the
lucene index files at the same time.</li>
<li>An index writer or reader can edit the
lucene index files while searches are
ongoing </li>
<li>Multiple index writers or
readers can try to edit the lucene
index files at the same time (it's
important for the index writer/reader
to be closed so it will release the
file lock). However, the query parser
is not thread safe, so each thread
using the index should have its own
query parser.</li>
</ul>
<p>The index writer however, is thread
safe, so you can update the index
while people are searching it.
However, you then have to make sure
that the threads with open index
searchers close them and open new
ones, to get the newly updated data.</p>
</blockquote>
|
<p>You don't have a problem with that so much as managing concurrent writes to the index. I've had an easier path going with SOLR, which abstracts most of those differences away for me since it runs as a server. </p>
| 23,529
|
<p>I'm working on a System Preferences Pane. It opens fine on some computers, but on other Macs (all running 10.5.5), the preference pane refuses to load and simply hangs, spitting the following into the console:</p>
<pre><code>11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: CGWindowContextCreate: failed to create context delegate.
11/9/08 8:38:55 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:55 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
</code></pre>
<p>Any ideas why this is happening?</p>
<p>Thanks.</p>
|
<p>You should read up on Reflection in Java.</p>
<p>The following example would invoke the method </p>
<p>myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)</p>
<pre><code>Integer[] params = {new Integer(123),new Integer(567)};
Class cl=Class.forName("stringParsedFromYourXML");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("methodNameAsString", parameterTypes);
mthd.invoke(new myObjectThatContainsMethod(), params);
</code></pre>
<p>hope that helps..</p>
|
<p>First, you need to choose an implementation of XACML. You should take one that is written in Java, to make things simpler.</p>
<p>Everything else depends on the chosen implementation. The implementation should document how to add custom functions. If it's not documented, ask the authors.</p>
| 34,962
|
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p>
<pre><code>sudo mod args
</code></pre>
<p>where mod is a perl script; so in python I would do </p>
<pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE)
</code></pre>
<p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p>
<pre><code>(stdout, stderr) = proc.communicate(input='y')
</code></pre>
<p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
|
<p>I would choose to go with Pexpect. </p>
<pre><code>import pexpect
child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q')
child.expect ('First question:')
child.sendline ('Y')
child.expect ('Second question:')
child.sendline ('Yup')
</code></pre>
|
<p>We need more information.</p>
<ol>
<li>Is sudo asking you for a password?</li>
<li>What kind of interface does the mod script have for asking questions?</li>
</ol>
<p>Because these kind of things are not handled as normal over the pipe.</p>
<p>A solution for both of these might be <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow noreferrer">Pexpect</a>, which is rather expert at handling funny scripts that ask for passwords, and various other input issues.</p>
| 31,201
|
<pre><code>$(document).ready(function() {
$("span.link").mouseover(function(e){
$(this.children).css("display","inline");
});
});
</code></pre>
<p>I'm not a javascript expert, but I've cobbled together a few functions using jQuery. </p>
<p>In this case, the stylesheet hides some controls. When the user mouses over, this function exposes those controls. </p>
<p>This works on every browser but Firefox (on the Mac and Windows). Am I missing something obvious? </p>
<p>Thanks for your help,</p>
<p>Jason</p>
|
<p>Try it like this:</p>
<pre><code>$(function() {
$("span.link").mouseover(function(e){
$(this).children().css("display","inline");
});
});
</code></pre>
|
<p>Check out this <a href="http://tredosoft.com/Multiple_IE" rel="nofollow noreferrer">app</a> which installs multiple versions of Internet Explorer</p>
<p>...ranging from v3, v4, v5 and most importantly, v6 (you should include tests in ie6 when developing)</p>
| 45,486
|
<p>This is one of the possible ways I come out:</p>
<pre><code>struct RetrieveKey
{
template <typename T>
typename T::first_type operator()(T keyValuePair) const
{
return keyValuePair.first;
}
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());
// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));
</code></pre>
<p>Of course, we can also retrieve all values from the map by defining another functor <strong>RetrieveValues</strong>.</p>
<p>Is there any other way to achieve this easily? (I'm always wondering why <code>std::map</code> does not include a member function for us to do so.)</p>
|
<p>While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.</p>
<p>I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:</p>
<pre><code>std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
key.push_back(it->first);
value.push_back(it->second);
std::cout << "Key: " << it->first << std::endl();
std::cout << "Value: " << it->second << std::endl();
}
</code></pre>
<p>Or even simpler, if you are using Boost:</p>
<pre><code>map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
v.push_back(me.first);
cout << me.first << "\n";
}
</code></pre>
<p>Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.</p>
|
<blockquote>
<p>(I'm always wondering why std::map does not include a member function for us to do so.)</p>
</blockquote>
<p>Because it can't do it any better than you can do it. If a method's implementation will be no superior to a free function's implementation then in general you should not write a method; you should write a free function.</p>
<p>It's also not immediately clear why it's useful anyway.</p>
| 13,538
|
<p>I have a Prusa i3 that homes properly when you use the menu. After adjusting the bed and homing several times, it keeps the head at a reliable distance. However, when I try to print from an SD card, the printer buries the hot end in the heat bed.</p>
<p>What needs to be adjusted to fix this issue?</p>
<p>G-code from one of the 2 files</p>
<pre><code>M190 S50.000000
M109 S200.000000
;Sliced at: Mon 13-06-2016 15:39:25
;Basic settings: Layer height: 0.2 Walls: 1.2 Fill: 20
;Print time: 3 hours 47 minutes
;Filament used: 11.435m 34.0g
;Filament cost: None
;M190 S50 ;Uncomment to add your own bed temperature line
;M109 S200 ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M82 ;set extruder to absolute mode
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F3000 ;move the platform down 15mm
G92 E0 ;zero the extruded length
G1 F200 E3 ;extrude 3mm of feed stock
G92 E0 ;zero the extruded length again
G1 F3000
;Put printing message on LCD screen
M117 Printing...
;Layer count: 446
;LAYER:0
M107
;LAYER:1
M106 S127
G1 F2400 E-4.50000
G0 F3000 X81.474 Y58.603 Z0.300
;TYPE:WALL-INNER
G1 F2400 E0.00000
G1 F2220 X83.063 Y56.456 E0.06663
G1 X84.277 Y55.080 E0.11240
G1 X84.836 Y54.444 E0.13353
G1 X85.799 Y53.476 E0.16759
G1 X86.755 Y52.587 E0.20015
G1 X87.179 Y52.244 E0.21376
G1 X88.836 Y50.911 E0.26680
G1 X89.285 Y50.610 E0.28029
</code></pre>
|
<p>The correlation between the endstop switch -- or sensor -- and the surface of the bed is not known <em>a priori</em> . In your case, there are two possibilities. I'd say the more likely is that your g-code generator is not setting the Z-height offset from the bed correctly. The other is that your bed is tilted, so proper Z-home at one corner does not match the entire bed.</p>
<p>Try this: first manually move the extruder head to all four corners and adjust the bed screws until the separation is identical at all times. Then let your gcode start up -- and don't worry if the extruder depresses the bed during homing, as that doesn't matter. See where the extruder is once the print starts. Adjust the endstop switch up or down to compensate until the print head <strong>when printing</strong> is just off the surface and the first layer adheres well. </p>
<p>If all that doesn't work, then you may have the wrong printer profile settings in your slicing softwqre. </p>
|
<p>I had the same issue: Z-axis correctly homing manually but not when printing.</p>
<p>What worked for me is disabling the following line in the Marlin configuration file:</p>
<pre><code>#define Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN
</code></pre>
| 523
|
<p>I know it's a long shot, but is there some package or means to insert emoticons into a LaTeX document?</p>
|
<p>I know at least two partial ways:</p>
<p>First:</p>
<pre><code>$\ddot\smile$
</code></pre>
<p>Second:</p>
<pre><code>\usepackage{wasysym}
\smiley
\frownie
</code></pre>
<p>Or you can use images (as mentioned in other replies).</p>
|
<p>One solution is to use bclogo package. It contains two smileys (happy & sad), plus many other small "logos" like flags and others.</p>
| 23,068
|
<p>Is it possible in .NET to ascertain whether my application is closing due to Windows being given a shutdown command (as opposed to any old application closing) in order to either write out some temporary cache files or even block the shutdown long enough to prompt for user input?</p>
<p>Whilst my current scope involves a Winform app and a windows service, I am interested in understanding this in a generic way if possible</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx" rel="noreferrer">SystemEvents.SessionEnding</a> looks like a good starting point for you. That article talks about the event sequence involved when a logout/shutdown is occurring.</p>
|
<p>In general, you will want to handle the <a href="http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx" rel="nofollow noreferrer"><code>WM_QUERYENDSESSION</code></a> Windows message. This will give your application a chance to do cleanup, or to block the shutdown if it's really necessary.</p>
| 30,405
|
<p>I am designing some parts that should modular fit together. I am currently exploring a Lego-like design with octagonal holes and cylindrical pins.</p>
<p>I notice that (depending on the amount of clearance) that the fit is initially tight (to the extent that the pieces are very difficult to remove from each other), but that after a few dozen times connecting and disconnecting the parts the fit becomes very loose. I am currently using PLA. With what material would this occur less quickly/is more resistant to this kind of wear?</p>
<p>The sizes of the pins/holes are slightly bigger than Lego (probably similar to Duplo). Don't think that snap-fit would work in that size. Below of a picture of one of the test pieces (this one later printed in PETG).</p>
<p><a href="https://i.stack.imgur.com/uePVE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uePVE.jpg" alt="enter image description here" /></a></p>
<p>I have an open printer so I prefer materials that don't require me to build an enclosure first. It is a Prusa i3 MK3S: Direct drive; 1.75 mm filament; max temp 300 °C; heat bed max temp 120 °C.</p>
|
<p>A flexible material, such as PETG or ABS, is probably the best. PLA is brittle, especially after absorbing moisture, and probably would crack under continued use.</p>
<p>Nylon is good, but not easy to use. With PETG in an enclosure, I end up running fans to avoid heat creep; so PETG may actually do better without an enclosure.</p>
<p>If you're printing to flex your print, keep in mind the the x and y axes are stronger than the z-axis, which depends on how well the layers stick together. PETG tends to stick to the print surface too well; so I use an Elmer's glue stick for it to pull up the glue layer instead of damaging my print surface.</p>
|
<p>PETG, ABS and NYLON would work great for press-fit or snap-fit connections. If you really can't build a (cardboard) enclosure I would go for PETG as it has good repeatable mechanical properties and does not require an enclosure.</p>
| 1,904
|
<p>I can't shake this error when compiling my Visual Studio.NET 2008 solution. The project that's generating the error is a VB.NET Web Application in a 12 project solution (mixed types and languages).</p>
<p>I've tried all the tricks I can find on google, and the obvious of removing the directoy and folder manually.</p>
<p>I'm running Vista Business 32 with VS.NET 2008 SP1. This just started happening out of the blue today and I've rebooted a bunch and even re-applied SP1 for VS.NET.</p>
<p>Any ideas or has anybody seen this?</p>
<p>vbc : <strong>error BC31019</strong>: <strong>Unable to write to output file</strong> 'G:\Projects\TCA.NET\TcaNet\WebUI\obj\Debug\TcaNet.WebUI.pdb': <strong>Unspecified error</strong> </p>
<p><strong>Update:</strong></p>
<p>After thinking about this and not finding any solutions from answers or via the Internet, I went ahead and moved my entire solution to my C:\ drive vs. my G:\ drive (both are local). Doing this fixed my compile problem for some reason.</p>
|
<p>Restart IIS on local.</p>
<p>If that's not the issue then, install <a href="http://www.emptyloop.com/unlocker/" rel="nofollow noreferrer">Unlocker</a> and try to delete that pdb file when you get the error, Unlocker will tell you which process is holding an open handle to that file.</p>
|
<p>I had this in Visual Studio 2005 except it was Error 1. I restarted my machine and it fixed the problem.</p>
| 19,381
|
<p>I'm programmatically adding ToolStripButton items to a context menu.</p>
<p>That part is easy.</p>
<pre><code>this.tsmiDelete.DropDownItems.Add("The text on the item.");
</code></pre>
<p>However, I also need to wire up the events so that when the user clicks the item something actually happens!</p>
<p>How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.</p>
|
<p>Couldn't you just subscribe to the Click event? Something like this:</p>
<pre><code>ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);
</code></pre>
<p>And OnBtnClicked would be declared like this:</p>
<pre><code>private void OnBtnClicked(object sender, EventArgs e)
{
ToolStripButton btn = sender as ToolStripButton;
// handle the button click
}
</code></pre>
<p>The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.</p>
|
<p>Thanks for your help with that Andy. My only problem now is that the AutoSize is not working on the ToolStripButtons that I'm adding! They're all too narrow. </p>
<p>It's rather odd because it was working earlier.</p>
<hr>
<p>Update: There's definitely something wrong with AutoSize for programmatically created ToolStripButtons. However, I found a solution:</p>
<ol>
<li>Create the ToolStripButton.</li>
<li>Create a label control and set the font properties to match your button.</li>
<li>Set the text of the label to match your button.</li>
<li>Set the label to AutoSize.</li>
<li>Read the width of the label and use that to set the width of the ToolStripButton.</li>
</ol>
<p>It's hacky, but it works.</p>
| 11,035
|
<p>I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:</p>
<pre><code>$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');
// Example 1
$query = $query->fetch_assoc();
// Example 2
$query_r = $query->fetch_assoc();
$query->free();
</code></pre>
<p>Now if I'm right Example 1 should be more efficient as <code>$query</code> is <code>unset</code> when I reassign it which should free any memory associated with it. However there is a method (<code>MySQLi_Result::free()</code>) which frees associated memory - is this the same thing?</p>
<p>If I don't call <code>::free()</code> to free any memory associated with the result but <code>unset</code> it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?</p>
|
<p>The <a href="http://us2.php.net/manual/en/mysqli-result.free.php" rel="noreferrer">manual</a> seems to suggest that you should still be using <code>free()</code> to release the memory. I believe the reasoning is that <code>free()</code> is freeing the memory in <em>MySQL</em>, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call <code>free()</code>.</p>
|
<p>Example 1 <strong>dissociates</strong> the $query variable from the MySQL result. The MySQL result still exists in memory, and will continue to exist and waste memory until garbage collection occurs.</p>
<p>Example 2 <strong>frees</strong> the MySQL result immediately, releasing the used resources.</p>
<p>However, since PHP pages are generally short-lived with small result-sets, the memory saved is trivial. You will not notice a slowdown unless you leave <strong>a ton</strong> of results in memory over a long period of time on pages that run for a long time.</p>
<p>Brian,
PHP <em>can</em> garbage collect the MySQL result, it just doesn't happen immediately.
The result lives in PHP's memory pool, not in the MySQL server's.</p>
<p>(the locality of memory when using unbuffered queries is slightly different, but they're so rarely used in PHP as to not be worth mentioning) </p>
| 4,606
|
<p>I've written a simple control which basically displays a few words with an image next to it.</p>
<p>I want the containing items to strech when the parent form is resized and as you can see from my commented out code, I don't want to use a loop as it flickers.</p>
<p>Any idea on how to get the items to grow and shrink with the form in a nice way?</p>
<pre><code> public class IconListBox : FlowLayoutPanel {
private const int ITEM_PADDING = 2;
private const int MAX_IMAGE_SIZE = 64;
List<FlowLayoutPanel> _listItems;
public IconListBox() {
this.SizeChanged += new EventHandler(IconListBox_SizeChanged);
this.AutoScroll = true;
this.HorizontalScroll.Enabled = false;
this.HorizontalScroll.Visible = false;
this.VerticalScroll.Enabled = true;
this.VerticalScroll.Visible = true;
_listItems = new List<FlowLayoutPanel>();
}
void IconListBox_SizeChanged(object sender, EventArgs e) {
//foreach (FlowLayoutPanel item in _listItems) {
// item.Width = this.Width - 10;
//}
}
public void AddItem(string itemText) {
PictureBox pic = new PictureBox();
pic.Image = MyWave.Properties.Resources.mywave_icon;
pic.Width = pic.Height = MAX_IMAGE_SIZE;
pic.SizeMode = PictureBoxSizeMode.Normal;
pic.Enabled = false;
FlowLayoutPanel p = new FlowLayoutPanel();
p.Width = this.Width;
p.Height = pic.Image.Height + (ITEM_PADDING * 4);
p.BackColor = Color.White;
p.Padding = new Padding(ITEM_PADDING);
p.Margin = new Padding(0);
Label l = new Label();
l.Margin = new Padding(10, 5, 0, 0);
l.Width = this.Width - ITEM_PADDING - MAX_IMAGE_SIZE;
l.Height = p.Height - (ITEM_PADDING * 2);
l.Text = itemText;
l.Enabled = false;
//l.BorderStyle = BorderStyle.FixedSingle;
p.Controls.Add(pic);
p.Controls.Add(l);
p.MouseEnter += new EventHandler(p_MouseEnter);
p.MouseLeave += new EventHandler(p_MouseLeave);
p.MouseClick += new MouseEventHandler(p_MouseClick);
this.Controls.Add(p);
_listItems.Add(p);
p.Anchor = AnchorStyles.Right;
}
void p_MouseClick(object sender, MouseEventArgs e) {
//throw new NotImplementedException();
}
void p_MouseLeave(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.White;
}
void p_MouseEnter(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.LightBlue;
}
public void AddItem(string itemText, Image icon) {
}
}
</code></pre>
|
<p>Avoid triggering a redraw every time you resize a child control by embedding your <code>foreach</code> in <code>SuspendLayout()</code> and <code>ResumeLayout()</code>:</p>
<pre><code>this.SuspendLayout();
foreach (FlowLayoutPanel item in _listItems)
{
item.Width = this.Width - 10;
}
this.ResumeLayout();
</code></pre>
|
<p>Anchor right and bottom on the form and maybe dock them.</p>
| 45,439
|
<p>Our app allows multiple files to be selected in a file selection dialog which is shown via the GetOpenFileName function (this question also applies to folks using CFileDialog, etc...)</p>
<p>There appears to be a limit to the number of characters that can be typed into the filename field (259 seems to be the magic number - not sure why).</p>
<p>We have tried changing the following members of the <a href="http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx" rel="nofollow noreferrer">OPENFILENAME</a> structure:</p>
<p>lpstrFile - point to our own buffer, sized at 4K bytes
nMaxFile - set to the size of lpstrFile (we are compiling ANSI, so this is effectively 4000</p>
<p>But these values appear to not increase the input width of the filename field in the dialog.</p>
<p>I am going to experiment with sending a EM_SETLIMITTEXT message to the control, but wanted to know if anyone else has a solution.</p>
<p>EDIT - solved this myself: <a href="https://stackoverflow.com/questions/361350/increase-number-of-characters-in-filename-field-of-getopenfilename-file-selecti#394443">solution</a> I can't accept out my own answer, but here it is for posterity. If anyone else has a better solution, please post it - or feel free to mod up my solution so future searchers will find it at the top.</p>
|
<p>Turns out that the edit control (At least in my development environment) is a combo box, so <code>EM_SETLIMITTEXT</code> isn't appropriate. </p>
<p>Instead, I tracked down the combo box using <code>GetDlgCtrl</code> on the parent of the file open dialog (I do this in the <code>OnInitDialog</code> handler), cast it to <code>CComboBox*</code>, then call <code>LimitText()</code> to set the limit. </p>
<p>This could also be done by sending a <code>CB_LIMITTEXT</code> message to the control for those of you who are not working with <code>CFileDialog</code>. The appropriate value here is most likely the <code>OPENFIILENAME.nMaxFile</code> value that is passed in.</p>
|
<p>I believe this is a hard limit that cannot be bypassed. The only time it should matter is when you want to select more than one file, since the limit is enough for the maximum file name length.</p>
<p>I have added an "All Files" button to these dialogs for opening all of the files in a folder; that's the only workaround I have found.</p>
| 47,157
|
<p>I need to be able to create basic MS Project items (tasks, projects, resources, etc.) programmatically from my app to my Project Server 2003 install, and haven't found any good examples. Can anyone point me to some good references or have some sample code of connecting to the server and creating these items?</p>
|
<p>Developing against Project Server 2003 isn't the friendliest experience around, but I have worked a little bit with the PDS (Project Data Services) which is SOAP based</p>
<p><A HRef="http://msdn.microsoft.com/en-us/library/aa204408(office.11).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa204408(office.11).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa204408(office.11).aspx</a></A></p>
<p>It contains .NET samples there</p>
|
<p>As far as I know, the only programatic access to PS 2003 is through PWS. </p>
<p>I don't know if it would work, but you could try writing a managed extension for Microsoft Project 2003 (The client application) .There <A href="http://msdn.microsoft.com/en-us/library/aa209377(office.11).aspx" rel="nofollow noreferrer">is a managed API for MS Project 2003</a>, and you might be able to leverage that to communicate with the server, get a project and update it all in code.</p>
<p>Good luck!</p>
| 3,925
|
<p>I'm writing an MFC App to automatically configure Postgresql with ODBC for use by another app. The idea being that the user runs the app and it automatically creates the database and the tables within it. My problem is that when I set up the File DSN it seems to require the name of the database it will access. This appears in the DSN file as ..</p>
<pre><code>DATABASE=mydb
</code></pre>
<p>However I haven't created mydb yet so can't connect to Postgresql ! I have tried editing the DSN file so this line reads ..</p>
<pre><code>DATABASE=
</code></pre>
<p>and removing it totally but then I get an error and can't connect.</p>
<p>Is it possible for a DSN file to allow access to any database ? If so how do I do this ?</p>
<p>Thanks</p>
<p>Ian</p>
|
<p>One simple option would be to create a view to render an XML-version of an Excel File. You could either use the new Office 2007 version, or the older 2003 version. We chose the 2003 version so that more people could use it, but that's up to you, of course.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:Workbook" rel="noreferrer">XML 2003 ref on MSDN</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa338205.aspx" rel="noreferrer">XML 2007 ref on MSDN</a></p>
|
<p>Here is a blog post from Stephen Walther entitled <a href="http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx" rel="noreferrer">ASP.NET MVC Tip #2 - Create a custom Action Result that returns Microsoft Excel Documents</a></p>
| 38,762
|
<p>I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to:</p>
<pre><code>public string Foo()
{
set {
Assert.IsNotNull(value);
Assert.IsTrue(value.Contains("bar"));
_foo = value;
}
}
</code></pre>
<p>I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.</p>
|
<blockquote>
<h2>C# 4.0 Code Contracts</h2>
</blockquote>
<p>Microsoft has released a library for design by contract in version 4.0 of the .net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code.</p>
<p>Here are some Microsoft resources:</p>
<ul>
<li><a href="http://research.microsoft.com/en-us/projects/contracts/" rel="noreferrer">The main Microsoft Research site</a></li>
<li><a href="http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf" rel="noreferrer">The user manual</a></li>
<li><a href="http://channel9.msdn.com/pdc2008/TL51/" rel="noreferrer">The 2008 PDC presentation</a></li>
<li><a href="http://microsoftpdc.com/Sessions/VTL01" rel="noreferrer">The 2009 PDC presentation</a></li>
</ul>
<p>Here are some other resources:</p>
<ul>
<li><a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/08/code-contracts-and-net-4-0-spec-comes-alive.aspx" rel="noreferrer">Code Contracts for .NET 4.0 - Spec# Comes Alive</a></li>
<li><a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/14/net-code-contracts-and-tdd-are-complementary.aspx" rel="noreferrer">.NET Code Contracts and TDD Are Complementary</a></li>
<li><a href="http://devlicio.us/blogs/derik_whittaker/archive/2009/07/01/code-contracts-primer-part-5-utilizing-object-invariants.aspx" rel="noreferrer">Code Contracts Primer – Part 5: Utilizing Object Invariants</a></li>
<li><a href="http://devlicio.us/blogs/derik_whittaker/archive/2010/05/14/code-contracts-primer-part-6-interface-contracts.aspx" rel="noreferrer">Code Contracts Primer – Part 6 Interface Contracts</a></li>
</ul>
|
<p>You may want to check out <a href="http://www.codeplex.com/umbrella" rel="nofollow noreferrer">nVentive Umbrella</a>:</p>
<pre><code>using System;
using nVentive.Umbrella.Validation;
using nVentive.Umbrella.Extensions;
namespace Namespace
{
public static class StringValidationExtensionPoint
{
public static string Contains(this ValidationExtensionPoint<string> vep, string value)
{
if (vep.ExtendedValue.IndexOf(value, StringComparison.InvariantCultureIgnoreCase) == -1)
throw new ArgumentException(String.Format("Must contain '{0}'.", value));
return vep.ExtendedValue;
}
}
class Class
{
private string _foo;
public string Foo
{
set
{
_foo = value.Validation()
.NotNull("Foo")
.Validation()
.Contains("bar");
}
}
}
}
</code></pre>
<p>I wish the Validation extensions were builders so you could do <code>_foo = value.Validation().NotNull("Foo").Contains("bar").Value;</code> but it is what it is (fortunately its open source so making it a builder is a trivial change).</p>
<p>And as an alternative solution you could <a href="http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx" rel="nofollow noreferrer">consider domain validation</a>.</p>
<p>Finally the <a href="http://msdn.microsoft.com/en-us/library/dd129617.aspx" rel="nofollow noreferrer">new M languages</a>, <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx" rel="nofollow noreferrer">as part of Oslo</a>, support restrictions on their extents and fields which translate both to T-SQL validation and a CLR class with functioning validation tests (though Oslo is a long time off from release).</p>
| 32,612
|
<p>I have a very dense point cloud (billions of points) of the exterior of a building obtained by laser scanning it with a Leica head.
I successfully subsampled it down to around 500,000 and I'm trying to print the building by first creating a mesh.
I tried using CloudCompare, Meshlab and PDAL, using Poisson surface reconstruction.
However, the resulting mesh is full of holes, mainly in the roofs which have the lowest point density, and I cannot print it.
Is there any algorithm which could use the fact that the point cloud is precisely the exterior part of a geometric thing?</p>
|
<p>The foundation of any 3D printer is the controller and the firmware. Many devices are based on Arduino type controllers, with stepper motor driver boards either integrated or added as a plug-in component.</p>
<p>Some manufacturers will use in-house or outside resources and develop their own boards and firmware.</p>
<p>You can search for 3D printer controllers and get a pretty comprehensive list of the various devices available for purchase. Smoothieboard is one device, Raspberry Pi and Arduino as noted above, and others.</p>
<p>There can be found varying "flavors" of firmware to load onto these controllers as well.</p>
<p>The field is exhaustive.</p>
<p>To address your focus regarding the printing aspect, that's one stepper motor per print head/nozzle (usually) and involves calibrating the amount of filament dispensed from the nozzle per unit steps, or more easily understood, amount of steps per unit of filament movement. My stepper motor for the extruder has a planetary gear and moves 100 mm of filament for about 5000 steps.</p>
<p>All of the parameters you've noted are integrated with the firmware. Motor calibration requires movement per step or steps per millimeter to be entered, unless you purchase a turnkey system with the values loaded.</p>
<p>You can adjust many of the parameters from the slicing software, but it's more practical to determine the calibration settings, enter that information into your slicer and proceed with model management.</p>
<p>Look into instructables for others' build projects to see what they've accomplished and the steps involved in such a build. This can give you a starting point for your efforts.</p>
|
<p>this is an extension to fred_dot_u answer.
As I am in the process of building my own printer, I decided to use RAMPS Arduino shield for electronics and Marlin firmware + Arduino mega2560 as a logic controller. </p>
<p>As above are battle-tested, I don't need to discover wheel again, but rather focus on the mechanics.
The RAMPS mainboard will provide you with the ability to connect 5 steppers and 3 PWM regulated devices (that can be heat-bed, nozzle and fan or combination) and there is still possibility to connect more as a bunch of IO pins are ready to alocate. </p>
<p>MarlinFirmware is avalible on github, so you can download it and then provide all mechanical parameters that are needed to properly drive your printer -so that is:</p>
<ol>
<li>Mainboard type</li>
<li>type coreXY, XZ ....</li>
<li>bed size (x,y)</li>
<li>gantry size (z)</li>
<li>steps / mm for steppers</li>
<li>thermal protection parameters </li>
<li>LCD display (if in use)</li>
</ol>
<p>The main benefit of using Marlin for me is that printer configuration is extremely customizable.</p>
| 885
|
<p>I need to convert an x12 850 v4010 to a x12 940 v4010. Most of the tools convert from x12 to xml then I would need to map the xml to a 940. I am hoping there is a tool that could convert from one edi document to another.</p>
<p>EDIT FOR INFORMATION:</p>
<blockquote>
<p><a href="http://www.rawlinsecconsulting.com/x12tutorial/index.html" rel="nofollow noreferrer">Quick Background</a></p>
<p>Electronic Data Interchange (EDI) is
classically defined as the
application-to-application exchange of
structured business data between
organizations. X12 is an ANSI standard
that supplies that structure. There
are many good books concerned with the
business benefits of EDI,
implementation considerations, and
operational aspects</p>
</blockquote>
|
<p>Going to give Altova MapForce and Stylus Studio® a try. </p>
<p><a href="http://www.altova.com/downloadtrialmapforce3.html" rel="nofollow noreferrer">http://www.altova.com/downloadtrialmapforce3.html</a></p>
<p><a href="http://www.stylusstudio.com/xml_product_index.html" rel="nofollow noreferrer">http://www.stylusstudio.com/xml_product_index.html</a></p>
|
<p>I would like to try out ALTOVA's mapforce tool to convert EDI 850 X12 to Oracle Apps. Is this a good choice.
I hear that the most popular is <a href="http://www.sterlingcommerce.com/" rel="nofollow noreferrer">http://www.sterlingcommerce.com/</a>, but it is very costly..</p>
<p>Please advice
Shashi</p>
| 9,221
|
<p>This is a for a Silverlight project that isn't anchored to an .aspx file, so right clicking, etc. is a bit out of the question. Any ideas?</p>
<p>Edit: </p>
<p>Add an .html file, then click it. Really dumb. Last time I ask a question at three in the morning.</p>
|
<p>Why is right-clicking out of the question? With any HTML document at least (even in <em>Miscellaneous Files</em>) you can right-click on it, select <em>Browse With...</em>, select the browser, and click on <strong><em>Set as Default</em></strong>. If the browser doesn't appear in the list, click on <em>Add...</em>.</p>
|
<p>Default Browser Changer extension:</p>
<p><a href="http://visualstudiogallery.msdn.microsoft.com/233945ae-0b7b-47e7-9b02-c5a11798afb5" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/233945ae-0b7b-47e7-9b02-c5a11798afb5</a></p>
| 21,990
|
<p>Is there a way for me to loop over a Javascript Object's built-in properties?</p>
<p>for...in gets me close to where I want to go, but "A for...in loop does not iterate over built-in properties."</p>
|
<p>I realize this question is three years old, but now, with ES5, it is possible:</p>
<p><code>>>> Object.getOwnPropertyNames(Object)</code></p>
<p><code>["prototype", "getPrototypeOf", "getOwnPropertyDescriptor", "keys", "defineProperty", "defineProperties", "create", "getOwnPropertyNames", "isExtensible", "preventExtensions", "freeze", "isFrozen", "seal", "isSealed", "length", "arity", "name", "arguments", "caller"]</code></p>
|
<p>This will work with JSON. It hasn't been tested much:</p>
<pre><code><style>
.tree {
margin-left:5px;
}
</style>
<div id='out'></div>
<script type="text/javascript">
data = {"feep":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"},"Bleh":"1234"}
$('out').innerHTML = renderJSON(data)
function renderJSON(obj) {
var keys = []
var retValue = ""
for (var key in obj) {
//$('out').innerHTML = $('out').innerHTML +"<br />" + key + ", " + obj[key]
if(typeof obj[key] == 'object') {
retValue += "<div class='tree'>" + key
retValue += renderJSON(obj[key])
retValue += "</div>"
}
else {
retValue += "<div class='tree'>" + key + " = " + obj[key] + "</div>"
}
keys.push(key)
}
return retValue
}
</script>
</code></pre>
| 32,871
|
<p>I am trying to configure Reporting Services 2005SP2 on a machine with SQL 2008 on another hosting the ReportServer DB.</p>
<p>When I create the ReportServerDB the DB is created as version C.0.9.45:</p>
<p>When, afterwards, I try to initialise Reporting Services, I get an error about an incorrect version number. Reporting Services created a ReportServer DB version C.0.9.45 but now expects a version C.0.8.54.</p>
<p>Changing compatibility settings of the DB doesn’t have an effect. And changing the version number sproc in the DB to return what Reporting Services wants to hear only delays the crash until initialisation has started.</p>
<p>Any ideas?</p>
|
<p>I got a reply from microsoft support saying that it is impossible on the same box.</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4153333&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4153333&SiteID=1</a></p>
|
<p>You must have created the reportServerDB using the SQL 2008 configuration tool. If you want to use the 2005 version of the server you need to create the configuration database using the configuration tool that came with SQL 2005. The 2005 SP2 tool will create a database with version C.0.8.54</p>
| 18,964
|
<p>Anyone use a language called Interactive Data Language, IDL? It is popular with scientists. I think it is a poor language because it is proprietary (every terminal running it has to have an expensive license purchased) and it has minimal support (try searching for IDL, the language, right now on stack) . I am trying to convince my colleagues to stop using it and learn C/C++/Python/Fortran/Java/Ruby. Does anybody know about or even care about IDL enough to have opinions on it? What do you think of it? Should I tell my colleagues to stop wasting their time on it now? How can I convince them?</p>
<p>Edit: People are getting the impression that I don't know or use IDL. Also, I said IDL has minimal support which is true in one sense, so I must clarify that the scientific libraries are indeed large. I use IDL all the time, but this is exactly the problem: I am only using IDL because colleagues use it. There is a file format IDL uses, the .sav, which can only be opened in IDL. So I must use IDL to work with this data and transfer the data back to colleagues, but I know I would be more efficient in another language. This is like someone sending you a microsoft word file in an email attachment and if you don't understand how wrong that is then you probably write too many words not enough code and you bought microsoft word.</p>
<p>Edit: As an alternative to IDL Python is popular. Here is a list of <a href="http://www.astrobetter.com/idl/idl-vs-python/" rel="noreferrer">The Pros of IDL</a> (and the cons) from <a href="http://www.astrobetter.com/" rel="noreferrer">AstroBetter</a>:</p>
<p>Pros of IDL</p>
<ul>
<li>Mature many numerical and astronomical libraries available</li>
<li>Wide astronomical user base</li>
<li>Numerical aspect well integrated with language itself</li>
<li>Many local users with deep experience</li>
<li>Faster for small arrays</li>
<li>Easier installation</li>
<li>Good, unified documentation</li>
<li>Standard GUI run/debug tool (IDLDE)</li>
<li>Single widget system (no angst about which to choose or learn)</li>
<li>SAVE/RESTORE capability</li>
<li>Use of keyword arguments as flags more convenient</li>
</ul>
<p>Cons of IDL</p>
<ul>
<li>Narrow applicability, not well suited to general programming</li>
<li>Slower for large arrays</li>
<li>Array functionality less powerful</li>
<li>Table support poor</li>
<li>Limited ability to extend using C or Fortran, such extensions hard to distribute and support</li>
<li>Expensive, sometimes problem collaborating with others that don’t have or can’t afford licenses.</li>
<li>Closed source (only RSI can fix bugs)</li>
<li>Very awkward to integrate with IRAF tasks</li>
<li>Memory management more awkward</li>
<li>Single widget system (useless if working within another framework)</li>
<li>Plotting:
<ul>
<li>Awkward support for symbols and math text</li>
<li>Many font systems, portability issues (v5.1 alleviates somewhat)</li>
<li>not as flexible or as extensible</li>
<li>plot windows not intrinsically interactive (e.g., pan & zoom)</li>
</ul></li>
</ul>
<p>Pros of Python</p>
<ul>
<li>Very general and powerful programming language, yet easy to learn. Strong, but optional, Object Oriented programming support</li>
<li>Very large user and developer community, very extensive and broad library base</li>
<li>Very extensible with C, C++, or Fortran, portable distribution mechanisms available</li>
<li>Free; non-restrictive license; Open Source</li>
<li>Becoming the standard scripting language for astronomy</li>
<li>Easy to use with IRAF tasks</li>
<li>Basis of STScI application efforts</li>
<li>More general array capabilities</li>
<li>Faster for large arrays, better support for memory mapping</li>
<li>Many books and on-line documentation resources available (for the language and its libraries)</li>
<li>Better support for table structures</li>
<li>Plotting
<ul>
<li>framework (matplotlib) more extensible and general</li>
<li>Better font support and portability (only one way to do it too)</li>
<li>Usable within many windowing frameworks (GTK, Tk, WX, Qt…)</li>
<li>Standard plotting functionality independent of framework used</li>
<li>plots are embeddable within other GUIs</li>
<li>more powerful image handling (multiple simultaneous LUTS, optional resampling/rescaling, alpha blending, etc)</li>
</ul></li>
<li>Support for many widget systems</li>
<li>Strong local influence over capabilities being developed for Python</li>
</ul>
<p>Cons of Python</p>
<ul>
<li>More items to install separately</li>
<li>Not as well accepted in astronomical community (but support clearly growing)</li>
<li>Scientific libraries not as mature:
<ul>
<li>Documentation not as complete, not as unified</li>
<li>Not as deep in astronomical libraries and utilities</li>
<li>Not all IDL numerical library functions have corresponding functionality in Python</li>
</ul></li>
<li>Some numeric constructs not quite as consistent with language (or slightly less convenient than IDL)</li>
<li>Array indexing convention “backwards”</li>
<li>Small array performance slower</li>
<li>No standard GUI run/debug tool</li>
<li>Support for many widget systems (angst regarding which to choose)</li>
<li>Current lack of function equivalent to SAVE/RESTORE in IDL</li>
<li>matplotlib does not yet have equivalents for all IDL 2-D plotting capability (e.g., surface plots)</li>
<li>Use of keyword arguments used as flags less convenient</li>
<li>Plotting:
<ul>
<li>comparatively immature, still much development going on</li>
<li>missing some plot type (e.g., surface)</li>
<li>3-d capability requires VTK (though matplotlib has some basic 3-d capability)</li>
</ul></li>
</ul>
|
<p>So many IDL fanboys here! I'm also an astronomer and I've extensively used IDL and Python. All I can say is that IDL survives to this day because of the laziness of fellow astronomers, who can't or don't want to learn new better programming language. Most of my colleagues haven't used anything else besides Fortran or IDL. For them there's only IDL in the entire world. By the way, many of the younger astronomy students are also all about IDL and don't even want to check Fortran, or god forbids Python or C/C++. Those are languages for programmers and mathematicians, and not for astronomers. </p>
<p>About the licensing fees. How many IDL versions have been and how many of them has your university bought? I guess many... </p>
<p>Yeah, go ahead buy that new IDL 8.x version. I've heard that its the new plotting package allows you to modify parts of the plot after it's been generated. WOOOW! That's so cool!</p>
<p>p.s. There's nothing in IDL that can't be done in Python in a much better and cleaner way. Most of the scientific tools in it are extensive and very stable. I haven't had any problems with plotting all sorts of plots in matplotlib. Its GUI tools are excellent and intuitive, and not unlike the crappy IDL "widgets".</p>
<p>This is very much alike the situation in my old university, where the old professors were kinda stumped by time, because they refused to learn anything new in programming. They became not competitive and stopped doing any significant work.</p>
|
<p>Well, I did search for IDL on stack and that's how I got here! :-)</p>
<p>I've been programming for almost 30 years and am just learning IDL. Thus far, I admit that I'm not overly fond of it. However, it does have some things that many other languages don't have (e.g. mathematical array operations can be done with a single command, not with loops or some other device).</p>
<p>As others said, IDL's popularity is somewhat cultural and a matter of being entrenched. I first heard of IDL almost 20 years ago. At that point in time, it seemed to me that Stallman had some nice ideas and a few useful tools out, and Linus had not yet put out his famous comp.os.minix message. Thus IDL had a good head start on anything open source that would be competitive; to my knowledge nothing in the open source community is competitive yet (and I know about GDL, but if I'm not mistaken, it's way behind IDL - I'd be happy to be corrected on that). Eventually, it may be supplanted, but I do not expect that to happen soon.</p>
| 32,616
|
<p>I've looked at every question so far and none seem to actually answer this question.</p>
<p>I created a UITabBarController and added several view controllers to it. Most of the views are viewed in portrait, but one should be viewed in landscape. I don't want to use the accelerometer or detect when the user rotates the device, I just want to display the view in landscape mode when they choose that view from the tab at the bottom.</p>
<p>I want the regular animations to occur, such as the tab dropping out, the view rotating, etc., when they choose that item, and the opposite to happen when they choose a different view.</p>
<p>Is there not a built-in property or method to tell the system what orientation to display the view as?</p>
<p>Overriding the shouldautorotate... method does absolutely nothing so far as I can tell.</p>
<p>The type of answer I would NOT appreciate is "RTFM" because I already have, and anybody who's developed for the iPhone so far knows that there is very little useful M to F-ing R.</p>
|
<p>An <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/3219-force-landscape-mode-one-view-2.html" rel="nofollow noreferrer">post</a> on a forum that might help. Short answer is you have to manually rotate your view or controller once the view has been drawn, in the viewWillAppear: method</p>
<pre><code>CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation(degreesToRadian(90));
landscapeTransform = CGAffineTransformTranslate (landscapeTransform, +80.0, +100.0);
[[appDelegate navController].view setTransform:landscapeTransform];
</code></pre>
|
<p>Override the Orientation method in your controller class and force it to Landscape like this :</p>
<pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Overriden to allow any orientation.
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
</code></pre>
<p>Simple and efficient ! </p>
| 46,537
|
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
|
<p>The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.</p>
<p>The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.</p>
<p>If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.</p>
|
<p>If the database have a DBA that isn't you, you may not be allowed to use a database-backed session (it being a front-end matter only). Until django supports easily merging data from several databases, so that you can have frontend-specific stuff like sessions and user-messages (the messages in django.contrib.auth are also stored in the db) in a separate db, you need to keep this in mind.</p>
| 7,337
|
<p>I am coding a client-server application using Eclipse's RCP.
We are having trouble testing the interaction between the two sides
as they both contain a lot of GUI and provide no command-line or other
remote API.</p>
<p>Got any ideas?</p>
|
<p>I have about 1.5 years worth of experience with the RCP framework, I really liked it. We simply JUnit for testing...</p>
<p>It's sort of cliche to say, but if it's not easy to test, maybe the design needs some refactoring?</p>
<p>Java and the RCP framework provide great facilities for keeping GUI code and logic code separate. We used the MVC pattern with the observer, observable constructs that are available in Java...</p>
<p>If you don't know about observer / observable construct that are in Java, I would HIGHLY recommend you take a look at this: <a href="http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html</a>, you will use it all the time and your apps will be easier to test.</p>
|
<p>Separate your client-server communication into a pure logic module (or package). Test this separately - either have a test server, or use mock objects.</p>
<p>Then, have your UI actions invoke the communications layer. Also, have a look at the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command design pattern</a>, using it may help you.</p>
| 5,157
|
<p>Does anybody know how I can see the actual machine code that <a href="http://code.google.com/p/v8/" rel="noreferrer">v8</a> generates from Javascript? I've gotten as far as <code>Script::Compile()</code> in <code>src/api.cc</code> but I can't figure out where to go from there.</p>
|
<p>I don't know how to invoke the disassembler from C++ code, but there is a quick-and-dirty way to get a disassembly from the shell.</p>
<p>First, compile v8 with disassembler support:</p>
<pre><code>scons [your v8 build options here] disassembler=on sample=shell
</code></pre>
<p>Now you can invoke the shell with the "--print_code" option:</p>
<pre><code>./shell --print_code hello.js
</code></pre>
<p>Which should give you something like this:</p>
<pre><code>--- Raw source ---
print("hello world");
--- Code ---
kind = FUNCTION
Instructions (size = 134)
0x2ad0a77ceea0 0 55 push rbp
0x2ad0a77ceea1 1 488bec REX.W movq rbp,rsp
0x2ad0a77ceea4 4 56 push rsi
0x2ad0a77ceea5 5 57 push rdi
0x2ad0a77ceea6 6 49ba59c13da9d02a0000 REX.W movq r10,0x2ad0a93dc159 ;; object: 0xa93dc159 <undefined>
0x2ad0a77ceeb0 16 4952 REX.W push r10
0x2ad0a77ceeb2 18 49ba688b700000000000 REX.W movq r10,0x708b68
0x2ad0a77ceebc 28 493b22 REX.W cmpq rsp,[r10]
0x2ad0a77ceebf 31 0f824e000000 jc 115 (0x2ad0a77cef13)
0x2ad0a77ceec5 37 488b462f REX.W movq rax,[rsi+0x2f]
0x2ad0a77ceec9 41 4883ec18 REX.W subq rsp,0xlx
0x2ad0a77ceecd 45 49ba094b3ea9d02a0000 REX.W movq r10,0x2ad0a93e4b09 ;; object: 0xa93e4b09 <String[5]: print>
0x2ad0a77ceed7 55 4c8955e0 REX.W movq [rbp-0x20],r10
0x2ad0a77ceedb 59 488945d8 REX.W movq [rbp-0x28],rax
0x2ad0a77ceedf 63 49ba014d3ea9d02a0000 REX.W movq r10,0x2ad0a93e4d01 ;; object: 0xa93e4d01 <String[11]: hello world>
0x2ad0a77ceee9 73 4c8955d0 REX.W movq [rbp-0x30],r10
0x2ad0a77ceeed 77 49baa06c7ba7d02a0000 REX.W movq r10,0x2ad0a77b6ca0 ;; debug: statement 0
;; code: contextual, CALL_IC, UNINITIALIZED, argc = 1
0x2ad0a77ceef7 87 49ffd2 REX.W call r10
0x2ad0a77ceefa 90 488b75f8 REX.W movq rsi,[rbp-0x8]
0x2ad0a77ceefe 94 4883c408 REX.W addq rsp,0xlx
0x2ad0a77cef02 98 488945e8 REX.W movq [rbp-0x18],rax
0x2ad0a77cef06 102 488be5 REX.W movq rsp,rbp ;; js return
0x2ad0a77cef09 105 5d pop rbp
0x2ad0a77cef0a 106 c20800 ret 0x8
0x2ad0a77cef0d 109 cc int3
0x2ad0a77cef0e 110 cc int3
0x2ad0a77cef0f 111 cc int3
0x2ad0a77cef10 112 cc int3
0x2ad0a77cef11 113 cc int3
0x2ad0a77cef12 114 cc int3
0x2ad0a77cef13 115 49ba60657ba7d02a0000 REX.W movq r10,0x2ad0a77b6560 ;; code: STUB, StackCheck, minor: 0
0x2ad0a77cef1d 125 49ffd2 REX.W call r10
0x2ad0a77cef20 128 488b7df0 REX.W movq rdi,[rbp-0x10]
0x2ad0a77cef24 132 eb9f jmp 37 (0x2ad0a77ceec5)
RelocInfo (size = 10)
0x2ad0a77ceea8 embedded object (0xa93dc159 <undefined>)
0x2ad0a77ceecf embedded object (0xa93e4b09 <String[5]: print>)
0x2ad0a77ceee1 embedded object (0xa93e4d01 <String[11]: hello world>)
0x2ad0a77ceeed statement position (0)
0x2ad0a77ceeef code target (context) (CALL_IC) (0x2ad0a77b6ca0)
0x2ad0a77cef06 js return
0x2ad0a77cef15 code target (STUB) (0x2ad0a77b6560)
hello world
</code></pre>
<p>Your output will vary, of course. The above is from the v8 trunk compiled for Linux x64.</p>
|
<p>Take a look at <code>v8_root/build/features.gypi</code>, and you will find disassembler related and many other compile time feature switches for V8.</p>
| 35,006
|
<p>I have roughly the following code. Could this be made nicer or more efficient? Perhaps using <code>std::remove_if</code>? Can you remove items from the map while traversing it? Can we avoid using the temporary map?</p>
<pre><code>typedef std::map<Action, What> Actions;
static Actions _actions;
bool expired(const Actions::value_type &action)
{
return <something>;
}
void bar(const Actions::value_type &action)
{
// do some stuff
}
void foo()
{
// loop the actions finding expired items
Actions actions;
BOOST_FOREACH(Actions::value_type &action, _actions)
{
if (expired(action))
bar(action);
else
actions[action.first]=action.second;
}
}
actions.swap(_actions);
}
</code></pre>
|
<p>You could use erase(), but I don't know how BOOST_FOREACH will handle the invalidated iterator. The <a href="http://en.cppreference.com/w/cpp/container/map/erase" rel="noreferrer">documentation for map::erase</a> states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop:</p>
<pre><code>Actions::iterator it = _actions.begin();
while (it != _actions.end())
{
if (expired(*it))
{
bar(*it);
Actions::iterator toerase = it;
++it;
_actions.erase(toerase);
}
else
++it;
}
</code></pre>
|
<p>If the idea is to remove expired items, why not use <a href="http://www.cplusplus.com/reference/stl/map/erase.html" rel="nofollow noreferrer">map::erase</a>? This way you only have to remove elements you don't need anymore, not rebuild an entire copy with all the elements that you want to keep.</p>
<p>The way you would do this is to save off the iterators pointing to the elements you want to erase, then erase them all after the iteration is over.</p>
<p>Or, you can save off the element that you visited, move to the next element, and then erase the temporary. The loop bounds get messed up in your case though, so you have to fine tune the iteration yourself.</p>
<p>Depending on how expired() is implemented, there may be other better ways. For example if you are keeping track of a timestamp as the key to the map (as expired() implies?), you can do upper_bound on the current timestamp, and all elements in the range [ begin(), upper_bound() ) need to be processed and erased.</p>
| 21,780
|
<p>I'm using the sortable function in jquery to sequence a faq list. Needless to say, i'm new to this concept. Anybody have any good examples of the backend for this. I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw.</p>
<p>Thanks in advance</p>
|
<p>Define the faq:</p>
<pre><code><div id="faq">
<div id="q1">...</div>
<div id="q2">...</div>
(...)
<div id="q100">..</div>
</div>
</code></pre>
<p>Make faq sortable:</p>
<pre><code><script type="text/javascript">
$("#faq").sortable();
</script>
</code></pre>
<p>Form submitted:</p>
<pre><code><form action="..." id="faq_form">
<input type="hidden" name="faqs" id="faqs" />
...
</form>
</code></pre>
<p>Add sorted sequence to form</p>
<pre><code><script type="text/javascript>
$("#faq_form").submit(function() {
$("#faqs").val($("#faq").sortable('toArray'))
})
</script>
</code></pre>
<p>When form is submitted, field "faqs" will contain comma separated id's from #faq like this:
q1,q3,q10,q11,q2,q100...</p>
<p>Just parse it and save to DB</p>
|
<p>Here is simple example of Jquery UI Sortable,how it can be used with div's.</p>
<p>First include libraries in your html:</p>
<pre><code> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>`<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>``
</code></pre>
<p>Html for making sortable:</p>
<pre><code><div id="target">
<div style="cursor: move;" class="entity">
<div class="digit"><span>1</span><tab />&nbsp; First Item </div>
</div>
<div style="cursor: move;" class="entity">
<div class="digit"><span>2</span>&nbsp; Second Item</div>
</div>
<div style="cursor: move;" class="entity">
<div class="digit"><span>3</span>&nbsp; Third Item</div>
</div>
<div style="cursor: move;" class="entity">
<div class="digit"><span>4</span>&nbsp; Fourth Item</div>
</div>
<div style="cursor: move;" class="entity">
<div class="digit"><span>5</span>&nbsp; Fifth Item</div>
</div>
</div>
</code></pre>
<p>Here is the sortable function:</p>
<pre><code>$(document).ready(function() {
$('#target').sortable({
items:'div.entity', //the div which we want to make sortable
scroll:true, //If set to true, the page
//scrolls when coming to an edge.
update:function(event,ui){ renumber(); } //This event is triggered when the user
//stopped sorting and the DOM position has changed.
});
});
</code></pre>
<p>renuber() is called from the Sortable update event handler callback:</p>
<pre><code>function renumber()
{
$('.digit span').each(function(index,element) {
$(element).html(index+1);
});
}
</code></pre>
| 22,651
|
<p>In Vim editor I opted <code>]I</code> on a function (in C++ code).
This presented a list, which says <em>'Press ENTER or type command to continue'</em>.</p>
<p>Now to jump to an occurrence say 6, I type <code>6</code> - but this is not working.</p>
<p>What commands can I type in such a case, and how do I jump to Nth occurrence from this list?</p>
<p><strong>Update:</strong></p>
<p>Actually I tried <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> (eg :6) - but the moment I type <code>:</code> Vim enters Insert mode, and the colon gets inserted in the code instead.</p>
<p><strong>Update</strong></p>
<p>Assuming <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing <code>:</code> does not switch Vim to insert mode.</p>
|
<p>It should present you a list like:</p>
<pre><code>1: 345 my_func (int var)
2: 4523 my_func (int var)
3: 10032 my_func (3);
</code></pre>
<p>The second column is line numbers. Type :345 to jump to line 345.</p>
|
<p>Try using <code>123G</code> to go to line 123 (see <code>:h G</code>).</p>
| 16,683
|
<p>I have a small problem with interfaces. Here it is in Pseudo code :</p>
<pre><code>type
Interface1 = interface
end;
Interface2 = interface
end;
TParentClass = class(TInterfacedObject, Interface1)
private
fChild : Interface2;
public
procedure AddChild(aChild : Interface2);
end;
TChildClass = class(TInterfacedObject, Interface2)
private
fParent : Interface2;
public
constructor Create(aPArent : Interface1);
end;
</code></pre>
<p>Can anyone see the flaw? I need the child to have a reference to it's parent, but the reference counting doesn't work in this situation. If I create a ParentClass instance, and add a child, then the parent class is never released. I can see why. How do I get round it?</p>
|
<p>A reference-counted reference has two semantics: it acts as a share of ownership as well as a means of navigating the object graph.</p>
<p>Typically, you don't need <strong>both</strong> of these semantics on all links in a cycle in the graph of references. Perhaps only parents own children, and not the other way around? If that is the case, you can make the child references to the parent <em>weak links</em>, by storing them as pointers, like this:</p>
<pre><code>TChildClass = class(TInterfacedObject, Interface2)
private
fParent : Pointer;
function GetParent: Interface1;
public
constructor Create(aPArent : Interface1);
property Parent: Interface1 read GetParent;
end;
function TChildClass.GetParent: Interface1;
begin
Result := Interface1(fParent);
end;
constructor TChildClass.Create(AParent: Interface1);
begin
fParent := Pointer(AParent);
end;
</code></pre>
<p>This is safe if the root of the tree of instances is guaranteed to be kept alive somewhere, i.e. you are not relying on only keeping a reference to a branch of the tree and still being able to navigate the whole of it.</p>
|
<p>With the use of a function pointer in the first example then the cyclic reference problem doesn't exist. .NET uses delegates, and VB6 uses events. All of which have the benefit of not incrementing the reference count of the object being pointed too.</p>
| 20,704
|
<p>To recap for those .NET gurus who might not know the Java API:</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow noreferrer">ConcurrentHashMap</a> in Java has atomic methods (i.e. require no external locking) for common Map modification operations such as:</p>
<pre><code>putIfAbsent(K key, V value)
remove(Object key, Object value)
replace(K key, V value)
</code></pre>
<p>It also allows iteration over the keyset without locking (it takes a copy at the start of iteration) and <code>get()</code> operations can generally be interleaved with calls to <code>put()</code> without blocking (it uses fine grained lock striping <a href="http://en.wiktionary.org/wiki/IIRC" rel="nofollow noreferrer">IIRC</a>).</p>
<p>Anyway, my question is: <strong>does .NET have an equivalent Dictionary implementation?</strong></p>
<p>I guess more generally, I'd be keen to know if .NET has a more general set of thread safe collection libraries. Or concurrency utilities in general - equivalent to <a href="http://en.wikipedia.org/wiki/Doug_Lea" rel="nofollow noreferrer">Doug Lea</a>'s <code>java.util.concurrent</code> libraries.</p>
|
<p>The incoming .Net 4.0 has a <a href="http://msdn.microsoft.com/en-us/library/dd287191(VS.100).aspx" rel="noreferrer">ConcurrentDictionary</a> class, it has a convenient <a href="http://msdn.microsoft.com/en-us/library/ee378677(VS.100).aspx" rel="noreferrer">GetOrAdd</a> method.</p>
<pre><code>public TValue GetOrAdd(
TKey key,
Func<TKey, TValue> valueFactory
)
</code></pre>
<p>Very useful for global server caches. </p>
|
<p>EDIT: This was written prior to .NET 4 being released, when obviously there's <code>ConcurrentDictionary</code>. I'm leaving it here as a reference for those needing .NET 3.5.</p>
<p>I don't know of any equivalent to <code>ConcurrentHashMap</code>.</p>
<p>In terms of general concurrency utilities - .NET has always provided a bit more than the basics which Java used to provide, in terms of <a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx" rel="nofollow noreferrer"><code>Mutex</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" rel="nofollow noreferrer"><code>ManualResetEvent</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx" rel="nofollow noreferrer"><code>AutoResetEvent</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx" rel="nofollow noreferrer"><code>ReaderWriterLock</code></a>; then more recently (.NET 2.0) <a href="http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx" rel="nofollow noreferrer"><code>Semaphore</code></a> and (.NET 3.5) <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" rel="nofollow noreferrer"><code>ReaderWriterLockSlim</code></a> - as well as the process-wide thread pool, of course.</p>
<p>A bigger shake-up will come in .NET 4.0 when Parallel Extensions arrives - that should make concurrency <em>much</em> simpler. Likewise the <a href="http://channel9.msdn.com/pdc2008/TL55/" rel="nofollow noreferrer">Coordination and Concurrency Runtime</a> is finally breaking free of the shackles of the Microsoft Robotics Studio, although I'm not clear on exactly where it's headed (whether it'll be part of .NET itself, or a separate library).</p>
| 35,917
|
<p>I've heard that <code>SELECT *</code> is generally bad practice to use when writing SQL commands because it is more efficient to <code>SELECT</code> columns you specifically need.</p>
<p>If I need to <code>SELECT</code> every column in a table, should I use </p>
<pre><code>SELECT * FROM TABLE
</code></pre>
<p>or </p>
<pre><code>SELECT column1, colum2, column3, etc. FROM TABLE
</code></pre>
<p>Does the efficiency really matter in this case? I'd think <code>SELECT *</code> would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database.</p>
<p>I'm curious to know what the best practice is in this case.</p>
<p><strong>UPDATE:</strong> I probably should specify that the only situation where I would really <em>want</em> to do a <code>SELECT *</code> is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. </p>
<p>Given the responses I've seen however, this still seems like a bad idea and <code>SELECT *</code> should never be used for a lot more technical reasons that I ever though about.</p>
|
<p>One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. </p>
<p>Here's a post I wrote about it: <a href="http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx" rel="noreferrer"><strong>The real reason select queries are bad index coverage</strong></a> </p>
<p>It's also less fragile to change, since any code that consumes the data will be getting the same data structure regardless of changes you make to the table schema in the future.</p>
|
<p>There can be a huge performance gain by limiting what columns are returned if the records are traversing the internet.</p>
| 9,125
|
<p>I recently converted a site from asp to CF. Unfortunately, alot of the old users had the "homepage" bookmarked. www.example.com/homepage.asp</p>
<p>Is there a sort of catch all way I could redirect any traffic from that page to the current index.cfm?</p>
<p>I would normally just delete those files, but the owner(s) wanted to keep it around for their own comparison reasons.</p>
<p>Any ideas?</p>
<p>Thanks</p>
|
<p>Put this in the old homepage.asp</p>
<pre><code><%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location", "/index.cfm"
%>
</code></pre>
|
<p>The best bet is to do either a meta refresh in the actual homepage.asp page, it is quick and dirty, but works.</p>
<p>A better solution would be to have the .asp page do a 301 redirect to the new homepage, that way when search engines access the page as well they know it has moved.</p>
| 30,654
|
<p>I'm writing a basic crawler that simply caches pages with PHP.</p>
<p>All it does is use <code>get_file_contents</code> to get contents of a webpage and regex to get all the links out <code><a href="URL">DESCRIPTION</a></code> - at the moment it returns:</p>
<pre><code>Array {
[url] => URL
[desc] => DESCRIPTION
}
</code></pre>
<p>The problem I'm having is figuring out the logic behind determining whether the page link is local or sussing out whether it may be in a completely different local directory.</p>
<p>It could be any number of combinations: i.e. <code>href="../folder/folder2/blah/page.html"</code> or <code>href="google.com"</code> or <code>href="page.html"</code> - the possibilities are endless.</p>
<p>What would be the correct algorithm to approach this? I don't want to lose any data that could be important.</p>
|
<p>First of all, regex and HTML don't mix. Use:</p>
<pre><code>foreach(DOMDocument::loadHTML($source)->getElementsByTagName('a') as $a)
{
$a->getAttribute('href');
}
</code></pre>
<p>Links that may go outside your site start with protocol or <code>//</code>, i.e.</p>
<pre><code>http://example.com
//example.com/
</code></pre>
<p><code>href="google.com"</code> is link to a local file.</p>
<p>But if you want to create static copy of a site, why not just use <code>wget</code>?</p>
|
<p>You would have to look for http:// in the href. Else, you could determine if it starts with ./ or any combination of "./". If you don't find a "/" then you would have to assume that its a file. Would you like a script for this?</p>
| 47,145
|
<p>Informed options needed about the merits of flat file database. I'm considering using a flat file database scheme to manage data for a custom blog. It would be deployed on Linux OS variant and written in Java. </p>
<p>What are the possible negatives or positives regarding performance for reading and writing of both articles and comments?</p>
<p>Would article retrieval crap out because of it being a flat file rather than a RDBMS if it were to get slash-doted? (Wishful thinking)</p>
<p>I'm not against using a RDBMS, just asking the community their opinion on the viability of such a software architecture scheme.</p>
<p><strong>Follow Up:</strong>
In the case of this question I would see “Flat file == file system–based” For example each blog entry and its accompanying metadata would be in a single file. Making for many files organized by date structure of the file folders (blogs\testblog2\2008\12\01) == 12/01/2008</p>
|
<p>Flat file databases have their place and are quite workable for the right domain.</p>
<p>Mail servers and NNTP servers of the past really pushed the limits of how far you can really take these things (which is actually quite far -- files systems can have millions of files and directories). </p>
<p>Flat file DBs two biggest weaknesses are indexing and atomic updates, but if the domain is suitable these may not be an issue.</p>
<p>But you can, for example, with proper locking, do an "atomic" index update using basic file system commands, at least on Unix.</p>
<p>A simple case is having the indexing process running through the data to create the new index file under a temporary name. Then, when you are done, you simply rename (either the system call rename(2) or the shell mv command) the old file over the new file. Rename and mv are atomic operations on a Unix system (i.e. it either works or it doesn't and there's never a missing "in between state").</p>
<p>Same with creating new entries. Basically write the file fully to a temp file, then rename or mv it in to its final place. Then you never have an "intermediate" file in the "DB". Otherwise, you might have a race condition (such as a process reading a file that is still being written, and may get to the end before the writing process is complete -- ugly race condition).</p>
<p>If your primary indexing works well with directory names, then that works just fine. You can use a hashing scheme, for example, to create directories and subdirectories to locate new files.</p>
<p>Finding a file using the file name and directory structure is very fast as most filesystems today index their directories.</p>
<p>If you're putting a million files in a directory, there may well be tuning issues you'll want to look in to, but out of that box most will handle 10's of thousands easily. Just remember that if you need to SCAN the directory, there's going to be a lot of files to scan. Partitioning via directories helps prevent that.</p>
<p>But that all depends on your indexing and searching techniques.</p>
<p>Effectively, a stock off the shelf web server serving up static content is a large, flat file database, and the model works pretty good.</p>
<p>Finally, of course, you have the plethora of free Unix file system level tools at your disposal, but all them have issues with zillions of files (forking grep 1000000 times to find something in a file will have performance tradeoffs -- the overhead simply adds up).</p>
<p>If all of your files are on the same file system, then hard links also give you options (since they, too, are atomic) in terms of putting the same file in different places (basically for indexing). </p>
<p>For example, you could have a "today" directory, a "yesterday" directory, a "java" directory, and the actual message directory.</p>
<p>So, a post could be linked in the "today" directory, the "java" directory (because the post is tagged with "java", say), and in its final place (say /articles/2008/12/01/my_java_post.txt). Then, at midnight, you run two processes. The first one takes all files in the "today" directory, checks their create date to make sure they're not "today" (since the process can take several seconds and a new file might sneak in), and renames those files to "yesterday". Next, you do the same thing for the "yesterday" directory, only here you simply delete them if they're out of date.</p>
<p>Meanwhile, the file is still in the "java" and the ".../12/01" directory. Since you're using a Unix file system, and hard links, the "file" only exists once, these are all just pointers to the file. None of them are "the" file, they're all the same.</p>
<p>You can see that while each individual file move is atomic, the bulk is not. For example, while the "today" script is running, the "yesterday" directory can well contain files from both "yesterday" and "the day before" because the "yesterday" script had not yet run.</p>
<p>In a transactional DB, you would do that all at once.</p>
<p>But, simply, it is a tried and true method. Unix, in particular, works VERY well with that idiom, and the modern file systems can support it quite well as well.</p>
|
<p>Horrible idea. Appending would involve seeking to the end of the file every time you want to add something. Updating would require rewriting the entire file each time. Reading involves a table scan (or maintaining a separate index, which would have the same problems with writing/updating). Just use a database unless, of course, you re-implement all the stuff that an RDBMS already provides to make your solution even moderately scalable.</p>
| 43,136
|
<p>When trying to run the Flex Builder 3 profiler on any I don't get the profiler dialog window and then after a few seconds I get "Socket timeout" in the console window. Any ideas why it can't connect?</p>
<p>I've got the latest debug version of Flash player and have tried shutting off my firewall.<br>
I'm running it on XP from the local drive, ie. not through localhost.</p>
<p>Thanks,
Alex</p>
|
<p>It looks like the browser (Firefox in my case) has to be shutdown before the profiler is started. Step 1. in the livedocs even says this -- wish I had read it earlier. :)</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=profiler_3.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=profiler_3.html</a></p>
|
<p>Browser tabs, make sure you have latest debug as you said you did, also make sure that the port is correct, for some reason the port sometimes changes(1001 or 20957) from the default 9999, be sure that your mm.cfg has ProfilingFileOutputEnable=1 and that bittorrent isn't on.
hth</p>
| 14,070
|
<p>I'm writing some Java code that uses a FileReader to load data from a few input files. I'm using TDD pretty heavily, and I'd like to add some tests that ensure that I'm cleaning up properly by calling close() on the reader when I'm done with it. Unfortunately, I can't come up with a good way to test for this. Anyone have any insights?</p>
<p>Edited to add: I know I can test explicitly for the close call using mock objects, but I'd like to avoid it if possible, partly because I find they lead to somewhat brittler code, and partly because I'm curious whether it's possible to write code that can recognize the effects of not closing a file.)</p>
|
<p>I think the way to do this is to inject the FileReader, or a Factory that creates the FileReader, into your class. Then in your unit test you can inject a mock version of the FileReader and check that the proper method on it has been called. You might want to look at <a href="http://www.jmock.org/" rel="noreferrer">JMock</a> to create the mock FileReader and set up the expectation for the close method call.</p>
|
<p>If you can pass the FileReader object in to the call then you can provide a custom FileReader that has an overridden close method -- in that, you have a boolean variable that checks on closed or not. You can then use that for your unit test. </p>
| 46,728
|
<p>My windows service is creating a directory on a shared folder, and I am getting a error:</p>
<pre><code>at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalCreateDirectory(String fullPath, String path,DirectorySecurity dirSecurity)
at System.IO.Directory.CreateDirectory(String path, DirectorySecurity directorySecurity)
at System.IO.Directory.CreateDirectory(String path) at
</code></pre>
<p>I referencing the shared folder like: <code>\\255.255.255.255\myfolder.uploads\</code></p>
<p>Any ideas on what I have to do to be able to write to this folder? The share has Everyone and fullcontrol setup on it.</p>
<p><b>Updates</b></p>
<p>Do I have to impersonate a user on the other server somehow?</p>
|
<p>This could be a couple of things depending upon the platform your server runs. As a complete (and assuming a windows based server) guess cross check both the share AND the folder have write permissions given to the appropriate user account. </p>
<p>Just providing permissions on the share only may not work.</p>
<p>Hope that helps!</p>
|
<p>For security in shared folders on .net you need to configure the .net security with <a href="http://msdn.microsoft.com/en-us/library/2bc0cxhc(VS.80).aspx" rel="nofollow noreferrer">".net Framework Configuration Tool"</a>. </p>
| 49,214
|
<p>Hopefully a nice simple one.</p>
<p>I've got a php3 website that I want to run on php 5.2</p>
<p>To start with I'd just like to have every reference to the current "index.php3" _within_each_file_ (recursively) changed to "index.php" and then move on to worrying about globals etc.</p>
<p>K. Go!</p>
<p>:) </p>
<p>Update: Thanks a lot! I realise that my question missed the fact that the references are in each file of a website and I wanted to do it recursively in all files/folders.</p>
|
<pre><code>find -type f -exec perl -pi -e 's/\bindex\.php3\b/index.php/g' {} \;
</code></pre>
|
<p>To do this recursively, use Jonathan's answer but substitute <code>find . -type f</code> for *.php3. Note that the back ticks are important and you can substitute any directory for "." (i.e. the current directory). Here is a version that also renames the file in the process (*.php3 -> *.php).</p>
<pre><code>#!/bin/bash
for file in `find . -type f`
do
sed 's/\.php3/\.php/g' $file > ${file//3/}
rm $file
done
</code></pre>
| 39,629
|
<p>Can a Silverlight 2 enabled web page be managed from an Apache server? (I'm not actually interested in doing this but trying to understand Silverlight 2 a bit more.)</p>
<p>Assuming that I have IIS6 and Server 2003 what are the .NET version requirements to host a web site with Silverlight 2? Are .NET 3.0 and 3.5 required on the server? My thinking is not because this is a client side technology.</p>
|
<p>Since Silverlight is a browser technology, it is <strong>server-agnostic</strong> and can be hosted on a variety of server platforms: LAMP, UNIX, and IIS. You don't have to install .NET or any other Microsoft software on the server.</p>
<p>The only configuration required on the web server is to <strong>register the MIME types for content being served</strong>. If not already registered, you'll have to add following entries.</p>
<p>There are three MIME types required:</p>
<ul>
<li>.xaml - application/xaml+xml</li>
<li>.xap - application/x-silverlight-app</li>
<li>.xbap - application/x-ms-xbap</li>
</ul>
<p>Here are some instructions <a href="http://blogs.technet.com/jorke/archive/2007/09/11/silverlight-mime-types-in-iis6.aspx" rel="nofollow noreferrer">how to do that for Apache and IIS</a>.</p>
<p>Needless to say, some features such as <a href="http://blogs.msdn.com/jitghosh/archive/2007/11/30/demo-live-streams-in-silverlight.aspx" rel="nofollow noreferrer">WMS Streaming</a> rely on a server supporting them.</p>
|
<p>The <a href="http://www.microsoft.com/silverlight/overview/faq.aspx#sys-req" rel="nofollow noreferrer">system requirements for Microsoft Silverlight</a> and associated technologies are listed below.</p>
<pre><code>* Windows
o Operating System: Windows Vista; Windows XP Service Pack 2
o Intel® Pentium® III 450MHz or faster processor (or equivalent)
o 128MB of RAM
* Mac OS
o Operating System: Apple Mac OS X 10.4.8 or above
o Intel Core™ Duo 1.83GHz or faster processor
o 128MB of RAM
* Linux. For the system requirements, please refer to the Mono Project's Moonlight Web site.
</code></pre>
| 35,620
|
<p>I am looking to improve the performance of my site, not because it is performing badly but just as a general exercise. The usual suggestion for asp.net sites is to remove viewstate wherever possible. I believe this can be done by each control on a page separately or for the whole page.</p>
<p>My question is if I disable the page viewstate will this stop the viewstate of controls on a masterpage (as I understand it the masterpage is actually a control on the page). </p>
|
<p>Yes, the page is the originator of the page flow. Thus, disabling viewstate for the page takes the viewstate rendering out of the OnInit process. A better question would be why does disabling the viewstate for the master page do the same?</p>
|
<p>Just a quick note on the side before optimising the site, have you optimised the server by making sure all the files are gzipped before being sent.</p>
<p>If not this will get you a nice boost before you even start tinkering with the page. </p>
<p><a href="http://www.codinghorror.com/blog/archives/000059.html" rel="nofollow noreferrer">http://www.codinghorror.com/blog/archives/000059.html</a></p>
| 24,591
|
<p>WinForms C#.. am getting some JSON in the format below (bottom of message) and trying to deserialise using:</p>
<p>using System.Web.Script.Serialization;</p>
<p>When I had simply this json returned:</p>
<pre><code>{
"objects": [
{
"categoryid": "1",
"name": "funny",
"serverimageid": "1",
"dateuploaded": "2008-11-17 16:16:41",
"enabled": "1"
},
{
"categoryid": "2",
"name": "happy",
"serverimageid": "2",
"dateuploaded": "2008-11-17 16:17:00",
"enabled": "1"
},
{
"categoryid": "3",
"name": "sad",
"serverimageid": "3",
"dateuploaded": "2008-11-16 16:17:13",
"enabled": "1"
}
]
}
</code></pre>
<p>Then is was easy to deserialize: (yikes.. a bit hacky)</p>
<pre><code>// s is the string
s = s.Remove(0, 11);
// last }
int stringLength = s.Length;
s = s.Remove(stringLength - 1, 1);
listOfCategories = serializer1.Deserialize<List<Category>>(s);
</code></pre>
<p>Where</p>
<pre><code>public class Category
{
public int categoryID;
public string name;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int displayOrder;
}
</code></pre>
<p>However now, I'm stuck! Have tried a list of lists... but can't get anywhere..</p>
<p>Much appreciated any help.</p>
<pre><code>{
"objects": {
"categories": [
{
"name": "Congratulations",
"imageID": "1",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-27 00:00:00"
},
{
"name": "Animals",
"imageID": "2",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-26 00:00:00"
},
{
"name": "Romance",
"imageID": "3",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-24 00:00:00"
}
],
"present": [
{
"presentID": "1",
"name": "Tiger",
"categoryID": "2",
"imageID": "1",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "2",
"name": "Donkey",
"categoryID": "2",
"imageID": "2",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "3",
"name": "Elephant",
"categoryID": "2",
"imageID": "3",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
}
]
}
}
</code></pre>
|
<p>This seems to work fine (And no wacky string trimming!):</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
class Program
{
static void Main( string[] args )
{
string json = System.IO.File.ReadAllText( "../../input.json" );
var serializer = new JavaScriptSerializer();
Structure jsonStructure = serializer.Deserialize<Structure>( json );
System.Diagnostics.Debugger.Break();
}
}
class Structure
{
public StructureObjects objects;
}
class StructureObjects
{
public List<StructureCategory> categories;
public List<StructurePresent> present;
}
class StructureCategory
{
public string name;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int displayOrder;
}
class StructurePresent
{
public int presentID;
public string name;
public int categoryID;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int? isAnimated;
public int? isInteractive;
public int? isAdaptive;
public Uri webLinkURL;
}
</code></pre>
<p>Thanks for the System.Web.Script.Serialization pointer, I would never have found that!</p>
|
<p>Edit: The following works with <code>DataContractJsonSerializer</code>, but does <strong>not</strong> work with the JavascriptSerializer from the OP. So this is just for refernence.</p>
<pre><code>[DataContract]
class Foo
{
[DataMember(Name = "objects")]
public Bar Bar { get; set; }
}
[DataContract]
class Bar
{
public Bar() {
Categories = new List<Category>();
Present = new List<Present>();
}
[DataMember(Name = "categories")]
public List<Category> Categories { get; private set; }
[DataMember(Name = "present")]
public List<Present> Present { get; private set; }
}
[DataContract]
class Category
{
[DataMember(Name = "name")]
public string Name {get;set;}
[DataMember(Name = "imageID")]
public int ImageID {get;set;}
[DataMember(Name = "isActive")]
public int IsActive {get;set;}
[DataMember(Name = "displayOrder")]
public int DisplayOrder {get;set;}
[DataMember(Name = "dateUpdated")]
public string DateUpdated {get;set;}
}
[DataContract]
class Present
{
[DataMember(Name = "presentID")]
public int PresentID {get;set;}
[DataMember(Name = "name")]
public string Name {get;set;}
[DataMember(Name = "categoryID")]
public int CategoryID {get;set;}
[DataMember(Name = "imageID")]
public int ImageID {get;set;}
[DataMember(Name = "dateUpdated")]
public string DateUpdated {get;set;}
[DataMember(Name = "isActive")]
public int IsActive {get;set;}
[DataMember(Name = "isAnimated")]
public int? IsAnimated {get;set;}
[DataMember(Name = "isInteractive")]
public int? IsInteractive {get;set;}
[DataMember(Name = "isAdaptive")]
public int? IsAdaptive {get;set;}
[DataMember(Name = "webLinkURL")]
public string WebLinkUrl {get;set;}
}
</code></pre>
| 42,083
|
<p>The standard model has been that OpenGL is for professional apps (CAD) and Direct3D is for games. </p>
<p>With the debacle of openGL 3.0, is openGl still the natural choice for technical 3D apps (cad/GIS)?<br>
Are there scenegraph libraries for Direct3D? </p>
<p>(Of course Direct3D is windows only.)</p>
|
<p>D3D makes you pay the Microsoft "strategy tax." That is, D3D serves two masters. One is giving you features and performance. The other is to ensure lock-in to other MS products and the Windows platform generally. This has some consequences for you:</p>
<ol>
<li><p>A D3D app won't run on anything but Windows (including Xbox). Maybe you don't think that's important now. But if, down the road, you want to run on Mac, Linux, PS3, future consoles, etc., you may be glad you chose the platform-independent choice.</p></li>
<li><p>MS can make some arbitrary decisions. Will the next version of D3D only run on an OS that requires new hardware, is expensive, and lots of people don't want to upgrade to? Will they make some other future decision you don't agree with?</p></li>
<li><p>Historically, OpenGL has led D3D in quick exposure of new HW features. This is because there's a mechanism in the standard for vendors to add their own extensions, and for those extensions to eventually be folded into the main spec. D3D is whatever MS wants it to be, with input from vendors to be sure, but MS gets veto power. You could easily be in a situation like with Vista, where MS decided not to expose new HW features to the old DX, and only make the new DX available on Vista. This was quite a headache for game developers.</p></li>
</ol>
<p>Now then, this is the flavor of reasons why a "professional app" (CAD, animation, scientific visualization, GIS, etc.) would favor OGL -- apps like this want to be stable for many years, need ongoing maintenance and improvement, and want to run on many platforms. This is in contrast to games, which quite frequently are only on one platform, will be released but generally not "maintained" (there likely won't be a 2.0, an update for another OS three years hence, don't need to support older HW, etc.). Games want maximum performance and only need to work for a short time window and on a fixed number of platforms. If they need to target Windows anyway and D3D is a little faster, that may be the right choice since the negative D3D consequences won't hurt them like it would for a CAD app, say.</p>
|
<p>Direct3D is only available on Windows and XBox. If you plan on targeting Unix or Mac, in addition to Windows, OpenGL is a good choice.</p>
| 15,177
|
<p>In honor of the <a href="http://prize.hutter1.net/" rel="noreferrer">Hutter Prize</a>,
what are the top algorithms (and a quick description of each) for text compression?</p>
<p>Note: The intent of this question is to get a description of compression algorithms, not of compression programs.</p>
|
<p>The boundary-pushing compressors combine algorithms for insane results. Common algorithms include:</p>
<ul>
<li>The <a href="http://en.wikipedia.org/wiki/Burrows-Wheeler_transform" rel="noreferrer">Burrows-Wheeler Transform</a> and <a href="http://marknelson.us/1996/09/01/bwt/" rel="noreferrer">here</a> - shuffle characters (or other bit blocks) with a predictable algorithm to increase repeated blocks which makes the source easier to compress. Decompression occurs as normal and the result is un-shuffled with the reverse transform. Note: BWT alone doesn't actually compress anything. It just makes the source easier to compress.</li>
<li><a href="http://books.google.com/books?id=ChSOjgiY84YC&pg=PA141&lpg=PA141&dq=Prediction+by+Partial+Match+PPM&source=web&ots=HIq05xfhjB&sig=b5JSuIz9D9C7yJJCwLcoTL2ECnM&hl=en&sa=X&oi=book_result&resnum=3&ct=result" rel="noreferrer">Prediction by Partial Matching (PPM)</a> - an evolution of <a href="http://en.wikipedia.org/wiki/Arithmetic_coding" rel="noreferrer">arithmetic coding</a> where the prediction model(context) is created by crunching statistics about the source versus using static probabilities. Even though its roots are in arithmetic coding, the result can be represented with Huffman encoding or a dictionary as well as arithmetic coding.</li>
<li>Context Mixing - Arithmetic coding uses a static context for prediction, PPM dynamically chooses a single context, Context Mixing uses many contexts and weighs their results. PAQ uses context mixing. <a href="http://en.wikipedia.org/wiki/PAQ#Algorithm" rel="noreferrer">Here's</a> a high-level overview.</li>
<li><a href="http://en.wikipedia.org/wiki/Dynamic_Markov_Compression" rel="noreferrer">Dynamic Markov Compression</a> - related to PPM but uses bit-level contexts versus byte or longer.</li>
<li>In addition, the Hutter prize contestants may replace common text with small-byte entries from external dictionaries and differentiate upper and lower case text with a special symbol versus using two distinct entries. That's why they're so good at compressing text (especially ASCII text) and not as valuable for general compression.</li>
</ul>
<p><a href="http://www.maximumcompression.com/index.php" rel="noreferrer">Maximum Compression</a> is a pretty cool text and general compression benchmark site. Matt Mahoney publishes another <a href="http://www.cs.fit.edu/~mmahoney/compression/text.html" rel="noreferrer">benchmark</a>. Mahoney's may be of particular interest because it lists the primary algorithm used per entry.</p>
|
<p>If you want to use PAQ as a program, you can install the <code>zpaq</code> package on debian-based systems. Usage is (see also <code>man zpaq</code>)</p>
<pre><code>zpaq c archivename.zpaq file1 file2 file3
</code></pre>
<p>Compression was to about <strong>1/10th of a zip file's size</strong>. (1.9M vs 15M)</p>
| 29,265
|
<p>When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?</p>
|
<p>I think you want this <a href="http://pgl.yoyo.org/luai/i/io.popen" rel="noreferrer">http://pgl.yoyo.org/luai/i/io.popen</a> io.popen. But it's not always compiled in.</p>
|
<p>I don't know about Lua specifically but you can generally run a command as:</p>
<pre><code>comd >comd.txt 2>&1
</code></pre>
<p>to capture the output and error to the file comd.txt, then use the languages file I/O functions to read it in.</p>
<p>That's how I'd do it if the language itself didn't provide for capturing stanard output and error.</p>
| 16,054
|
<p>I have an Oracle table which contains event log messages for an application. We don't want this table to grow out of control and eat up too much space, so we'd like to set a cap on the number of rows that it can contain to some big number like one million.</p>
<p>So we'd like to tell Oracle that when the table grows too large, it should delete the oldest rows to make space for new rows.</p>
<p>Is there any way to do this? I imagine we could do this with a trigger or by making all inserts with a stored procedure, but is there anything simpler?</p>
<p>EDIT: A couple of answers have suggested solutions that involve partitions. We do not currently partition this table, although we have the ability to do so if necessary. However, from looking into the matter, it seems that even if we partition the table, we'd still need for some kind of a scheduled job to drop the old partitions, etc. So we've decided to forgo partitions in favor of a scheduled job to check the row count and delete old rows as necessary once per day.</p>
<p>Thanks for the help, everyone.</p>
|
<p>Depending on your definition of simpler...</p>
<p>My bias would be to schedule a job that runs periodically (say, nightly) in order to delete the oldest rows. If you expect that you could generate a million event logs in a single day, you may want the job to run more frequently, but nightly is generally sufficient for most people. This has the advantage of being asynchronous so that you're not incurring the overhead of counting a million rows every time you do an insert to find out if you have to purge some data. On the other hand, it does potentially require some administration to set up the job.</p>
|
<p>you can't tell Oracle to keep my table at a certain size. If this is news, partitioning might not be for you. Otherwise, I'd completely agree with Nick. </p>
<p>Remember the 1M is just a magic number that you've decided to keep, it's ok if it gets to 1.1M before an clean up occurs. If you do rolling partitions, you'll need to abandon your 1M number for a number of days to keep. You'll make, daily, weekly, whatever partitions and drop the oldest based on your criteria.</p>
<p>Add a comment to your question to indicate if you have partitioning.</p>
| 24,562
|
<p>I've got a load-balanced (not using Session state) ASP.Net 2.0 app on IIS5 running back to a single Oracle 10g server, using version 10.1.0.301 of the ODAC/ODP.Net drivers. After a long period of inactivity (a few hours), the application, seemingly randomly, will throw an Oracle exception:</p>
<blockquote>
<p>Exception: ORA-03113: end-of-file on communication channel at
Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32
errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx*
pOpoSqlValCtx, Object src, String procedure) at
Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery,
Boolean fillRequest, CommandBehavior behavior) at
Oracle.DataAccess.Client.OracleCommand.System.Data.IDbCommand.ExecuteReader()</p>
<p>...Oracle portion of the stack ends here...</p>
</blockquote>
<p>We are creating new connections on every request, have the open & close wrapped in a try/catch/finally to ensure proper connection closure, and the whole thing is wrapped in a using (OracleConnection yadayada) {...} block. This problem does not appear linked to the restart of the ASP.Net application after being spun down for inactivity.</p>
<p>We have yet to reproduce the problem ourselves. Thoughts, prayers, help?</p>
<hr />
<p><strong>More:</strong> Checked with IT, the firewall isn't set to kill connections between those servers.</p>
|
<blockquote>
<p>ORA-03113: end-of-file on communication channel</p>
</blockquote>
<p>Is the database letting you know that the network connection is no more. This could be because:</p>
<ol>
<li>A network issue - faulty connection, or firewall issue</li>
<li>The server process on the database that is servicing you died unexpectedly.</li>
</ol>
<p>For 1) (<strong>firewall</strong>) search tahiti.oracle.com for <code>SQLNET.EXPIRE_TIME</code>. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.</p>
<p>For 1) (<strong>network</strong>) speak to your network admin (connection could be unreliable)</p>
<p>For 2) Check the <code>alert.log</code> for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.</p>
<p>Support issues can be raised at <em>metalink.oracle.com</em> with a suitable Customer Service Identifier (CSI)</p>
|
<p>The article previously mentioned is good. <a href="http://forums.oracle.com/forums/thread.jspa?threadID=191750" rel="nofollow noreferrer">http://forums.oracle.com/forums/thread.jspa?threadID=191750</a> (as far as it goes) </p>
<p>If this is not something that runs frequently (don't do it on your home page), you can turn off connection pooling. </p>
<p>There is one other "gotcha" that is not mentioned in the article. If the first thing you try to do with the connection is call a stored procedure, ODP will HANG!!!! You will not get back an error condition to manage, just a full bore HANG! The only way to fix it is to turn OFF connection pooling. Once we did that, all issues went away.</p>
<p>Pooling is good in some situations, but at the cost of increased complexity around the first statement of every connection. </p>
<p>If the error handling approach is so good, why don't they make it an option for ODP to handle it for us????</p>
| 10,875
|
<p>I know this is odd. but I can't figure other ways to do what I need.
I have a controller: report and a view: report.
Also I have a view that acts as a dashboard where I can see several zones (partials).
I need to add this report view to my dashboard but don't know how.
This report view utilizes complex logic from controller and displays the results.
How could I "stuck" the (logic+presentation) of exising view (report) into my partial, so I could use it on my dashboard??</p>
<p>Thank you.
Valve.</p>
|
<p>(I hope I'm understanding the problem, here...)</p>
<p>This part seemed significant:</p>
<blockquote>
<p>This report view utilizes complex
logic from controller</p>
</blockquote>
<p>As a general rule, controllers should be simple. Really simple. The rule of thumb is "thin controller, fat model" (Rails Envy made some entertaining but useful <a href="http://www.railsenvy.com/2008/6/3/mvc-videos" rel="nofollow noreferrer">screencasts on the subject</a>)</p>
<p>What would happen if you created a new model (quite possibly not inheriting from ActiveRecord::Base) that encapsulated the logic you want to deliver into the partial? Then different controller/action combinations can deliver the information into your views as necessary/required.</p>
<p>Or have I completely missed the point (not impossible!)</p>
|
<p>I had a similar problem a while ago, when they deprecated render_controller. The only solution I found then was to use ajax, passing a parameter to the page you want to load that bypasses the layout.</p>
| 46,410
|
<p>Any hints or suggestions (filament type? suggested settings? model sources?) for 3D printing minis to use in Dungeons & Dragons?</p>
<p>I've done a couple where the support structures were difficult to break off without breaking off a hand or something.</p>
<p>I have a Lulzbot Mini (1), single-extruder if that makes any difference.</p>
|
<p>There are adequate demonstration videos on YouTube showing that it is possible to print very acceptable 28 mm scale miniatures with FDM printers, easily rivaling the quality of resin printers from only a few years ago.</p>
<p>There are a couple of key requirements to get optimum quality for small, highly detailed parts (like miniatures): the smallest practical nozzle (0.2 mm seems to be elected), the smallest practical layer height (for 0.2 mm nozzle, this seems to be 0.1 mm), and optimal temperature and cooling. Supports, if needed, can be optimized for layer skip, interface, and traditional or tree style. It may take several test prints to find the best combination, but once found this should remain fairly constant for a given printer and filament choice.</p>
<p>The final ingredient, of course, is patience -- small nozzle, fine layer height, possibly reduced print speed required for those, mean these prints will take longer than you'd think for the size of the final object -- but if you get the settings right, and are willing to wait, you can get good miniatures with FDM.</p>
<p>For filament choice, I'd suggest PLA, generally -- it's very tolerant stuff, except for temperature, and you aren't likely to leave your minis on the dash of your car in the sun anyway.</p>
|
<p>Buckle up, this is going to be rough:</p>
<p>FDM printers are not the best choice for printing figurines in the 25 to 40 mm scale that is typical for wargaming and D&D games. Resolution-wise, that's the area of <em>resin</em> printers.</p>
<p>But there are ways to get some partially decent prints made:</p>
<ul>
<li>you might want a small nozzle. 0.2 is about the smallest you can do without specialty extruders, so there is our lower limit.</li>
<li>You need to make sure to have a minimum layer time set, especially as the crosssections of figures are often rather slim.</li>
<li>Overhangs can be a pain</li>
</ul>
<p>You might be better-served printing "meeples" than actual figurines.</p>
| 1,931
|
<p>Why does nvarchar(256) seem to the be the standard for user names in SQL Server? </p>
<p>Any system functions that return a user name return nvarchar(256), the ASP Membership provider uses nvarchar(256)</p>
<p>256 seems like an odd number (yes, I know its even...) - 255 I could understand (1 byte address) but 256 doesn't make sense to me. </p>
<p>Can anyone explain?</p>
|
<p>As programmers we automatically count starting at 0, but in this case nvarchar(0) would mean no characters. Turns out that 256 is your nice round number 2^8.</p>
|
<p>Experience suggests that, across various database over a period of time, 256 seems to be the minimum value for the maximum length of string fields. I wouldn't be surprised if it goes back to dBASE.</p>
| 43,995
|
<p>I have a <code>mysql</code> database filled up and running on a <em>Windows</em> computer, is there any tool to transfer the database to another computer (running <em>Ubuntu</em>)?</p>
<p>Else I'll just write a <code>script</code> to take all the data base into <code>SQL</code> and <em>insert</em> it on the other computer. Just trying to save some time :)</p>
<p>Thank you all.</p>
|
<p>The tool you speak of already exists: mysqldump</p>
<p>It dumps out to sql, which you can then copy to another machine and re-load.</p>
<p>eg:</p>
<p>on source:</p>
<pre><code>mysqldump -u username -p databasename > dumpfile.sql
</code></pre>
<p>Then use ftp/rsync/whatever to move the file to the destination machine, and on there, create an empty database to import into and run:</p>
<pre><code>mysql -u username -p databasename < dumpfile.sql
</code></pre>
<p>You'll also need to set up permissions on any users that may have been transferred as well, as they aren't held within the database.</p>
<p>Alternatively, you can copy the files from the mysql data dir - but mysqldump is the easiest/most reliable way.</p>
<p>Worth noting that the table names may become case sensitive on one system when they weren't on the original. It depends on the config at both ends - in particular the case sensitivity (or otherwise) of the filesystem.</p>
|
<p>You can make a backup using any gui tool, like Mysql Administrator (<a href="http://dev.mysql.com/downloads/gui-tools/" rel="nofollow noreferrer">http://dev.mysql.com/downloads/gui-tools/</a> on Windows, aptitude install mysql-admin on Ubuntu) or phpmyadmin (<a href="http://www.phpmyadmin.net/home_page/index.php" rel="nofollow noreferrer">http://www.phpmyadmin.net/home_page/index.php</a> on Windows, aptitude install phpmyadmin on Ubuntu), and then recover it in the other computer.</p>
| 42,616
|
<p>More specifically, if I have:</p>
<pre><code>public class TempClass : TempInterface
{
int TempInterface.TempProperty
{
get;
set;
}
int TempInterface.TempProperty2
{
get;
set;
}
public int TempProperty
{
get;
set;
}
}
public interface TempInterface
{
int TempProperty
{
get;
set;
}
int TempProperty2
{
get;
set;
}
}
</code></pre>
<p>How do I use reflection to get all the propertyInfos for properties explicitly implementing TempInterface?</p>
<p>Thanks.</p>
|
<p>I think the class you are looking for is System.Reflection.InterfaceMapping.</p>
<pre><code>Type ifaceType = typeof(TempInterface);
Type tempType = typeof(TempClass);
InterfaceMapping map = tempType.GetInterfaceMap(ifaceType);
for (int i = 0; i < map.InterfaceMethods.Length; i++)
{
MethodInfo ifaceMethod = map.InterfaceMethods[i];
MethodInfo targetMethod = map.TargetMethods[i];
Debug.WriteLine(String.Format("{0} maps to {1}", ifaceMethod, targetMethod));
}
</code></pre>
|
<p>Jacob's code is missing a filter:</p>
<pre><code> var props = typeof(TempClass).GetInterfaces().Where(i => i.Name=="TempInterface").SelectMany(i => i.GetProperties());
foreach (var prop in props)
Console.WriteLine(prop);
</code></pre>
| 35,233
|
<p>We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a <kbd>ctrl</kbd><kbd>F5</kbd> refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.</p>
<p>Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.</p>
<p>As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?</p>
|
<p>As far as I know a common solution is to add a <code>?<version></code> to the script's src link.</p>
<p>For instance:</p>
<pre><code><script type="text/javascript" src="myfile.js?1500"></script>
</code></pre>
<hr>
<blockquote>
<p>I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?</p>
</blockquote>
<p>You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.</p>
<p>It would look something like this:</p>
<pre><code><script type="text/javascript" src="myfile.js?$$REVISION$$"></script>
</code></pre>
<hr>
<p>Of course, there are always better solutions like <a href="http://blog.greenfelt.net/2009/09/01/caching-javascript-safely/" rel="noreferrer">this one</a>.</p>
|
<p>A simple trick that works fine for me to prevent conflicts between older and newer javascript files. That means: If there is a conflict and some error occurs, the user will be prompted to press Ctrl-F5.</p>
<p>At the top of the page add something like</p>
<pre><code><h1 id="welcome"> Welcome to this page <span style="color:red">... press Ctrl-F5</span></h1>
</code></pre>
<p>looking like</p>
<p><a href="https://i.stack.imgur.com/yiqlQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yiqlQ.png" alt="enter image description here" /></a></p>
<p>Let this line of javascript be the last to be executed when loading the page:</p>
<pre><code>document.getElementById("welcome").innerHTML = "Welcome to this page"
</code></pre>
<p>In case that no error occurs the welcome greeting above will hardly be visible and almost immediately be replaced by</p>
<p><a href="https://i.stack.imgur.com/IVakd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IVakd.png" alt="enter image description here" /></a></p>
| 5,235
|
<p>Has anyone had any experience in building a 'real world' application with the <a href="http://www.codeplex.com/smartclient" rel="noreferrer">Smart Client Software Factory</a>, from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls.</p>
|
<p>We used SCSF for a real world app with about 10 developers. It was a steep learning curve to set up and develop a pattern of usage, but once it was set up, introducing new developers to the project was VERY easy. Using CAB and SCSF was very beneficial to our project especially getting each developer up to speed and productive. </p>
<p>A downfall of SCSF is that it provides ALOT of functionality that may not be used (we probably only used 60% of the functionality).</p>
<p>I am also using SCSF for a new project and am considering refactoring to PRISM. PRISM allows you to cull the functionality that is not used. If you use WPF, I suggest looking into PRISM.</p>
|
<p>We use the <a href="http://www.codeplex.com/servicefactory" rel="nofollow noreferrer">Web Service Software Factory</a>, and we really like it because it makes it easier for developers to follow standards and appropriate patterns. The learning curve for us wasn't bad - a few hours per developer at most.</p>
<p>Other than that, there aren't any other pros & cons worth mentioning.</p>
| 2,800
|
<p>The more I think about how I use computers, the more I become convinced that 'workflow' is the key factor in terms of productivity, and the way I should go about designing interactions. I'm thinking of workflow as the way we approach and manage data, information and knowledge as it relates to a task.</p>
<p>I'm starting out with my first web-framework - I've chosen kohana, because it seems relatively lightweight, well-featured and uses a language I'm already partly familiar with (PHP). Recently I've been studying a book on design-patterns, but feel a little daunted about putting the information to use.</p>
<p>I have a few ideas for simple web-applications, which I think might be useful additions to the web. I've sketched out my data-objects, and I've had a go at post-it-noting the stages involved.</p>
<p>Do any of you have any design tips for ensuring that my webapp grows around this concept of user-workflow? Aside from design-patterns, are there any other concepts I should research?</p>
|
<p>I think your right on that solid and engaging workflows are the key to successful user applications. As an example, consider this site (stackoverflow) which has an engaging and simple workflow around questions. It's a great example. I have been thinking a lot about this as well. Let me point you to a couple resources. One is a fantastic article by Bret Victor, now of Apple. <a href="http://worrydream.com/MagicInk/" rel="nofollow noreferrer">http://worrydream.com/MagicInk/</a>. It is about software design as information design. This is a different idea than workflow but I think it boils down to the same thing, giving users meaning information graphics that they can act upon easily and answers their top questions. Read that article, it might change your perspective of software, it did mine. Second, is the concept of flow (work <em>flow</em> right?) that is used in game programming. Consider these core ideas from <a href="http://www.jenovachen.com/flowingames/flowtheory.htm" rel="nofollow noreferrer">http://www.jenovachen.com/flowingames/flowtheory.htm</a>:</p>
<ul>
<li>We are up to the activity. </li>
<li>We are able to concentrate on the activity.</li>
<li>The activity has clear goals. </li>
<li>The activity has direct feedback. </li>
<li>We feel that we control the activity.</li>
<li>Our worries and concerns disappear.</li>
<li>Our subjective experience of time is altered.</li>
</ul>
<p>These sound like ingredients of a great workflow to me. </p>
<p>Also you might read the IPhone UI docs and study Apple apps in general, they are generally the best in the world at building UIs with solid workflow.</p>
|
<p>Look at the source code to (open source) alternative applications of a similar workflow orientation, and others written in the framework you have chosen.</p>
<p>Theory is excellent, but for true understanding you will need to investigate the actual concrete applications already out there.</p>
| 32,060
|
<p>I have a number of tables that use the trigger/sequence column to simulate auto_increment on their primary keys which has worked great for some time.</p>
<p>In order to speed the time necessary to perform regression testing against software that uses the db, I create control files using some sample data, and added running of these to the build process.</p>
<p>This change is causing most of the tests to crash though as the testing process installs the schema from scratch, and the sequences are returning values that already exist in the tables. Is there any way to programtically say "Update sequences to max value in column" or do I need to write out a whole script by hand that updates all these sequences, or can I/should I change the trigger that substitutes the null value for the sequence to some how check this (though I think this might cause the mutating table problem)?</p>
|
<p>You can generate a script to create the sequences with the start values you need (based on their existing values)....</p>
<pre><code>SELECT 'CREATE SEQUENCE '||sequence_name||' START WITH '||last_number||';'
FROM ALL_SEQUENCES
WHERE OWNER = your_schema
</code></pre>
<p>(If I understand the question correctly)</p>
|
<p>As part of your schema rebuild, why not drop and recreate the sequence? </p>
| 14,279
|
<p>I suppose it allows for moving changes from one branch to the next but that's what cherry picking is for and if you're not making a commit of your changes, perhaps you shouldn't be moving them around?</p>
<p>I have on occasion applied the wrong stash at the wrong branch, which left me wondering about this question.</p>
|
<p>As mentioned, if you want a “per-branch stash,” you really want a new branch forking off from the existing branch.</p>
<p>Also, besides the already mentioned fact that the stash allows you to pull into a branch that you’re working on, it also allows you to <em>switch</em> branches before you have committed everything. This is useful not for cherry-picking in the usual sense so much as for cherry-picking <em>your working copy</em>.</p>
<p>F.ex., while working on a feature branch, I will often notice minor bugs or cosmetic impurities in the code that aren’t relevant to that branch. Well, I just fix those right away. When time comes to commit, I selectively commit the relevant changes but not the fixes and cosmetics. Instead I stash those, which allows me to switch to my minor-fixes-on-stable branch, where I can then apply the stash and commit each minor fix separately. (Depending on the changes in question, I will also stash some of them yet again, to switch to a different feature branch, where I apply <em>those</em>.)</p>
<p>This allows me to go deep into programming mode when I am working, and not worry about proper librarianship of my code. Then when I take a mental break, I can go back and carefully sort my changes into all the right shelves.</p>
<p>If the stash weren’t global, this type of workflow would be far more difficult to do.</p>
|
<p>git-stash is most useful to me to move not-yet-checked-in changes off to a different branch than the one that is currently checked out.</p>
<p>For example - I often find myself doing simple changes on a bug-fixes branch; only to find that a change I'm working on is more complex than I first guessed. Git-stash is the easiest way to move that set of changes to a different branch.</p>
| 11,499
|
<p>I have images being sent to my database from a remote video source at about 5 frames per second as JPEG images. I am trying to figure out how to get those images into a video format so I can stream a live video feed to Silverlight.</p>
<p>It seems to make sense to create a MJPEG stream but I'm having a few problems. Firstly I was trying to stream via an HTTP request so I didn't have a deal with sockets but maybe this is breaking my code.</p>
<p>If I try surf to my stream from QT I get a video error, Media player shows the first frame image and Silverlight crashes :)</p>
<p>Here is the code that streams - since I content type used this way can only be sent once I know that it isn't ideal and might be the root cause. All images are coming in via a LINQ2SQL object.</p>
<p>I did already try simply updating the image source of an image control in Silverlight but the flicker isn't acceptable. If Silverlight doesn't support MJPEG then no point even continuing but it looks like it does. I do have access to the h.264 frames coming in but that seemed more complicated via MP4.</p>
<pre><code> Response.Clear();
Response.ContentType = "multipart/x-mixed-replace; boundary=--myboundary";
ASCIIEncoding ae = new ASCIIEncoding();
HCData data = new HCData();
var videos = (from v in data.Videos
select v).Take(50); // sample the first 50 frames
foreach (Video frame in videos)
{
byte[] boundary = ae.GetBytes("\r\n--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length:" + frame.VideoData.ToArray().Length + "\r\n\r\n");
var mem = new MemoryStream(boundary);
mem.WriteTo(Response.OutputStream);
mem = new MemoryStream(frame.VideoData.ToArray());
mem.WriteTo(Response.OutputStream);
Response.Flush();
Thread.Sleep(200);
}
</code></pre>
<p>Thanks!</p>
<p>EDIT: I have the stream working in firefox so if I surf to the page I see video! but nothing else accepts the format. Not IE, SL, Media player - nothing.</p>
|
<p>I did MJPEG a long time ago (3-4 years ago) and I'm scratching my head trying to remember the details and I simply can't. But, if its possible, I would suggest finding some kind of web site that streams MJPEG content and fire up wireshark/ethereal and see what you get over the wire. My guess is you are missing some required HTTP headers that firefox is little more forgiving about.</p>
<p>If you can't find a sample MJPEG stream over the internet, a lot of web cams have software that give you an MJPEG stream. The app I worked on it with was a console for multiple security cameras, so I know that is a common implementation for cams of all types (if they support a web interface).</p>
|
<p>First, write your mjpeg frames out to separate files. You should then be able to open these in Phototshop (this will independently verify that you are parsing the stream correctly). If this fails, by bet is that you have HTTP headers embedded in your image data.</p>
| 26,632
|
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer">shebang</a> line:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p>
<pre><code>if sys.version_info < (2, 4):
raise ImportError("Cannot run with Python version < 2.4")
</code></pre>
<p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p>
<pre><code>#!/usr/bin/env python2.4
</code></pre>
<p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p>
<p>What's the elegant solution?</p>
<p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
|
<p>"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.</p>
|
<p>@morais: That's an interesting idea, but I think maybe we can take it one step farther. Maybe there's a way to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow noreferrer">Ian Bicking's virtualenv</a> to:</p>
<ul>
<li>See if we're running in an acceptable environment to begin with, and if so, do nothing.</li>
<li>Check if there exists a version-specific executable on the <code>PATH</code>, i.e. check if <code>python2.x</code> exists <code>for x in reverse(range(4, 10))</code>. If so, re-run the command with the better interpreter.</li>
<li>If no better interpreter exists, use virtualenv to try and install a newer version of Python from the older version of Python and get any prerequisite packages.</li>
</ul>
<p>I have no idea if virtualenv is capable of this, so I'll go mess around with it sometime soon. :)</p>
| 6,195
|
<p>I have read (or perhaps heard from a colleague) that in .NET, TransactionScope can hit its timeout and then VoteCommit (as opposed to VoteRollback). Is this accurate or hearsay? I couldn't track down information on the web that talked about this issue (if it IS an issue), so I wonder if anyone has any direct experience with it and can shed some light?</p>
|
<p>If you mean in relation to SQL Server, then there is an issue that you can fix in the connection string; see my reply <a href="https://stackoverflow.com/questions/189534/net-transactionscope-class-and-t-sql-tran-commit-and-rollback#190332">here</a>, or the full details <a href="http://weblogs.asp.net/ryangaraygay/archive/2008/04/14/issue-with-system-transactions-sqlconnection-and-timeout.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>The short version is: ensure you have <code>Transaction Binding=Explicit Unbind;</code> in the connection string.</p>
<p>It isn't actually doing a vote commit - the transaction (and any early operations) has rolled back, but any subsequent operations (still inside the <code>TransactionScope</code>) can get performed in the nul-transaction, i.e. auto-commit.</p>
|
<p>The behaviour that Marc Gravell described has been changed in .Net 4.0. Instead of the operation being autocommitted, it will now throw an InvalidOperationException. So in 4.0 you no longer need to use Explicit Unbind.</p>
| 23,738
|
<p>How can my vbscript detect whether or not it is running in a UAC elevated context?</p>
<p>I have no problem detecting the user, and seeing if the user is within the Administrators group. But this still doesn't answer the question of whether the process has elevated privs or not, when running under Vista or Windows 2008. Please note, I need only to <em>detect</em> this status; not attempt to elevate or (err ..) de-elevate.</p>
|
<p>The method I finally settled on depends on the fact that Vista and Windows 2008 have the whoami.exe utility, and it detects the integrity level of the user who owns the process. A couple of screenshots help here:</p>
<p><a href="http://lh3.ggpht.com/_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512">WHOAMI, normal and elevated, on Vista http://lh3.ggpht.com/_Svunm47buj0/SQ6ql4iNjPI/AAAAAAAAAeA/iwbcSrAZqRg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512</a></p>
<p>You can see that when cmd is running elevated, whoami /groups reports a "High" mandatory integrity level and a different SID than when running non-elevated. In the pic, the top session is normal, the one underneath is running elevated after UAC prompt.</p>
<p>Knowing that, here is the code I used. It essentially checks the OS version, and if it is Vista or Server 2008, calls CheckforElevation which runs whoami.exe /groups, and looks for the string S-1-16-12288 in the output. In this example I just echo status; in the real script I branch to different actions based on the result.</p>
<pre><code>sub GetOSVersion
Dim strComputer, oWMIService, colOSInfo, oOSProperty, strCaption, strOSFamily
strComputer = "."
Set oWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colOSInfo = oWMIService.ExecQuery("Select * from Win32_OperatingSystem")
'I hate looping through just to get one property. But dunno another way!
For Each oOSProperty in colOSInfo
strCaption = oOSProperty.Caption
Next
If InStr(1,strCaption, "Vista", vbTextCompare) Then strOSFamily = "Vista"
If InStr(1,strCaption, "2008", vbTextCompare) Then strOSFamily = "2008"
If InStr(1,strCaption, "XP", vbTextCompare) Then strOSFamily = "XP"
If InStr(1,strCaption, "2003", vbTextCompare) Then strOSFamily = "2003"
If InStr(1,strCaption, "2000", vbTextCompare) Then strOSFamily = "2000"
If strOSFamily = "" Then
Wscript.Echo "No known OS found. (Script can detect Windows 2000, 2003, XP, Vista, 2008.)"
Else
Wscript.Echo "OS Family = " & strOSFamily
End If
Select Case strOSFamily 'if Vista/2008 then call CheckforElevation
Case "Vista"
CheckforElevation
Case "2008"
CheckforElevation
Case Else
Exit Sub
End Select
end sub
sub CheckforElevation 'test whether user has elevated token
Dim oShell, oExecWhoami, oWhoamiOutput, strWhoamiOutput, boolHasElevatedToken
Set oShell = CreateObject("WScript.Shell")
Set oExecWhoami = oShell.Exec("whoami /groups")
Set oWhoamiOutput = oExecWhoami.StdOut
strWhoamiOutput = oWhoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then boolHasElevatedToken = True
If boolHasElevatedToken Then
Wscript.Echo "Current script is running with elevated privs."
Else
Wscript.Echo "Current script is NOT running with elevated privs."
End If
end sub
</code></pre>
|
<p>a little bit shorter in WSH Jscript</p>
<pre><code>function isElevated(){
var strCaption = "";
for (var enumItems=new Enumerator(GetObject("winmgmts:\\\\.\\root\\CIMV2").ExecQuery("Select * from Win32_OperatingSystem")); !enumItems.atEnd(); enumItems.moveNext()) {
strCaption += enumItems.item().Caption;
}
if(/Vista|2008|Windows\s7|Windows\s8/.test(strCaption)){
return (new ActiveXObject("WScript.Shell").run('cmd.exe /c "whoami /groups|findstr S-1-16-12288"', 0, true)) == 0;
}else{return true}
}
WScript.Echo(isElevated());
</code></pre>
| 29,184
|
<p>I have trouble. One of the users of an application I'm developing is occasionally, but regularly, experiencing an application hang.</p>
<p>When this happens, we find an entry with a source of "Application Hang" in the machine's Event Log, with the informative message "Hanging application [my app], version [the right version], hang module hungapp, version 0.0.0.0, hang address 0x00000000."</p>
<p>I'm logging all unhandled exceptions that my application throws, and there aren't any entries in my log files when this happens.</p>
<p>My current working hypothesis is that this hang is occurring during the application's call to an unsafe legacy API. This wouldn't astonish me; I've been working with this API for years and while I haven't seen it hang before, it's genuinely crappy code. Also, the user's reporting that the program seems to hang at random times. I don't think this is really true. Not that I don't believe her, but that the code that talks to the legacy API is running inside a method called by a BackgroundWorker. If the background thread were making the application hang, this could very much look to the user like it were happening randomly.</p>
<p>So, I have two questions, one specific, one general.</p>
<p>The specific question: I would expect that if a method running on a non-UI thread were to hang, it would just kill the thread. Would it actually kill the whole application?</p>
<p>The general question:</p>
<p>I'm already logging all unhandled exceptions. My program's already set up to use tracing (though I'm going to need to add instrumentation code to trace activity in suspect methods). Are there other things I should be doing? Are there diagnostic tools that allow some kind of post-crash analysis when a .NET application hangs? Are there mechanisms inside the .NET framework that I can invoke to capture more (and more usable) data?</p>
<p><strong>EDIT:</strong> On a closer examination of my code, I'm remembering that all of its usage of BackgroundWorker is through a utility class I implemented that wraps the method called in an exception handler. This handler logs the exception and then returns it as a propoerty of the utility object. The completion event handler in the UI thread re-throws the exception (less than ideal, since I lose the call stack, but it's already been logged), causing the UI's main exception handler to report the exception to a message box and then terminate the app.</p>
<p>Since none of that is happening, I'm pretty confident that there's no exception being thrown in the background thread. Well, no .NET exception, anyway.</p>
<p><strong>Further followup:</strong></p>
<p>Mercifully, I've now gotten enough data from the users to be certain that the hang isn't occurring inside the legacy API. This means it's clearly something I'm doing wrong, which means that I can fix it, so, win. It also means that I can isolate the problem through tracing, which is another win. I'm very happy at the answers I got to this question; I"m even happier that I probably don't need them for this problem.</p>
<p>Also: PostSharp is outstanding. If you need to add instrumentation code to an existing application, you almost certainly should be using it.</p>
|
<p>In answer to your specific question, when a background/worker thread blocks or hangs, the effect on the rest of the application would depend a lot on the synchronization happening between the threads in the app. There's no particular reason why it would necessarily hang the whole app, but it's entirely possible that it would.</p>
<p>One possible way to diagnose this would be to generate a dump of the process while it's hung (assuming someone is around to notice when it happens). This would be done using <a href="http://msdn.microsoft.com/en-us/library/ms680360.aspx" rel="nofollow noreferrer">MiniDumpWriteDump</a>, from dbghelp.dll. It's fairly straightforward to write a simple tool that can dump a process (based on its pid), which could be provided to the customer experiencing the issue. Since this is a managed app, a full memory dump is preferable (MiniDumpWithFullMemory), but a normal dump should still have some useful info. Once you have the dump, you can use windbg or your post-mortem debugger of choice to see what might be going on.</p>
<p>If you go this route, <a href="http://msdn.microsoft.com/msdnmag/issues/03/06/Bugslayer/" rel="nofollow noreferrer">this msdn article</a> is a good starting point for managed dump debugging.</p>
|
<p>Thought 1) step into .net framework code (from a KB at my work):</p>
<p>If you’ve installed VS2008 SP1, all you need to do is go to Tools -> Options -> Debugging</p>
<ol>
<li>Uncheck Enable Just My Code</li>
<li>Check Enable .NET Framework Source Stepping</li>
<li>Check Enable source server support</li>
<li>Under Debugging -> Symbols, add a new location of <a href="http://referencesource.microsoft.com/symbols" rel="nofollow noreferrer">http://referencesource.microsoft.com/symbols</a></li>
</ol>
<p>Now when debugging something that’s got greyed-out framework code in the call stack, just right click the call line and choose Load Symbols.</p>
<p>Thought 2) Setup remote debugging <a href="http://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx</a> </p>
| 24,746
|
<p>What is the best way to perform a couple of tasks together and if one task fails then the next tasks should not be completed? I know if it were the database operations then I should have used Transactions but I am talking about different types of operations like the following: </p>
<p>All tasks must pass: </p>
<p>SendEmail
ArchiveReportsInDatabase
CreateAFile</p>
<p>In the above scenario all the tasks must pass or else the whole batch operation must be rollback. </p>
|
<p>in C#</p>
<p>return SendEmail() && ArchiveResportsInDatabase() && CreateAFile();</p>
|
<p>If your language allows it, this is very tidy:</p>
<ol>
<li>Put your tasks in an array of code blocks or function pointers.</li>
<li>Iterate over the array.</li>
<li>Break if any block returns failure.</li>
</ol>
| 20,350
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.