instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm working on building a development tool that is written in JavaScript.</p>
<p>This will not be an open source project and will be sold (hopefully) as a commercial product.</p>
<p>I'm looking for the best way to protect my investment. Is using an obfuscator (code mangler) enough to reasonably secure the code?</p>
<p>Are there other alternatives that I am not aware of?</p>
<p>(I'm not sure if obfuscator is the right word, it's one of the apps that takes your code and makes it very unreadable.)</p>
|
<p>I'm going to tell you a secret. Once you understand it, you'll feel a lot better about the fact that Javascript obfuscation is only really useful for saving bandwidth when sending scripts over the wire.</p>
<p>Your source-code is not worth stealing.</p>
<p>I know this comes as a shock to the ego, but I can say this confidently without ever having seen a line of code you've written because outside the very few realms of development where serious magic happens, it's true of all source-code.</p>
<p>Say, tomorrow, someone dumped a pile of DVDs on your doorstep containing the source code for Windows Vista. What would you be able to do with it? Sure, you could compile it and give away copies, but that's just one step more effort than copying the retail version. You could painstakingly find and remove the license-checking code, but that's something some bright kid has already done to the binaries. Replace the logo and graphics, pretend you wrote it yourself and market it as "Vicrosoft Mista"? You'll get caught.</p>
<p>You could spend an enormous amount of time reading the code, trying to understand it and truly "stealing the intellectual property" that Microsoft invested in developing the product. But you'd be disappointed. You'd find the code was a long series of mundane decisions, made one after the other. Some would be smarter than you could think of. Some would leave you shaking your head wondering what kind of monkeys they're hiring over there. Most would just make you shrug and say "yeah, that's how you do that."</p>
<p>In the process you'll learn a lot about writing operating systems, but that's not going to hurt Microsoft.</p>
<p>Replace "Vista" with "Leopard" and the above paragraphs don't change one bit. It's not Microsoft, it's <em>software</em>. Half the people on this site could probably develop a Stack Overflow clone, with or without looking at the source of this site. They just haven't. The source-code of Firefox and WebKit are out there for anyone to read. Now go write your own browser from scratch. See you in a few years.</p>
<p>Software development is an investment of time. It's utter hubris to imagine that what you're doing is so special that nobody could clone it without looking at your source, or even that it would make their job that much easier without an actionable (and easily detectable) amount of cut and paste. </p>
|
<p>That's probably about the best you can do. Just be aware that anybody with enough dedication, can probably de-obfuscate your program. Just make sure you're comfortable with that before embarking on your project. I think the biggest problem with this would be to control who's using it on their site. If somebody goes to a site with your code on it, and likes what it does, it doesn't matter that they don't understand what the code does, or can't read it, when they can just copy the code, and use it on their own site.</p>
| 4,904
|
<p>I have the original Prusa i3m3 printer. Prusa recommends cleaning the bed before each print with isopropanol (isopropyl alcohol), with only occasional cleaning with acetone. The textured bed prohibits using acetone.</p>
<p>Given the SARS-COV-2 situation and COVID-19, isopropanol is impossible to find, and will not be in stock on shelves in the US for months.</p>
<p>What would you suggest as an alternative that might still be found on store shelves?</p>
|
<p><strong>Ethanol</strong> (Ethyl Alcohol) should work just fine as long as it's around 80% or more. It's very similar to isopropanol as a cleaning solvent. What you're basically doing is removing any stray grease from the bed with a solvent that evaporates quickly. </p>
<p><strong>Methanol</strong> would also probably work. It's very poisonous though, and shouldn't come into contact with your skin, so it requires a bit more careful handling. Methanol also has the benefit that it can't be used for hand sanitizer (since it's absorbed through the skin), so supplies shouldn't run out. </p>
<p>Look for alternative sources, for example, methanol is often sold as de-icing agent for pneumatic brakes on trucks. Just make sure it's pure alcohol without anything funky added. </p>
|
<p>Dish soap will remove grease very well. Once you rinse it with a moist sponge and dry with a clean cloth most residues will be gone.</p>
| 1,618
|
<p>another issue in IE 6... <a href="http://plwd.co.uk/rangers" rel="nofollow noreferrer">link</a></p>
<p>The navbar link list has a border applied to the left side of each element. </p>
<p>In fireforx/safari this matches up with the navbar background but in IE the border/element spills out below the navbar ( the border sticks out the bottom).</p>
<p>EDIT: ALSO, the navbar is the entire length of the blue header in IE, when it should only be as big as the navigations links inside it! arg!</p>
<p>Any ideas? thanks.</p>
<p>Pictures:</p>
<p>How it looks in ie6:</p>
<p><a href="http://plwd.co.uk/rangers/images/ie6.jpg" rel="nofollow noreferrer">ie6 sucking http://plwd.co.uk/rangers/images/ie6.jpg</a></p>
<p>How it should look:</p>
<p><a href="http://plwd.co.uk/rangers/images/firefox.jpg" rel="nofollow noreferrer">alt text http://plwd.co.uk/rangers/images/firefox.jpg</a></p>
|
<p>Try getting rid of the height rule on the anchor tags, and using top/bottom margins/paddings to ensure they fill the space. I find CSS using floats a lot easier when you don't try to enforce heights on elements.</p>
|
<p>It's not the borders doing it - it's the line-height. Your nav anchors are inheriting "line-height: 2em" from #header. Try setting the line height on the anchors (or their parent LI's or the UL) to something smaller - maybe 1.5em or so - and then make up the difference with some top padding on the anchors</p>
| 28,738
|
<p>So our SQL Server 2000 is giving me the error, "The log file for database is full. Back up the transaction log for the database to free up some log space."</p>
<p>How do I go about fixing this without deleting the log like some other sites have mentioned?</p>
<p>Additional Info: Enable AutoGrowth is enabled growing by 10% and is restricted to 40MB.</p>
|
<p>To just empty it:</p>
<pre><code>backup log <dbname> with truncate_only
</code></pre>
<p>To save it somewhere:</p>
<pre><code>backup log <dbname> to disk='c:\somefile.bak'
</code></pre>
<p>If you dont really need transactional history, try setting the database recovery mode to simple.</p>
|
<p>Rename it it. eg:<br>
old-log-16-09-08.log</p>
<p>Then the SQL server can use a new empty one.</p>
| 9,858
|
<p>So I'm doing this in PHP but it is a logic issue so I'll try to write it as generically as possible.</p>
<p>To start here's how this pagination script works:</p>
<ol>
<li>for (<em>draw first three pages links</em>)</li>
<li>if (<em>draw ellipsis (...) if there are pages between #1's pages and #3's pages</em>)</li>
<li>for (<em>draw current page and two pages on each side of it links</em>)</li>
<li>if (<em>draw elipsis (...) if there are pages between #3's pages and #5's pages</em>)</li>
<li>for (<em>draw final three pages links</em>)</li>
</ol>
<p>The problem is that when there are low amounts of pages (I noticed this when the page count was at 10) there should be an ellipsis but none is drawn.</p>
<p>Onto the code:</p>
<pre><code>$page_count = 10; //in actual code this is set properly
$current_page = 1; //in actual code this is set properly
for ($i = 1;$i <= 3;$i++)
{
if ($page_count >= $i)
echo $i;
}
if ($page_count > 3 && $current_page >= 7)
echo "...";
for ($i = $current_page - 2;$i <= current_page + 2;$i++)
{
if ($i > 3 && $i < $page_count - 2)
echo $i;
}
if ($page_count > 13 && $current_page < $page_count - 5)
echo "...";
for ($i = $page_count - 2;$i <= $page_count;$i++)
{
if ($page_count > 3)
echo $i;
}
</code></pre>
<p>So I figure the best idea would to be to modify one of the two ellipsis if statements to include a case like this, however I've tried and am stumped.</p>
<p>Also please note that I condensed this code for readability sake so please don't give tips like "those for loops are ineffective because they will recalculate current_page - 2 for each iteration" because I know :)</p>
<hr>
<p>For those whom want to see a breakdown of how this logic currently works, here is example output ( modified ) with iterating $page_count and $current_page.
<a href="http://rafb.net/p/TNa56h71.html" rel="nofollow noreferrer">http://rafb.net/p/TNa56h71.html</a></p>
|
<pre><code><?php
/**
* windowsize must be odd
*
* @param int $totalItems
* @param int $currentPage
* @param int $windowSize
* @param int $anchorSize
* @param int $itemsPerPage
* @return void
*/
function paginate($totalItems, $currentPage=1, $windowSize=3, $anchorSize=3, $itemsPerPage=10) {
$halfWindowSize = ($windowSize-1)/2;
$totalPages = ceil($totalItems / $itemsPerPage);
$elipsesCount = 0;
for ($page = 1; $page <= $totalPages; $page++) {
// do we display a link for this page or not?
if ( $page <= $anchorSize ||
$page > $totalPages - $anchorSize ||
($page >= $currentPage - $halfWindowSize &&
$page <= $currentPage + $halfWindowSize) ||
($page == $anchorSize + 1 &&
$page == $currentPage - $halfWindowSize - 1) ||
($page == $totalPages - $anchorSize &&
$page == $currentPage + $halfWindowSize + 1 ))
{
$elipsesCount = 0;
if ($page == $currentPage)
echo ">$page< ";
else
echo "[$page] ";
// if not, have we already shown the elipses?
} elseif ($elipsesCount == 0) {
echo "... ";
$elipsesCount+=1; // make sure we only show it once
}
}
echo "\n";
}
//
// Examples and output
//
paginate(1000, 1, 3, 3);
// >1< [2] [3] ... [98] [99] [100]
paginate(1000, 7, 3, 3);
// [1] [2] [3] ... [6] >7< [8] ... [98] [99] [100]
paginate(1000, 4, 3, 3);
// [1] [2] [3] >4< [5] ... [98] [99] [100]
paginate(1000, 32, 3, 3);
// [1] [2] [3] ... [31] >32< [33] ... [98] [99] [100]
paginate(1000, 42, 7, 2);
// [1] [2] ... [39] [40] [41] >42< [43] [44] [45] ... [99] [100]
</code></pre>
|
<p>This is probably an overcomplicated solution, but it works. </p>
<p>I've used an array here instead of just printing, which lets me "do-over" the logic. </p>
<p>Part of the problem occurs when "left and right of page" happens to coincide with left-and-right shoulders. </p>
<pre><code>function cdotinator ( $current_page, $page_count )
{
$stepsize = 3;
$elipse = '...';
# Simple Case.
if ( $page_count <= 2 * $stepsize )
{
$out = range( 1, $page_count );
$out[$current_page - 1 ] = '*' . $current_page . '*';
return $out;
}
#Complex Case
# 1) Create All Pages
$out = range( 1, $page_count );
# 2 ) Replace "middle" pages with "." placeholder elements
for( $i = $stepsize+1 ; $i <= ( $page_count - $stepsize ) ; $i ++ )
{
$out[ $i - 1 ] = '.' ;
}
# 3.1 ) Insert the pages around the current page
for( $i = max(1,( $current_page - floor($stepsize / 2) )) ;
$i <= min( $page_count,( $current_page + floor( $stepsize/2)));
$i ++ )
{
$out[ $i - 1] = $i;
}
# 3.2 Bold Current Item
$out[ $current_page - 1 ] = '*' . $current_page . '*' ;
# 4 ) Grep out repeated '.' sequences and replace them with elipses
$out2 = array();
foreach( $out as $i => $v )
{
# end, current == peek()
end($out2);
if( current($out2) == $elipse and $v == '.' )
{
continue;
}
if( $v == '.' )
{
$out2[] = $elipse;
continue;
}
$out2[]= $v;
}
return $out2;
}
</code></pre>
<p>Output can be seen here: <a href="http://dpaste.com/92648/" rel="nofollow noreferrer">http://dpaste.com/92648/</a></p>
| 39,664
|
<p>I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.</p>
<p>I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!</p>
<pre><code> Error: The state information is invalid for this page and might be corrupted.
Target: Void ThrowError(System.Exception, System.String, System.String, Boolean)
Data: System.Collections.ListDictionaryInternal
Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**)
Offending URL: (**Omitted**)
Source: System.Web
Message: The state information is invalid for this page and might be corrupted.
Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
</code></pre>
|
<p>That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted. </p>
<p>Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx" rel="nofollow noreferrer">how ViewState works</a></p>
|
<p>Alternatively if you know the time-out length then you could add a bit of javascript to the page which redirects the user to an alternative page if there has been no activity on the page after a preset period of time. You can then extend this to warn the customer that their session / page is about to expire and provide them with a means to extend it (e.g. javascript server call back).</p>
| 9,905
|
<p>Using vim 7.1, I recently heard you can debug php in VI.
But how?</p>
|
<p><a href="http://computing.vt.edu/infrastructure_services/vtaix/learning.html#4" rel="noreferrer">Message of the day</a>, /etc/motd</p>
<p>i.e. edit the /etc/motd text file</p>
|
<p>Put some content in the file /etc/issue</p>
<p>Some more details in <a href="http://www.linuxfromscratch.org/blfs/view/svn/postlfs/logon.html" rel="nofollow noreferrer">http://www.linuxfromscratch.org/blfs/view/svn/postlfs/logon.html</a></p>
<hr>
<p>crap /etc/motd was the file i was trying to remember. Upvoting his answer :)</p>
| 30,530
|
<p>I am making a program in C# to connect to a webcam and do some image manipulation with it.</p>
<p>I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.</p>
<p>This is the code I use to connect the webcam:</p>
<pre><code>mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, 320, 240, 1024, 0);
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
</code></pre>
<p>And this is what I use to copy the image to the clipboard:</p>
<pre><code>SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
tempObj = Clipboard.GetDataObject();
tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
</code></pre>
<p>There's some error checking which I have removed from the code to make it shorter.</p>
|
<p>I've recently started doing some hobby work in this area.</p>
<p>We settled on using the <a href="http://sourceforge.net/projects/opencv/" rel="noreferrer">OpenCV</a> library with the <a href="http://code.google.com/p/opencvdotnet/" rel="noreferrer">opencvdotnet</a> wrapper. It supports capturing frames from a webcam:</p>
<pre><code>using (var cv = new OpenCVDotNet.CVCapture(0))
{
var image = cv.CreateCompatibleImage();
// ...
cv.Release();
}
</code></pre>
<p>And if you're doing image manipulation, OpenCV's image processing algorithms have been wrapped within the OpenCVDotNet.Algs assembly.</p>
<p>If you decide to go this route be sure to install OpenCV version 1.0 (and install it to "c:\program files\opencv" if you are on Vista 64-bit, or "mklink OpenCV 'c:\program files (x86)\OpenCV`" from the correct directory or else opencvdotnet will not install).</p>
|
<p>Have you tried Clipboard.GetImage()? You could also try the various Clipboard.Contains*() methods to see what format the data is stored in the clipboard.</p>
| 28,897
|
<p>I'm looking for a library to read a SWF file and let me parse through its actionscript and header information. Is there anything out there that will work?</p>
|
<p>I ended up finding one at:</p>
<p><a href="http://sourceforge.net/projects/swfdotnet/" rel="nofollow noreferrer">http://sourceforge.net/projects/swfdotnet/</a></p>
|
<p>I do not know of any libraries (including .NET) that let you read and parse (or reverse engineer) the contents of SWF's files. The ActionScript you are referring to is compiled down to byte code during compilation so you will not find the actual ActionScript source code in the SWF file.</p>
<p>For more information in the SWF file format I suggest you have a look at the <a href="http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v9.pdf" rel="nofollow noreferrer">official specifications</a>.</p>
| 36,150
|
<blockquote>
<p>This question exists because it has
historical significance, but it is not
considered a good, on-topic question
for this site, so please do not use it
as evidence that you can ask similar
questions here.</p>
<p>More info: <a href="https://stackoverflow.com/faq">https://stackoverflow.com/faq</a></p>
</blockquote>
<p>Anyone knows if it's possible to find all A records, CNAME or subzone records configured for a domain name?</p>
<p>For example, domain.com:</p>
<pre><code>www IN CNAME domain.com.
subdomain1 IN CNAME domain.com.
subdomain2 IN CNAME domain.com.
subdomain1 IN A 123.4.56.78.
subdomain2 IN A 123.4.56.79.
</code></pre>
<p>I want to keep a sub-domain private where I'll run an admin application (it will be password protected and on a special port, but I would prefer to keep it as private as possible).</p>
|
<p>Like others have said, what you want is a so called zone-transfer. If it is your own domain you can configure the DNS server to give it to you. If it is for some other domain you probably don't get it, since most DNS-admins consider it a security threat.</p>
<p>Even if an individual record isn't a problem (thats what the DNS it therefore) it could be a problem if an evil person gets a list of all your records: It could simplify an attack. </p>
|
<p>If name servers allow zone transfers you can use this page <a href="http://www.magic-net.info/dns-lookup.dnslookup" rel="nofollow noreferrer">http://www.magic-net.info/dns-lookup.dnslookup</a> to find all subdomains in given zone.</p>
<p>15 oct. I`m have modified my tool. Now it checks first 6 name servers for zone transfers and, if no one allow zone transfers, uses search engeines <a href="http://www.magic-net.info/dns-and-ip-tools.dnslookup" rel="nofollow noreferrer">Reverse lookup and subdomains search</a></p>
| 39,294
|
<p>Quite simple really:</p>
<pre><code>var req:URLRequest=new URLRequest();
req.url="http://somesite.com";
var header:URLRequestHeader=new URLRequestHeader("my-bespoke-header","1");
req.requestHeaders.push(header);
req.method=URLRequestMethod.GET;
stream.load(req);
</code></pre>
<p>Yet, if I inspect the traffic with WireShark, the <code>my-bespoke-header</code> is not being sent. If I change to <code>URLRequestMethod.POST</code> and append some data to <code>req.data</code>, then the header is sent, but the receiving application requires a GET not a POST. </p>
<p>The documentation mentions a blacklist of headers that will not get sent. <code>my-bespoke-header</code> is not one of these. It's possibly worth mentioning that the originating request is from a different port on the same domain. Nothing is reported in the policyfile log, so it seems unlikely, but is this something that can be remedied by force loading a crossdomain.xml with a <code>allow-http-request-headers-from</code> despite the fact that this is not a crossdomain issue? Or is it simply an undocumented feature of the Flash Player that it can only send custom headers with a POST request?</p>
|
<p>In your PagesMethods call, remove the parentheses from the callback and error functions:</p>
<pre><code>PageMethods.getAdCodeInfo(value, onSuccess, onError)
</code></pre>
<p><code>onSuccess</code> and <code>onError</code> are basically variables that point to the functions. So you don't need parentheses for variable names.</p>
|
<p>OK, stupid me. Here is some code. </p>
<pre><code> function getName()
{
var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');
var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;
//alert(value);
PageMethods.getAdCodeInfo(value,onSuccess(),onError());
}
function onSuccess(result)
{
alert(result);
}
function onError(error)
{
alert("error "+error);
}
</code></pre>
| 27,565
|
<p>In the NodeMouseClick event I'm trying to load some objects from the Node.Tag. Before I do so I check e.Node.IsSelected. When run regularly IsSelected is false....if I stick a break point around there and check e.node.Isselected, the value changes on me and becomes true. Why? </p>
|
<p>The NodeMouseClick event is raised before the selection actually changes. (When you click on the same node twice, the second time e.Node.IsSelected will certainly have been true.)</p>
<p>You could try handling the AfterSelect event, although that will also be raised when using the keyboard to navigate the treeview, which may even be better for your purposes.</p>
|
<p>I tried to recreate your problem but could not. When I click on a node for the first time this value is always false, whether I set a break point or not. If I click a node the second time the value is true. </p>
<p>If the node is selected by default the value will be true, but otherwise it will always return false on the first click.</p>
| 32,493
|
<p>For testing purposes I'm planning to put together a little app that will listen for a particular event coming from an application and interact with it at that point. </p>
<p>Given that we're at a point in the testing process where changing the application code is out of the question, the ideal from my point of view would be to listen to the debugging trace from the application, a little like debugview does, and respond to that.</p>
<p>Can anyone offer guidance on how best to go about this?</p>
|
<p>The way I found to do it used the <a href="http://blogs.msdn.com/jmstall/archive/2005/11/08/mdbg_linkfest.aspx" rel="noreferrer">Mdbg tools</a> from Microsoft to give me access from the runtime to the core debugging information. The basic shape of the code I'm using looks like this:</p>
<pre><code> MDbgEngine mg;
MDbgProcess mgProcess;
try
{
mg = new MDbgEngine();
mgProcess = mg.Attach(debugProcess.Id);
}
catch (Exception ed)
{
Console.WriteLine("Exception attaching to process " + debugProcess.Id );
throw (ed);
}
mgProcess.CorProcess.EnableLogMessages(true);
mgProcess.CorProcess.OnLogMessage += new LogMessageEventHandler(HandleLogMessage);
mg.Options.StopOnLogMessage = true;
mgProcess.Go().WaitOne();
bool running = true;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (running)
{
try
{
running =mgProcess.IsAlive;
mgProcess.Go().WaitOne();
}
catch
{
running = false;
}
}
</code></pre>
<p>It seems to work well enough for what I need at any rate, perhaps it will provide a useful template to anyone else who finds themselves in the same boat.</p>
|
<p>Is the application that you want to trace using standard <code>System.Diagnostics</code>-based tracing? In that case you could build your own <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener(VS.80).aspx" rel="nofollow noreferrer">TraceListener</a>.</p>
| 48,032
|
<p>Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only <em>part</em> of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though!</p>
<p>This can be easily achieved from the command line with:</p>
<pre><code>javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java
</code></pre>
<p>Now, how can you do that with ant? The javac ant <a href="http://ant.apache.org/manual/Tasks/javac.html" rel="noreferrer">task compiles everything</a>:</p>
<blockquote>
<p>The source and destination directory
will be recursively scanned for Java
source files to compile.</p>
</blockquote>
<p>One can use the <code>excludes</code> and <code>includes</code> parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the <code>includes</code> (not automatic dependency lookup), and <strong>even worst</strong> that <a href="http://ant.apache.org/manual/dirtasks.html#patternset" rel="noreferrer">excludes has priority on includes</a>:</p>
<blockquote>
<p>When both inclusion and exclusion are
used, only files/directories that
match at least one of the include
patterns and don't match <em>any</em> of the
exclude patterns are used.</p>
</blockquote>
<p>Thus, you cannot use </p>
<pre><code><javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"
excludes="**/*.java" includes="src/path/to/MyClass.java" />
</code></pre>
<p>Because it will not compile anything :-(</p>
<p>Is there any way of achieving that simple command line <code>javac</code> with ant?</p>
<hr>
<p>EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer):</p>
<p>1) I did read the documentation (see links above), but it's unclear that with just <code>includes</code> you are actually also excluding everything else</p>
<p>2) When you just <code>includes</code> ant logs something like</p>
<pre><code>[javac] Compiling 1 source file to /my/path/to/build
</code></pre>
<p>even if the dependencies make it compiling (much) more than just one source file.</p>
|
<p>Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work:</p>
<pre><code><javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"
includes="src/path/to/MyClass.java" />
</code></pre>
<p>Or more flexibly:</p>
<pre><code><javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath">
<include name="src/path/to/MyClass.java"/>
<include name="src/path/to/AnotherClass.java"/>
</javac>
</code></pre>
<p>To include only certain packages or classes in a jar, use a fileset attribute</p>
<pre><code><jar jarfile="${outlib}/something.jar">
<fileset dir="${build.dir}">
<include name='src/path/to/classes' />
</fileset>
</jar>
</code></pre>
<p>Again, you can use multiple includes to combine separate packages. Experiment with includes and <a href="http://ant.apache.org/manual/" rel="noreferrer">read the documentation</a> and you're sure to find the answer you need.</p>
|
<p>Actually, ant only <em>checks</em> everything, if you run a compile twice in a row you will notice the second is much quicker. Actually, it can be easily persuaded to miss things.</p>
<p>If you don't even want it to consider everything, you're going to have to break it down into smaller modules/projects/source trees so that you're explicitly telling ant what to compile.</p>
| 24,854
|
<p>I've incorporated <a href="http://www.libpng.org/pub/png/pngcode.html" rel="nofollow noreferrer">LIBPNG and ZLIB</a> into my C software for a microcontroller project due to their nicely liberal license which permits such use without requiring me to disclose any of my code (it's very similar to BSD/MIT/APACHE, but with no attribution requirement).</p>
<p>I'd like to look at using lossy image compression to save memory. The JPEG code I've found is either GPL, LGPL, or not C. I cannot use LGPL, because that still requires me to make it possible for users to replace the library with a newer or different version, which is not possible for this project.</p>
<p>I'm hoping you know of a suitable lossy image compression library. It doesn't have to be JPEG (I control both encoding and decoding) but it does have to be C, and at most BSD licensed or similar (attribution is fine).</p>
<p>-Adam</p>
|
<p>libjpeg ILJ at is C source and liberally licensed. </p>
<p><a href="http://www.ijg.org/" rel="nofollow noreferrer">http://www.ijg.org/</a></p>
<p>"We are releasing this software for both noncommercial and commercial use.
Companies are welcome to use it as the basis for JPEG-related products.
We do not ask a royalty, although we do ask for an acknowledgement in
product literature ..."</p>
<p>Mike</p>
|
<p>+1 on the <a href="http://www.ijg.org/" rel="nofollow noreferrer">Independent JPEG Group</a> library. </p>
<ul>
<li>It's in C</li>
<li>Highly portable</li>
<li>Small footprint</li>
<li>Liberally licensed</li>
<li>Highly regarded</li>
<li>Widely used</li>
<li>Stable (the last release was <em>over <strong>10 years</strong> ago</em> )</li>
</ul>
<p>Both Firefox and IE use IJG code for JPEG browsers. You can't get much better than that.</p>
| 33,930
|
<p>Apparently ;-) the standard containers provide some form of guarantees.</p>
<p>What type of guarantees and what exactly are the differences between the different types of container?</p>
<p>Working from <a href="http://www.sgi.com/tech/stl/" rel="noreferrer">the SGI page</a> (about <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>) I have come up with this:</p>
<pre><code>Container Types:
================
Container:
Forward Container
Reverse Container
Random Access Container
Sequence
Front Insert Sequence
Back Insert Sequence
Associative Container
Simple Associative Container
Pair Associative Container
Sorted Associative Container
Multiple Associative Container
Container Types mapped to Standard Containers
=============================================
std::vector: Sequence Back Sequence Forward/Reverse/Random Container
std::deque: Sequence Front/Back Sequence Forward/Reverse/Random Container
std::list: Sequence Front/Back Sequence Forward/Reverse Container
std::set: Sorted/Simple/Unique Associative Container Forward Container
std::map: Sorted/Pair/Unique Associative Container Forward Container
std::multiset: Sorted/Simple/Multiple Associative Container Forward Container
std::multimap: Sorted/Pair/Multiple Associative Container Forward Container
Container Guarantees:
=====================
Simp
or
For Rev Rand Front Back Assoc Sort Mult
Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont:
Copy Const: O(n)
Fill Const: O(n)
begin() O(1)
end() O(1)
rbegin() O(1)
rend() O(1)
front() O(1)
push_front() O(1)
pop_front() O(1)
push_back() O(1)
pop_back() O(1)
Insert() O(ln(n))
Insert: fill O(n)
Insert: range O(n) O(kln(n)+n)
size() O(1)
swap() O(1)
erase key O(ln(n))
erase element O(1)
erase range O(ln(n)+S)
count() O(log(n)+k)
find() O(ln(n))
equal range O(ln(n))
Lower Bound/Upper Bound O(ln(n))
Equality O(n)
InEquality O(n)
Element Access O(1)
</code></pre>
|
<p>I found the nice resource <em><a href="http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html" rel="noreferrer">Standard C++ Containers</a></em>. Probably this is what you all looking for.</p>
<p><strong>VECTOR</strong></p>
<p><strong>Constructors</strong></p>
<pre><code>vector<T> v; Make an empty vector. O(1)
vector<T> v(n); Make a vector with N elements. O(n)
vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)
vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n)
</code></pre>
<p><strong>Accessors</strong></p>
<pre><code>v[i] Return (or set) the I'th element. O(1)
v.at(i) Return (or set) the I'th element, with bounds checking. O(1)
v.size() Return current number of elements. O(1)
v.empty() Return true if vector is empty. O(1)
v.begin() Return random access iterator to start. O(1)
v.end() Return random access iterator to end. O(1)
v.front() Return the first element. O(1)
v.back() Return the last element. O(1)
v.capacity() Return maximum number of elements. O(1)
</code></pre>
<p><strong>Modifiers</strong></p>
<pre><code>v.push_back(value) Add value to end. O(1) (amortized)
v.insert(iterator, value) Insert value at the position indexed by iterator. O(n)
v.pop_back() Remove value from end. O(1)
v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)
v.erase(iterator) Erase value indexed by iterator. O(n)
v.erase(begin, end) Erase the elements from begin to end. O(n)
</code></pre>
<p>For other containers, refer to the page.</p>
|
<p>Another quick lookup table is available at this <a href="https://alyssaq.github.io/stl-complexities/" rel="nofollow noreferrer">github page</a></p>
<p>Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of <a href="http://cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html" rel="nofollow noreferrer">this</a></p>
| 21,936
|
<p>Hi I'm looking into iPhone development, and Objective-C is not be my preferred language. As far as I can see at this moment Ruby cannot be used to talk to Cocoa Touch at the moment on the iPhone.</p>
<p>So my question is, am I wrong? Can I use Ruby on the iPhone to develop Cocoa Touch applications. And what is the future looking like for Ruby on the iPhone?</p>
|
<p>No, you are correct. Currently, and most likely for the foreseeable future, Ruby will not be an option, at least for AppStore applications. There's no reason you couldn't do this on a Jailbroken phone, but Apple is pretty wed to Objective C for official development.</p>
|
<p>One possible solution would be to create an application wrapping for example the rice library (google it) which includes a ruby-vm. I reckon you would be able to create c++ wrappers that you could expose to ruby, thus making an environment for iphone development with ruby. This probably requires a lot of work though ^^</p>
| 27,043
|
<p>How can I combine the followings to fight spam and at the same time minimize annoyance imposed to the user?</p>
<ol>
<li>In registration page, sending an email to verify the email address</li>
<li>In registration page, use CAPTCHA</li>
<li>In every post page, use CAPTCHA</li>
</ol>
<p>Feel free to add new items to the list, and please tell your suggested scheme in boolean expression, eg: (1 and 3) or 2</p>
|
<p>Try using javascript to submit forms with a time limited variable in a hidden field. This will mean that bots won't currently be able to sumbit anything.</p>
|
<p>Comment spam is often done with botnets, so anything relying on IP blacklisting is just going to end up blocking legitimate users.</p>
<p>Focus on analyzing the message content with <a href="http://akismet.com/" rel="nofollow noreferrer">Akismet</a> or using a proven accessible CAPTCHA solution like <a href="http://recaptcha.net/" rel="nofollow noreferrer">reCAPTCHA</a>.</p>
<p>Libraries and plugins are available for most languages and applications.</p>
| 23,951
|
<p>We get sometimes the following error from our partner's database:</p>
<pre><code><i>ORA-01438: value larger than specified precision allows for this column</i>
</code></pre>
<p>The full response looks like the following:</p>
<pre><code><?xml version="1.0" encoding="windows-1251"?>
<response>
<status_code></status_code>
<error_text>ORA-01438: value larger than specified precision allows for this column ORA-06512: at &quot;UMAIN.PAY_NET_V1_PKG&quot;, line 176 ORA-06512: at line 1</error_text>
<pay_id>5592988</pay_id>
<time_stamp></time_stamp>
</response>
</code></pre>
<p>What can be the cause for this error?</p>
|
<p>The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store.</p>
<pre><code>select cast (10 as number(1,2)) from dual
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
select cast (15.33 as number(3,2)) from dual
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
</code></pre>
<p>Anything at the lower end gets truncated (silently) </p>
<pre><code>select cast (5.33333333 as number(3,2)) from dual;
CAST(5.33333333ASNUMBER(3,2))
-----------------------------
5.33
</code></pre>
|
<p>It is also possible to get this error code, if you are using PHP and bound integer variables (oci_bind_by_name with SQLT_INT).
If you try to insert NULL via the bound variable, then you get this error or sometimes the value 2 is inserted (which is even more worse).</p>
<p>To solve this issue, you must bind the variable as string (SQLT_CHR) with fixed length instead. Before inserting NULL must be converted into an empty string (equals to NULL in Oracle) and all other integer values must be converted into its string representation.</p>
| 21,887
|
<p>I saw something about needing to have the assembly available for the type of the first argument passed to the function. I think it is, I can't figure out what am I missing.</p>
<p>This code is in a service. I was running the service under the 'NETWORK SERVICES' user account, when I changed the account to that of the session I was logged on with it worked ok. But, what's the difference, and how can I get it to work for the NETWORK SERVICES user.</p>
|
<p>copy your binary to the bin folder of your web app will also fix this.</p>
|
<p>I finally found an answer: it appears that the type given to ApplicationHost.CreateApplicationHost() must be in an assembly located in the GAC.
Simple, and stupid :)</p>
| 41,964
|
<p>We have an error that we can't seem to find and don't have the need/resources to try and track it down. What we do need to do is just keep the freaking "Please tell Microsoft about this problem" dialog boxes from cluttering up the server.</p>
<p>It is from an MS-Access error (we think) but I can't find where Access is installed (I don't think it is); there is no MS Office directory on any of the drives.</p>
<p>If we could just stop the dialog boxes from appearing that would be great.</p>
<p>Thanks.</p>
<p>Spec: Window Server 2003 sp2</p>
|
<p>From <a href="http://www.codeproject.com/KB/exception/UnhandledExceptionClass.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/exception/UnhandledExceptionClass.aspx</a>:</p>
<blockquote>
<p>If you also want to disable the Windows “Send Error Report” dialog on your computer, right-click on the “My Computer” icon, select “Properties”, switch to the “Advanced” tab, and click on the “Error Reporting” button. In the Options dialog, select the “Disable error reporting” radio button:<br>
<img src="https://i.stack.imgur.com/1bjZg.png"></p>
</blockquote>
<p>Compare also <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/exception/ExceptionHandling.aspx</a> for general .NET Exception Handling sanity.</p>
|
<p>When working in .net, you can catch all unhandled exceptions (which is what causes this message). But I'm not aware of a way to do the same in Access.</p>
<p><a href="http://devcity.net/Articles/60/1/unhandled_exceptions.aspx" rel="nofollow noreferrer">http://devcity.net/Articles/60/1/unhandled_exceptions.aspx</a></p>
| 7,866
|
<p>Are there compilers for high-level languages (such as C) which can be targeted to various architectures by specifying the hardware resources of the target?</p>
<p>I'm wondering if there are compilers which can target an architecture by specifying features such as the available registers and instruction set of the processor (i.e. how each instruction changes the state of the processor), and memory layout of the architecture.</p>
<p>I am aware that compilers such as <a href="http://gcc.gnu.org/" rel="nofollow noreferrer">gcc</a> can target for multiple archtectures, but I'd like to know if there are compilers that can compile for new architectures by swapping out, say, configuration files, in order to target a new architecture.</p>
|
<p>AFAIK, gcc does work just like that. check <a href="http://gcc.gnu.org/onlinedocs/gccint/Machine-Desc.html" rel="nofollow noreferrer">"Machine Descriptions"</a> in the gcc docs. Of course, creating those <code>.md</code> files is a major programming effort.</p>
|
<p>I was listening to a podcast a while ago which talked about a Java virtual machine written (mostly) in Java, which targets multiple different platforms with some kind of platform definition file. I <em>think</em> I was listening to <a href="http://javaposse.com" rel="nofollow noreferrer">Java Posse</a> and I <em>think</em> it may have been the <a href="https://maxine.dev.java.net/" rel="nofollow noreferrer">Maxine Research Virtual Machine</a>. </p>
| 32,006
|
<p>I have been working on standardizing the source control structure for our Team Foundation Server rollout for the new year. I have started by using the <a href="http://www.codeplex.com/BranchingGuidance" rel="noreferrer">Microsoft Team Foundation Server Branching Guidance</a> documentation available on CodePlex.</p>
<p>I was hoping to get some feedback and answers to a few of the specific questions I have about the proposed structure. When it comes to structuring source control in TFS, I have learned that there are so many "standards" to choose from that there is not really a standard.</p>
<p>First, I will outline and describe the decisions and usage.</p>
<pre><code>$/
{Team Project}/
{Subproject}/
Development/
Trunk/
Source/
Tests/
Sandcastle/
TeamBuildTypes/
{Build Name}/
Branches/
{Branch Name}/
Source/
Tests/
Sandcastle/
TeamBuildTypes/
{Build Name}/
Integration/
Source/
Tests/
Sandcastle/
TeamBuildTypes/
{Build Name}/
Production/
Releases/
{Release Version}/
Source/
Tests/
Sandcastle/
TeamBuildTypes/
{Build Name}/
Branches/
{Branch Name}/
Source/
Tests/
Sandcastle/
TeamBuildTypes/
{Build Name}/
</code></pre>
<p>The general logic is that a Team Project can contain either a single logical project (where there would be no <code>{Subproject}</code> entry) or multiple related projects in the form of a product or tool suite. The three major containers are called <code>Development</code>, <code>Integration</code>, and <code>Production</code>.</p>
<p>Within the <code>Development</code> container's Trunk, there are provisions for both the projects which make up the product in the <code>Source</code> folder, with corresponding unit tests available in the <code>Tests</code> folder. A majority of minor development would occur in the trunk, with branching available through the <code>Trunk</code> folder's sibling <code>Branches</code> folder, which acts as a branching container. One or more solution files would live within the <code>Trunk</code>, allowing for branches at that level to capture the solution, source, and unit tests.</p>
<p>The <code>Integration</code> container, often called "main" in non-TFS implementation, is solely used to integrate Changesets from <code>Development</code> to create a stable and testable build. It is initially created as a branch from the <code>Development</code> container once a testable product has been attained. The builds from this container will be used for our testing environment and load testing environment. We choose to include load testing with testable builds so that we can monitor for changes in performance, being able to rapidly isolate Changesets that may have contributed to any irregularities.</p>
<p><code>Production</code> is used to produce pre-production and production quality builds. It is initially created as a branch from the <code>Integration</code> container once a stable build has been recommended for release. Within the <code>Releases</code> folder, a "branch by release" structure is followed, providing snapshotting and isolation in a single place. (For example, when <code>Release 1.1</code> is ready for a pre-production build, the stable <code>Integration</code> container is branched into a new <code>Release 1.1</code> folder in the <code>Production/Releases</code> structure. Subsequent RCs and RTWs/RTMs are promoted into this folder, as well.) A branching structure is also present, as seen in the <code>Branches</code> container. This allows for "hotfixes", usually a revision marker (Major.Minor.Revision). The branch is created from the current release and merged back into the new revision marker - like <code>Release 1.1.1</code>. The Changeset would be reverse integrated to the <code>Development</code> container's <code>Trunk</code> upon acceptance.</p>
<p>We feel that this structure is a fair balance between robustness and complexity. But there are a few nagging questions that I can not logically fit into the model. They are:</p>
<p><strong>Team Build</strong> - The <code>Development</code> and <code>Integration</code> containers will initially start out as being nightly builds, eventually moving to Continuous Integration (CI). The Production container will be manually built.</p>
<ul>
<li><p><del>Where should the build definitions live?</del> <strong>Edit - Based upon a couple of responses, the TeamBuildTypes folder has been moved to the trunk and branched to the appropriate containers. This does, however, lead to a new question (follows).</strong></p></li>
<li><p>By having the TeamBuildTypes folder in their appropriate containers, does that mean that all build definitions will be reproduced between the appropriate folders? For example, having a build definition for development quality builds, as well as testable builds, etc. all living in all TeamBuildType folders throughout the structure.</p></li>
</ul>
<p><strong>Documentation Generation</strong> - We use Sandcastle to generate documentation. Specifically, we also use <a href="http://www.codeplex.com/SHFB" rel="noreferrer">Sandcastle Help File Builder</a> to manage the output. This produces a project file in a format specific to SFHB.</p>
<ul>
<li><p>Should generated documentation be stored in the source control structure?</p></li>
<li><p>Should documentation be generated for each container, or does it only posses value for pre-production and production quality builds?</p></li>
<li><p>To preserve fast local build times, should documentation creation be owned by a build definition?</p></li>
<li><p><del>Where should the SHFB-specific files live? My initial inkling is to put it as a peer to the <code>Source</code> and <code>Tests</code> folders.</del> <strong><em>I agree with the recommondations that it be a peer to <code>Source</code> and <code>Tests</code>. Diagram changed to reflect this change.</em></strong></p></li>
</ul>
<p><strong>Third Party Binaries</strong></p>
<ul>
<li><p>Should binaries (controls, libraries, etc.) be stored in source control?</p></li>
<li><p>If so, should it be it's own Team Project?</p></li>
</ul>
<p><strong>General Documentation</strong> - Non-generated documentation, such as requirements, design documents, test plans, etc. are not going to be reflected by a folder in the source control structure. After some research and discussion with my developers and peers, using the built-in Documents folder in Team Explorer provides more benefit, since it mirrors the structure within the Team Project Portal and some (business) users do not need the additional complexity of learning the source control aspect of TFS.</p>
<hr>
<p>I will update the structure as I get answers to the questions to provide a clearer picture. I also welcome any other comments related to potential changes. If I have any other questions, I will make sure to modify this post.</p>
<p><strong>Edits:</strong></p>
<ul>
<li><p><strong>Clarification. <code>Source</code> and <code>Tests</code> folders do live under the <code>Integration</code> container, as well.</strong></p></li>
<li><p><strong>Both Micah and Josh brought up great points regarding third party binaries. Question added regarding the issue.</strong></p></li>
<li><p><strong>Documentation generation can be slow. Question added regarding whether documentation creation should be owned by a specific Team Build Type.</strong></p></li>
<li><p><strong>Added resolution related to non-generated documentation, such as requirements, design documents, test plans, etc.</strong></p></li>
<li><p><strong>Added resolution related to TeamBuildTypes folder for build defintions.</strong></p></li>
<li><p><strong>Based upon various feedback, moved the TeamBuildTypes folder to the trunk / branch levels.</strong></p></li>
</ul>
|
<p>I like your idea of putting the Sandcastle files as a peer to Source and Tests, I would add a documentation folder, that would then contain the sandcastle files, and optionally the actual documentation.</p>
<p>There are definetly differences of opinions and I'm sure I will be downvoted for this (since I have been before). I would put the generated documentation in TFS for a couple of reasons:</p>
<ol>
<li>Your going to want your documentation with each release, and using TFS is an easy aproach to ensure your documentation stays in the correct place.</li>
<li>Using TFS to store it means everyone will know where to go get the documentation.</li>
</ol>
<p>One thing I don't see which I always struggle with is where to third party dependancies, it might be that they belong down under the source so they are with each project although if you wanted to share them accross projects you could add a new top level node.</p>
<h1>Edit</h1>
<p>For my binaries I usually end up with</p>
<p>$/ThirdParty/Company/Product/Version/Src(optional)</p>
<p>So for example I have </p>
<p>$/ThirdParty/
Microsoft/
EntLib/
3.1
4.0
ComponentArt/
WebUI/
2008.1/
Src</p>
<p>I like to add the source, I've had to patch CA's source which I hate to do but when a third party doesn't fix the bug you have to resort to this.</p>
|
<p>Great layout and explanation. I've struggled with the exact same issues. I've wound up with a very similar structure. Mine varies slightly.</p>
<pre><code>Development/
Trunk/
Binaries/ -- Shared libraries
Source/
Test/
Docs/ -- Documentation
TeamBuildTypes/ -- Build definitions
</code></pre>
<ul>
<li>Adding the binaries folder allows you to have one location in the branch where all your projects can reference shared libraries</li>
<li>We put the documentation here so it can travel along with it's specific branch. </li>
<li>Our build definitions are at the development level since we can figure them in one location for all of the branches, but it could definitely be at the branch level which may make more sense.</li>
</ul>
<blockquote>
<p>Should binaries (controls, libraries,
etc.) be stored in source control? If so, should it be it's own Team
Project?</p>
</blockquote>
<p>I think they should definitely be source controlled, but I don't see any reason to put them in their own team project. One issue to be careful with is TFS for some reason treats binary files slightly different. I've had issues where I've updated the binaries in source control, but "Getting Latest" on other machines doesn't cause update of the files. Sometimes you need to do "Get Specific Version" and check the "Overwrite Unchanged Files" option for that particular file.</p>
| 49,934
|
<p>My website makes a lot of requests. I often need to cancel all current requests, so that the browser is not blocking relevant new requests.</p>
<p>I have 3 kinds of requests:</p>
<ul>
<li>Ajax</li>
<li>inserted script-tags (which do JSONP-Communication)</li>
<li>inserted image-tags (which cause the browser to request data from various servers)</li>
</ul>
<p>For Ajax its no problem as the XMLHttpRequest object supports canceling.
What I need is a way to make any browser stop loading resources, from DOM-Objects.</p>
<p>Looks like simply removing an object (eg. an image-tag) from the DOM only helps avoiding an request, if the request is not already running.</p>
<p><strong>UPDATE:</strong> a way to cancel all requests, which are irrelevant, instead of really any request would be perfect. </p>
|
<p><code>window.stop()</code> should cancel any pending image or script requests.</p>
|
<p>I think <code>document.close()</code> stops all requests, but I'm not so sure about it.</p>
| 14,319
|
<p>Well behaved windows programs need to allow users to save their work when they are shutting the PC down.</p>
<p>How can I make my app detect the shutdown event? Any solution should allow the user to abort the shutdown if user selects, say "Cancel".</p>
<p>The normal Swing window closing hook doesn't work, nor does adding a shutdown hook.</p>
<p>On testing, the methods of WindowListener (windowClosing,windowClosed, etc) do not get called.</p>
<p>The answer I have accepted requires the use of platform specific code (JNI to register for WM_QUERYENDSESSION ). Isn't this a bug on Swing?</p>
<p>See <a href="http://forums.sun.com/thread.jspa?threadID=481807&messageID=2246870" rel="nofollow noreferrer">http://forums.sun.com/thread.jspa?threadID=481807&messageID=2246870</a></p>
|
<p>Write some JNI code to WM_QUERYENDSESSION message. You can get details for this from the MSDN documentation or by googling it.</p>
<p>If you don't want to write too much C++ code to do this I can recommend the JNA library <a href="https://jna.dev.java.net/" rel="nofollow noreferrer">click here</a>. Which gives you some nice Java abstractions for C code.</p>
|
<p>The above seems to be the better answer.</p>
<p>I can't find any good information on detecting window shutdown events. I guess the best possible method would be to detect weather your application is trying to close, using a window closing event or the like then ask the question.</p>
<p><a href="http://www.javalobby.org/java/forums/t17933" rel="nofollow noreferrer">http://www.javalobby.org/java/forums/t17933</a></p>
| 9,740
|
<p>I'm looking at buying a code-signing certificate from Comodo (they seem to be the cheapest).</p>
<p>Can someone who has done this tell me how long it takes to issue the certificate once you submit your business documents?</p>
|
<p>took us about 1 business day, once we faxed all the necessary docs</p>
|
<p>It took us 8 business days (10 total days) to receive ours, but Comodo had a hard time verifying our company. I recommend submitting your DUNS # as well as your yellowbook.com listing to them to aid in speeding up the request. We did not do so originally, and they were trying to verify us through a list of 3rd party websites I'd never even heard of before that our information was not on, or was incorrect on.</p>
| 47,648
|
<p>Is it possible to modify/write data to an XML file without any server-side proxy(e.g. a php or asp script)? Can this be done via javascript? XSLT?</p>
|
<p>You can load and modify xml in browser, but writing the file back is a different thing. </p>
<p>I don't know of any feasible way of writing data back to a server without some kind of server side mechanism to write the data to disk. </p>
|
<p>Yes it is possible. You can do it with pure javascript or using a library like <a href="http://jquery.com/" rel="nofollow noreferrer">jquery</a></p>
| 29,966
|
<p>Similar questions have been asked, but nothing exactly like mine, so here goes.</p>
<p>We have a collection of Microsoft Word documents on an ASP.NET web server with merge fields whose values are filled in as a result of user form submissions. After the field merge, the server must convert the document to PDF and stream it down to the browser. Our first inclination was to use the Visual Studio Tools for Office API; however, we ran into <a href="http://support.microsoft.com/?id=257757" rel="noreferrer">this warning from Microsoft</a>:</p>
<blockquote>
<p>Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.</p>
</blockquote>
<p>It looks like the field manipulation can be done using the <a href="http://msdn.microsoft.com/en-us/library/aa982683.aspx" rel="noreferrer">Open XML SDK</a>, but what's the best way to convert Word 2007 documents to PDF without opening Word? The optimal solution would be low-cost, scalable, have a low memory footprint, be easy to deploy, and have a .NET API.</p>
|
<p>It's not exactly Open Source, but Aspose has a couple products which can do that,</p>
<p><a href="http://www.aspose.com/categories/file-format-components/aspose.pdf.kit-for-.net-and-java/default.aspx" rel="noreferrer">Aspose.Pdf.Kit</a></p>
<blockquote>
<p>Aspose.Pdf.Kit is a non-graphical PDF® document manipulation component that enables both .NET and Java developers to manage existing PDF files as well as manage form fields embedded within PDF files. Aspose.Pdf is perfect for creating new PDF files; however, developers often need to edit already existing PDF documents. Aspose.Pdf.Kit allows them to do just that. Aspose.Pdf.Kit allows developers to create powerful applications for merging data directly into PDF documents as well as for updating and managing PDF documents. Aspose.Pdf.Kit is a wonderful product and works great with the rest of our PDF products.</p>
</blockquote>
<p>and <a href="http://www.aspose.com/categories/file-format-components/aspose.pdf-for-.net-and-java/default.aspx" rel="noreferrer">Aspose.pdf</a></p>
<blockquote>
<p>Aspose.Pdf is a non-graphical PDF® document reporting component that enables either .NET or Java applications to create PDF documents from scratch without utilizing Adobe Acrobat®. Aspose.Pdf is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. Aspose.Pdf supports the creation of PDF files through API, XML templates and XSL-FO files. Aspose.Pdf is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic.</p>
</blockquote>
<p>Check out the <a href="http://www.aspose.com/documentation/file-format-components/aspose.pdf-for-.net-and-java/aspose.pdf-for-.net-api-reference.htm" rel="noreferrer">API</a> and <a href="http://www.aspose.com/demos/aspose.words/default.aspx" rel="noreferrer">demos</a>. You can download a DLL for free to try it out. I've used both before and they work out great.</p>
<p>There's also <a href="http://itextsharp.sourceforge.net/" rel="noreferrer">iTextSharp</a> which is a C# port of iText, a Java PDF converter. I've heard some people try it with mixed results. </p>
|
<p>Microsoft PDF add-in for word seems to be the best solution for now but you should take into consideration that it does not convert all word documents correctly to pdf and in some cases you will see huge difference between the word and the output pdf. Unfortunately I couldn't find any api that would convert all word documents correctly. The only solution I found to ensure the conversion was 100% correct was by converting the documents through a printer driver. The downside is that documents are queued and converted one by one, but you can be sure the resulted pdf is exactly like the word docuemtn. I personally preferred using UDC (Universal document converter) and installed Foxit Reader(free version) on server too then printed the documents by starting a "Process" and setting its Verb property to "print". You can also use FileSystemWatcher to set a signal when the conversion has completed.</p>
| 19,319
|
<p>I need to have some information about the Scoping issue in Javascript. I know that it spports lexical(static) scoping, but, does not it support dynamic scoping as well?
If you know anything about the scoping in Javascript, would you please share them with me ?</p>
<p>Thanks</p>
|
<p>I think you're confused because Javascript uses static scoping but at function-level, not at block level like usual structured languages.</p>
<pre><code>var foo = "old";
if (true) {var foo = "new";}
alert (foo == "new")
</code></pre>
<p>So be careful, blocks don't make scope!
That's why you sometimes see loops with functions inside just to enable variables whose scope is inside an iteration:</p>
<pre><code>functions = [];
for(var i=0; i<10; i++) {
(function(){
var local_i = i;
functions[local_i] = function() {return local_i;}
})();
}
functions[2]() // returns 2 and not 10
</code></pre>
|
<p>As far as I understood; Javascript has two kinds of variables which are global and local variables. But, suppose we have a variable called x, which is defined as global, and defined in the static parent of the scope of place where x is referenced. In this case, x takes the value of the global variable. Thus, global variable has higher priority than local ones. And, when there is no any global variables, x finds the declaration through the static chain which makes me think that Javascirpt is staticaly scoped language.</p>
<p>Am I right at above?</p>
| 42,432
|
<p>I am using VSTO with Excel 2007 to generate PivotTables and PivotCharts dynamically.
I am having a problem when I need to have a PivotField in more than one column. </p>
<p>To accomplish this I create a PivotTable in Excel and serialize its properties into an XML document, which I then use to rebuild the PivotTable.</p>
<p>Ie: as a Value and as a Column</p>
<p>This is possible when building the PivotTable in Excel. Has found a way to do this using C# ?</p>
<p><a href="http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx" rel="nofollow noreferrer">Creating a PivotTable Programmatically</a></p>
|
<p>If you add a calculated field to a Piviot Table and make the formula simply be the name of the field you need a duplicate of that allows you to use the same field twice, the Calculated Field does have to be a Value field. </p>
<p>Prehaps you can do this programaticly.</p>
|
<p>Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user.</p>
<pre><code>for (int cIndex = 1; cIndex < 1 + columns; cIndex++)
sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);
if (rows > 0)
{
//select the range where the data will be pasted
Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);
//Convert the datatable to an object array
object[,] workingValues = new object[rows, columns];
for (int rIndex = 0; rIndex < rows; rIndex++)
for (int cIndex = 0; cIndex < columns; cIndex++)
workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();
r.Value2 = workingValues;
}
</code></pre>
| 13,110
|
<p>I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)</p>
<p>I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable.</p>
<p>For example:</p>
<pre><code>g++ -o build/bin/myapp build/bin/_mylib.so
</code></pre>
<p>Is there a way to link to this library without causing the path to be hardcoded into the executable?</p>
|
<p>There is the ":" prefix that allows you to give different names to your libraries.
If you use </p>
<pre><code>g++ -o build/bin/myapp -l:_mylib.so other_source_files
</code></pre>
<p>should search your path for the _mylib.so.</p>
|
<p>If you are on Unix or Linux I think you can create a symbolic link to the library in the directory you want the library.<br>
<br>
For example:<br>
<code>ln -s build/bin/_mylib.so build/bin/lib_mylib.so</code><br>
<br>
You could then use <code>-l_mylib</code>
<br>
<br>
<a href="http://en.wikipedia.org/wiki/Symbolic_link" rel="nofollow noreferrer"><code>http://en.wikipedia.org/wiki/Symbolic_link</code></a></p>
| 25,379
|
<p>Writing something like this using the <a href="http://loki-lib.sourceforge.net/" rel="nofollow noreferrer">loki library</a>,</p>
<pre><code>typedef Functor<void> BitButtonPushHandler;
</code></pre>
<p>throws a compiler error, but this works</p>
<pre><code>typedef Functor<void,TYPELIST_1(Matrix3D*)> Perspective;
</code></pre>
<blockquote>
<p>Functor.h:530: error: '((Loki::FunctorHandler, int>*)this)->Loki::FunctorHandler, int>::f_' cannot be used as a function
Functor.h:530: error: return-statement with a value, in function returning 'void'</p>
</blockquote>
<p>Anyone familiar with this library know how to get the first line working?</p>
|
<p>Looking at the source code, the Functor template definition is as follows:</p>
<pre><code>template <typename R = void, class TList = NullType,
template<class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL>
class Functor{...};
</code></pre>
<p>As commented below, there are no template typedefs allowed, so all types (or accept all defaults) need to be specified.</p>
<p>You can just define as follows and let the defaults do the work:</p>
<pre><code>typedef Functor<> BitButtonPushHandler;
</code></pre>
<p>This compiles for me with a small test Functor class (not the actual Loki one), and I can use the typedef successfully.</p>
|
<p>What I originally wrote worked... it was late, and I forgot about... </p>
<pre><code>using namespace Loki;
</code></pre>
<p>...so sorry</p>
| 32,068
|
<p>I have a Visual Studio Setup Project that I use to install a fairly simple WinForms application. At the end of the install I have a custom user interface page that shows a single check box which asks the user if they want to run the application. I've seen other installers do this quite often. But I cannot find a way to get the Setup Project to run an executable after the install finishes. An ideas?</p>
<p>NOTE: You cannot use Custom Actions because these are used as part of the install process, I want to run my installed application once the user presses the 'Close' button at the end of the install.</p>
|
<p>I believe this is one of the real limitations of the Visual Studio installation project. You need to be able to modify the last page of the installation UI but VS.NET does not give you a way to do this. You could modify the tables in the .MSI after it has been built but VS.NET would probably overwrite these changes each time it is built. You may be able to override the last page using a merge module that you include in the installation project. Either way you will need to become familiar with how the UI dialogs are authored in an .MSI and this is not trivial.</p>
<p>You may want to consider switching to a free script based installer or buy a commercial setup authoring application (just don't buy InstallShield for the love of Pete). Take a look at InstallAware (although I have not used it).</p>
|
<p>I managed it by doing invoking the Main method the assembly using the following line:</p>
<pre><code>(typeof(ClassWithinAssemblyToExecute)).Assembly.EntryPoint.Invoke(null, new Object[] {} )
</code></pre>
| 8,546
|
<p>I need to compare 2 strings as equal such as these:</p>
<blockquote>
<p>Lubeck == Lübeck</p>
</blockquote>
<p>In JavaScript.</p>
<p>Why? Well, I have an auto-completion field that's going out to a Java service using Lucene, where place names are stored naturally (as Lübeck), but also indexed as normalized text, </p>
<pre><code>import sun.text.Normalizer;
oDoc.setNameLC = Normalizer.normalize(oLocName, Normalizer.DECOMP, 0)
.toLowerCase().replaceAll("[^\\p{ASCII}]","");
</code></pre>
<p>This way some-one who doesn't know to type "Mèxico" can type "mexico" and get a match which returns "Mèxico" (among a lot of other possible hits, like "Café Mèxico, Dubai, UAE").</p>
<p>Now the thing is I don't have the ability to change the service to do any highlighting on the server side, therefore I am highlighting on the client JavaScript side with something like:</p>
<pre><code>return result.replace( input.replace(/[aeiou]/g,"."), "<b>$1</b>");
</code></pre>
<p>It's a little more fancy because I am escaping special regex characters in the input. This is fine for simple one word matches at the beginning of a hit, but it really breaks down if you suddenly wish to support multi-word matches like "london cafe":</p>
<pre><code>input = input.strip().toLowerCase(); //fyi prototype's strip is like trim
re = new RegEx(input.replace(/[aeiou]/g,".").replace(/\s+/g,"|"),"gi");
return result.replace(re, "<b>$1</b>");
</code></pre>
<p>This doesn't work for say "london ca" (was typing london cafe), because it would mark "Jack London Cabin, Dawson City, Canada" as: <code>"Ja<b>ck</b> <b>London</b> <b>ca</b>bin, Dawson <b>Ci</b>ty, <b>Ca<b/>nada"</code> [note the "ck" and "Ci" particularly]</p>
<p>Therefore I'm sort of looking for something that's not as crazy as:</p>
<pre><code>input = input.strip().toLowerCase();
input = input.replace(/a/g,"[ÀàÁáÂâÃãÄäÅ寿ĀāĂ㥹]");
input = input.replace(/e/g,"[ÈèÉéÊêËëĒēĔĕĖėĘęĚě]");
// ditto for i, o, u, y, c, n, maybe also d, g, h, j, k, l, r, s, t, w, z
re = new RegEx(input.replace(/\s+/g,"|"),"gi");
return result.replace(re, "<b>$1</b>");
</code></pre>
<p>Is there a compiled table I can refer to mapping a range of characters which are accented versions of an other character to that character, by which I don't mean the plain unicode chart. And if so, could I avoid using weird, possibly slow, RegEx statements?</p>
<p><em>About the bounty:</em><br>
Before I started a bounty there were two answers, the one pointing me to doing it in Ruby, and <a href="https://stackoverflow.com/questions/227950/programatic-accent-reduction-in-javascript-aka-text-normalization-or-unaccenting/228006#228006">the one</a> that <a href="https://stackoverflow.com/users/22364/mizardx">MizzardX</a> wrote which was a completion of the basic form I'd put in my question. Now don't get me wrong, I really appreciate working it out as completely as he did, but I just wished that there might be another way. It seems so far that everyone who's dropped by to look at the question and answer has decided that MizzardX covers it just fine, or that they have no different approach. I would be interested in a different approach, and if it simply isn't available before the bounty closes, MizzardX will win the bounty (though in a cruel twist, his edits mad it a community wiki answer, so I'm not sure if he'll get the bounty!)</p>
|
<pre><code>/**
* Creates a RegExp that matches the words in the search string.
* Case and accent insensitive.
*/
function make_pattern(search_string) {
// escape meta characters
search_string = search_string.replace(/([|()[{.+*?^$\\])/g,"\\$1");
// split into words
var words = search_string.split(/\s+/);
// sort by length
var length_comp = function (a,b) {
return b.length - a.length;
};
words.sort(length_comp);
// replace characters by their compositors
var accent_replacer = function(chr) {
return accented[chr.toUpperCase()] || chr;
}
for (var i = 0; i < words.length; i++) {
words[i] = words[i].replace(/\S/g,accent_replacer);
}
// join as alternatives
var regexp = words.join("|");
return new RegExp(regexp,'g');
}
var accented = {
'A': '[Aa\xaa\xc0-\xc5\xe0-\xe5\u0100-\u0105\u01cd\u01ce\u0200-\u0203\u0226\u0227\u1d2c\u1d43\u1e00\u1e01\u1e9a\u1ea0-\u1ea3\u2090\u2100\u2101\u213b\u249c\u24b6\u24d0\u3371-\u3374\u3380-\u3384\u3388\u3389\u33a9-\u33af\u33c2\u33ca\u33df\u33ff\uff21\uff41]',
'B': '[Bb\u1d2e\u1d47\u1e02-\u1e07\u212c\u249d\u24b7\u24d1\u3374\u3385-\u3387\u33c3\u33c8\u33d4\u33dd\uff22\uff42]',
'C': '[Cc\xc7\xe7\u0106-\u010d\u1d9c\u2100\u2102\u2103\u2105\u2106\u212d\u216d\u217d\u249e\u24b8\u24d2\u3376\u3388\u3389\u339d\u33a0\u33a4\u33c4-\u33c7\uff23\uff43]',
'D': '[Dd\u010e\u010f\u01c4-\u01c6\u01f1-\u01f3\u1d30\u1d48\u1e0a-\u1e13\u2145\u2146\u216e\u217e\u249f\u24b9\u24d3\u32cf\u3372\u3377-\u3379\u3397\u33ad-\u33af\u33c5\u33c8\uff24\uff44]',
'E': '[Ee\xc8-\xcb\xe8-\xeb\u0112-\u011b\u0204-\u0207\u0228\u0229\u1d31\u1d49\u1e18-\u1e1b\u1eb8-\u1ebd\u2091\u2121\u212f\u2130\u2147\u24a0\u24ba\u24d4\u3250\u32cd\u32ce\uff25\uff45]',
'F': '[Ff\u1da0\u1e1e\u1e1f\u2109\u2131\u213b\u24a1\u24bb\u24d5\u338a-\u338c\u3399\ufb00-\ufb04\uff26\uff46]',
'G': '[Gg\u011c-\u0123\u01e6\u01e7\u01f4\u01f5\u1d33\u1d4d\u1e20\u1e21\u210a\u24a2\u24bc\u24d6\u32cc\u32cd\u3387\u338d-\u338f\u3393\u33ac\u33c6\u33c9\u33d2\u33ff\uff27\uff47]',
'H': '[Hh\u0124\u0125\u021e\u021f\u02b0\u1d34\u1e22-\u1e2b\u1e96\u210b-\u210e\u24a3\u24bd\u24d7\u32cc\u3371\u3390-\u3394\u33ca\u33cb\u33d7\uff28\uff48]',
'I': '[Ii\xcc-\xcf\xec-\xef\u0128-\u0130\u0132\u0133\u01cf\u01d0\u0208-\u020b\u1d35\u1d62\u1e2c\u1e2d\u1ec8-\u1ecb\u2071\u2110\u2111\u2139\u2148\u2160-\u2163\u2165-\u2168\u216a\u216b\u2170-\u2173\u2175-\u2178\u217a\u217b\u24a4\u24be\u24d8\u337a\u33cc\u33d5\ufb01\ufb03\uff29\uff49]',
'J': '[Jj\u0132-\u0135\u01c7-\u01cc\u01f0\u02b2\u1d36\u2149\u24a5\u24bf\u24d9\u2c7c\uff2a\uff4a]',
'K': '[Kk\u0136\u0137\u01e8\u01e9\u1d37\u1d4f\u1e30-\u1e35\u212a\u24a6\u24c0\u24da\u3384\u3385\u3389\u338f\u3391\u3398\u339e\u33a2\u33a6\u33aa\u33b8\u33be\u33c0\u33c6\u33cd-\u33cf\uff2b\uff4b]',
'L': '[Ll\u0139-\u0140\u01c7-\u01c9\u02e1\u1d38\u1e36\u1e37\u1e3a-\u1e3d\u2112\u2113\u2121\u216c\u217c\u24a7\u24c1\u24db\u32cf\u3388\u3389\u33d0-\u33d3\u33d5\u33d6\u33ff\ufb02\ufb04\uff2c\uff4c]',
'M': '[Mm\u1d39\u1d50\u1e3e-\u1e43\u2120\u2122\u2133\u216f\u217f\u24a8\u24c2\u24dc\u3377-\u3379\u3383\u3386\u338e\u3392\u3396\u3399-\u33a8\u33ab\u33b3\u33b7\u33b9\u33bd\u33bf\u33c1\u33c2\u33ce\u33d0\u33d4-\u33d6\u33d8\u33d9\u33de\u33df\uff2d\uff4d]',
'N': '[Nn\xd1\xf1\u0143-\u0149\u01ca-\u01cc\u01f8\u01f9\u1d3a\u1e44-\u1e4b\u207f\u2115\u2116\u24a9\u24c3\u24dd\u3381\u338b\u339a\u33b1\u33b5\u33bb\u33cc\u33d1\uff2e\uff4e]',
'O': '[Oo\xba\xd2-\xd6\xf2-\xf6\u014c-\u0151\u01a0\u01a1\u01d1\u01d2\u01ea\u01eb\u020c-\u020f\u022e\u022f\u1d3c\u1d52\u1ecc-\u1ecf\u2092\u2105\u2116\u2134\u24aa\u24c4\u24de\u3375\u33c7\u33d2\u33d6\uff2f\uff4f]',
'P': '[Pp\u1d3e\u1d56\u1e54-\u1e57\u2119\u24ab\u24c5\u24df\u3250\u3371\u3376\u3380\u338a\u33a9-\u33ac\u33b0\u33b4\u33ba\u33cb\u33d7-\u33da\uff30\uff50]',
'Q': '[Qq\u211a\u24ac\u24c6\u24e0\u33c3\uff31\uff51]',
'R': '[Rr\u0154-\u0159\u0210-\u0213\u02b3\u1d3f\u1d63\u1e58-\u1e5b\u1e5e\u1e5f\u20a8\u211b-\u211d\u24ad\u24c7\u24e1\u32cd\u3374\u33ad-\u33af\u33da\u33db\uff32\uff52]',
'S': '[Ss\u015a-\u0161\u017f\u0218\u0219\u02e2\u1e60-\u1e63\u20a8\u2101\u2120\u24ae\u24c8\u24e2\u33a7\u33a8\u33ae-\u33b3\u33db\u33dc\ufb06\uff33\uff53]',
'T': '[Tt\u0162-\u0165\u021a\u021b\u1d40\u1d57\u1e6a-\u1e71\u1e97\u2121\u2122\u24af\u24c9\u24e3\u3250\u32cf\u3394\u33cf\ufb05\ufb06\uff34\uff54]',
'U': '[Uu\xd9-\xdc\xf9-\xfc\u0168-\u0173\u01af\u01b0\u01d3\u01d4\u0214-\u0217\u1d41\u1d58\u1d64\u1e72-\u1e77\u1ee4-\u1ee7\u2106\u24b0\u24ca\u24e4\u3373\u337a\uff35\uff55]',
'V': '[Vv\u1d5b\u1d65\u1e7c-\u1e7f\u2163-\u2167\u2173-\u2177\u24b1\u24cb\u24e5\u2c7d\u32ce\u3375\u33b4-\u33b9\u33dc\u33de\uff36\uff56]',
'W': '[Ww\u0174\u0175\u02b7\u1d42\u1e80-\u1e89\u1e98\u24b2\u24cc\u24e6\u33ba-\u33bf\u33dd\uff37\uff57]',
'X': '[Xx\u02e3\u1e8a-\u1e8d\u2093\u213b\u2168-\u216b\u2178-\u217b\u24b3\u24cd\u24e7\u33d3\uff38\uff58]',
'Y': '[Yy\xdd\xfd\xff\u0176-\u0178\u0232\u0233\u02b8\u1e8e\u1e8f\u1e99\u1ef2-\u1ef9\u24b4\u24ce\u24e8\u33c9\uff39\uff59]',
'Z': '[Zz\u0179-\u017e\u01f1-\u01f3\u1dbb\u1e90-\u1e95\u2124\u2128\u24b5\u24cf\u24e9\u3390-\u3394\uff3a\uff5a]'
};
</code></pre>
|
<p>A more complete version with case sensitive support, ligatures and whatnot.
Original source at: <a href="http://web.archive.org/web/20120918093154/http://lehelk.com/2011/05/06/script-to-remove-diacritics/" rel="noreferrer">http://lehelk.com/2011/05/06/script-to-remove-diacritics/</a></p>
<pre><code>var defaultDiacriticsRemovalMap = [
{'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
{'base':'AA','letters':/[\uA732]/g},
{'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
{'base':'AO','letters':/[\uA734]/g},
{'base':'AU','letters':/[\uA736]/g},
{'base':'AV','letters':/[\uA738\uA73A]/g},
{'base':'AY','letters':/[\uA73C]/g},
{'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
{'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
{'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
{'base':'DZ','letters':/[\u01F1\u01C4]/g},
{'base':'Dz','letters':/[\u01F2\u01C5]/g},
{'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
{'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
{'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
{'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
{'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
{'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
{'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
{'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
{'base':'LJ','letters':/[\u01C7]/g},
{'base':'Lj','letters':/[\u01C8]/g},
{'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
{'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
{'base':'NJ','letters':/[\u01CA]/g},
{'base':'Nj','letters':/[\u01CB]/g},
{'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
{'base':'OI','letters':/[\u01A2]/g},
{'base':'OO','letters':/[\uA74E]/g},
{'base':'OU','letters':/[\u0222]/g},
{'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
{'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
{'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
{'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
{'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
{'base':'TZ','letters':/[\uA728]/g},
{'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
{'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
{'base':'VY','letters':/[\uA760]/g},
{'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
{'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
{'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
{'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
{'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
{'base':'aa','letters':/[\uA733]/g},
{'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
{'base':'ao','letters':/[\uA735]/g},
{'base':'au','letters':/[\uA737]/g},
{'base':'av','letters':/[\uA739\uA73B]/g},
{'base':'ay','letters':/[\uA73D]/g},
{'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
{'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
{'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
{'base':'dz','letters':/[\u01F3\u01C6]/g},
{'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
{'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
{'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
{'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
{'base':'hv','letters':/[\u0195]/g},
{'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
{'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
{'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
{'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
{'base':'lj','letters':/[\u01C9]/g},
{'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
{'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
{'base':'nj','letters':/[\u01CC]/g},
{'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
{'base':'oi','letters':/[\u01A3]/g},
{'base':'ou','letters':/[\u0223]/g},
{'base':'oo','letters':/[\uA74F]/g},
{'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
{'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
{'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
{'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
{'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
{'base':'tz','letters':/[\uA729]/g},
{'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
{'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
{'base':'vy','letters':/[\uA761]/g},
{'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
{'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
{'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
{'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
];
var changes;
function removeDiacritics (str) {
if(!changes) {
changes = defaultDiacriticsRemovalMap;
}
for(var i=0; i<changes.length; i++) {
str = str.replace(changes[i].letters, changes[i].base);
}
return str;
}
</code></pre>
| 28,210
|
<p>I have a file upload form that is being posted back to a servlet (using multipart/form-data encoding). In the servlet, I am trying to use Apache Commons to handle the upload. However, I also have some other fields in the form that are just plain fields. How can I read those parameters from the request?</p>
<p>For example, in my servlet, I have code like this to read in the uplaoded file:</p>
<pre><code> // Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
Iterator /* FileItem */ items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
... do stuff ...
}
</code></pre>
|
<p>You could try something like this:</p>
<pre><code>while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
if (thisItem.isFormField()) {
if (thisItem.getFieldName().equals("somefieldname") {
String value = thisItem.getString();
// Do something with the value
}
}
}
</code></pre>
|
<p>Did you try request.getParam() yet?</p>
| 45,663
|
<p>We have concurrent edits happening on Word documents and I want to make sure that Subversion can handle merging .doc files. Do you know if Subversion handles merges of Word documents well?</p>
|
<p>Use <a href="http://tortoisesvn.tigris.org/" rel="noreferrer">TortoiseSVN</a> merge utility with the <a href="http://freemind.s57.xrea.com/xdocdiff/e/index.html" rel="noreferrer">xdocdiff</a> plugin to compare and merge Office documents</p>
|
<p>You might also consider using a non binary format like Html</p>
| 11,561
|
<p>I was wondering if there was somewhere I could get some starter kit / theme sample for ASP.NET.</p>
<p>I am not a designer, but I need to build a prototype for a project, and if I do it myself it'll certainly be awful</p>
<p>Do you know where I could find that (ASP.NET specific)?</p>
|
<p>Check <a href="http://asp.net" rel="nofollow noreferrer">http://asp.net</a>. There are quite a few starter kits and sample projects there. (<a href="http://www.asp.net/community/projects/" rel="nofollow noreferrer">http://www.asp.net/community/projects/</a>)</p>
|
<p>I advice to check ASP.NET Iteration Zero: <a href="http://aspnetzero.com/" rel="nofollow">http://aspnetzero.com/</a></p>
<p>It's a professional starter kit based on a strong framework and UI. It includes role and membership management and much more. You can create a demo to see it in action easily.</p>
| 16,874
|
<p>If I want to provide OpenID as the only registration method available AND want to do something meaningful with the nick name, how can I handle 2 users with the same Jon Smith nickname?</p>
<p>Actually, when I looked at StackOverflow's URL schema I was surprised that the internal user ID was being used in the URL. For example:</p>
<p><a href="https://stackoverflow.com/users/5908/z225rate">https://stackoverflow.com/users/5908/z225rate</a></p>
<p>Now I realize it's probably to avoid this problem. </p>
<p>But this also opens a tricky scenario. What if users wants to impersonate someone else? They just need to create a fake OpenID account, copy the nick and there you go. Sure you can tell who's who looking at the OpenID url, but it's quite likely going to cause confusion among non-experienced users.</p>
<p>I was thinking about checking the nick during registration and forcing the user to pick up another one in case it was already in use. But then you have to keep the new nick and use it instead of the one set up in OpenID. Not nice.</p>
<p>Any ideas? "Don't use OpenID" is not a (valid) idea : ) I mean, it might well be that I end up not using it, but want to know how far would I have to go to make it work "properly".</p>
<p>Thanks!</p>
|
<p>You can use the nick from Open ID and default the nick choice in your system to that, but do not allow duplicates in your system, so they will be forced to choose a different nick for your system.</p>
<p>You could still store their Open ID nick and use it, so if you want them to be able to display their preferred nick from OpenID at all costs, for any dupe users, you could force display as "OpenID Nick (your unique nick)".</p>
<p>So you might have Mike (mike1), Mike (mike2), etc. for any user that prefers a nick that a lot of users want. I would think that this would discourage any users from picking a non-unique nick, since they won't want it displayed that way.</p>
|
<p>There isn't such a thing as a fake OpenID, basically OpenID is mapping a URL space to a user, with a bit of hand off rules on how to pass data around. </p>
<p>Since there isn't a standard on how to form a URL for OpenID it would be a bit ugly to just slap up their full OpenID URL next to their name. Which you've already noted.</p>
<p>Your own internal data should always be considered more valid then the OpenID fields passed by the User. Have the user select another name if a name is already claimed by another OpenID.</p>
| 38,027
|
<p>I've been playing with ADO.NET Entity Framework lately, and I find that it suits my needs for a project I'm developing. I also find cool its non-invasive nature.</p>
<p>After generating a data model from an existing database you are faced with the task of integrating the generated model and your business logic. More specifically, I'm used to integration-test my classes that interact with the data store via mocks/stubs of the DAL interfaces. The problem is that you cannot do this using the ADO.NET Entity Framework because the entities it generates are simple classes with no interface.</p>
<p>The question is: how do I apply a <strong>TDD approach</strong> to the development of an application that uses ADO.NET Entity Framework? Is this even possible or should I migrate to another DAL-generation toolset?</p>
|
<p>One of the big critiques against the Entity Framework has been that it is inherently hard to test, for example in the ALT.Net <a href="http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/" rel="nofollow noreferrer">Vote of No Confidence</a> that gef quoted.</p>
<p><a href="http://blogs.msdn.com/diego/archive/2008/03/03/unit-testing-your-entity-framework-domain-classes.aspx" rel="nofollow noreferrer">Here is a blog post</a> discussing how to get around this, and be able to test your code without hitting the database, when using Entity Framework.</p>
<p>If testability is a big concern, you might want to look at another ORM framework, such as NHibernate, at least until Entity Framework 2.0 is released.</p>
|
<p>This answer has changed to "Yes, you can".</p>
<p>You can generate POCO and interfaces using customized T4 templates such as <a href="https://entityinterfacegenerator.codeplex.com/" rel="nofollow">https://entityinterfacegenerator.codeplex.com/</a>, then create mocking objects to test EF in and out without hitting the database. </p>
| 40,923
|
<p>In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put <code>this</code> in the window's user data area via <code>SetWindowLong(hwnd, GWL_USERDATA, this)</code>, which allows us to have an MFC-like callback or a tightly integrated <code>WndProc</code>, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx" rel="noreferrer">SetWindowLongPtr</a> was created to replace <a href="http://msdn.microsoft.com/en-us/library/ms633591%28VS.85%29.aspx" rel="noreferrer">SetWindowLong</a> in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.</p>
<pre><code>LONG_PTR SetWindowLongPtr(
HWND hWnd,
int nIndex,
LONG_PTR dwNewLong
);
</code></pre>
<p>Remember that the constants have changed too, so usage now looks like:</p>
<pre><code>SetWindowLongPtr(hWnd, GWLP_USERDATA, this);
</code></pre>
<p>Also don't forget that now to retrieve the pointer, you must use <a href="http://msdn.microsoft.com/en-us/library/ms633585%28VS.85%29.aspx" rel="noreferrer">GetWindowLongPtr</a>:</p>
<pre><code>LONG_PTR GetWindowLongPtr(
HWND hWnd,
int nIndex
);
</code></pre>
<p>And usage would look like (again, with changed constants):</p>
<pre><code>LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
MyObject* pMyObject = (MyObject*)lpUserData;
</code></pre>
|
<p>The other alternative is SetProp/RemoveProp (When you are subclassing a window that already uses GWLP_USERDATA)</p>
<p>Another good alternative is ATL style thunking of the WNDPROC, for more info on that, see</p>
<ul>
<li><a href="http://www.ragestorm.net/blogs/?cat=20" rel="noreferrer">http://www.ragestorm.net/blogs/?cat=20</a></li>
<li><a href="http://www.hackcraft.net/cpp/windowsThunk/" rel="noreferrer">http://www.hackcraft.net/cpp/windowsThunk/</a></li>
</ul>
| 4,307
|
<p>I have a stored procedure that looks like:</p>
<pre><code>CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
</code></pre>
<p>Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.</p>
|
<pre><code>CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND (@AdditionalFilter = 0 OR
T.Column2 IS NOT NULL)
</code></pre>
<p>If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between brackets. If it's anything other than 0, the column condition will be evaluated.</p>
|
<pre><code>select *
from SomeTable t
where t.Column1 is null
and (@AdditionalFilter = 0 or t.Column2 is not null)
</code></pre>
| 18,406
|
<p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p>
<p>These obvious ideas don't work:</p>
<pre><code>>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
</code></pre>
<p>In the end I have written functions like this:</p>
<pre><code>def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
</code></pre>
<p>I can't help thinking that I'm missing an easier way to do this though.</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li>
</ul>
|
<p>You can use full <code>datetime</code> variables with <code>timedelta</code>, and by providing a dummy date then using <code>time</code> to just get the time value.</p>
<p>For example:</p>
<pre><code>import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
</code></pre>
<p>results in the two values, three seconds apart:</p>
<pre><code>11:34:59
11:35:02
</code></pre>
<p>You could also opt for the more readable</p>
<pre><code>b = a + datetime.timedelta(seconds=3)
</code></pre>
<p>if you're so inclined.</p>
<hr>
<p>If you're after a function that can do this, you can look into using <code>addSecs</code> below:</p>
<pre><code>import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
</code></pre>
<p>This outputs:</p>
<pre><code> 09:11:55.775695
09:16:55
</code></pre>
|
<p>Try adding a <code>datetime.datetime</code> to a <code>datetime.timedelta</code>. If you only want the time portion, you can call the <code>time()</code> method on the resultant <code>datetime.datetime</code> object to get it.</p>
| 12,542
|
<p>I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?</p>
|
<p>Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.</p>
<p>Abstract? Hell yes. Class? No.</p>
<p>Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes.</p>
<p>Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.</p>
|
<p>An interface contains prototype of methods (i.e Declaration ) not defination but Abstract class can contain defination of method & atleast one Abstract method (method with only prototype) </p>
| 32,240
|
<p>In your practice, how do you effectively track and manage technical debt? </p>
<p>Is there a specific metric, like <a href="http://jamesshore.com/Blog/An-Approximate-Measure-of-Technical-Debt.html" rel="nofollow noreferrer">SLOC</a>, that you use?</p>
<p>How do you visually display your results to stakeholders and management? </p>
<p>What benefits have you seen in the process?</p>
|
<p>We write story cards for technical debt. They are BLACK, with big yellow warning signs on them. Get too many on the wall, and it's REAL obvious.</p>
<p>Anyone who walks past can see them :)</p>
|
<p>There is a <a href="http://www.sonarsource.org/evaluate-your-technical-debt-with-sonar/" rel="nofollow">plug-in for Sonar</a> that translates technical debt into $.</p>
<p>I haven't used it myself yet, but it looks promising.</p>
| 39,311
|
<p>If you have something like:</p>
<pre><code>val myStuff = Array(Person("joe",40), Person("mary", 35))
</code></pre>
<p>How do you create an XML value with that data as nodes? I know how to use { braces } in an XML expression to put a value, but this is a collection of values. Do I need to iterate explicitly or is there something better?</p>
<pre><code>val myXml = <people>{ /* what here?! */ }</people>
</code></pre>
<p>The resulting value should be something like:</p>
<pre><code><people><person><name>joe</name><age>40</age></person>
<person><name>mary</name><age>39</age></person></people>
</code></pre>
|
<p>As it's a functional programming language Array.map is probably what you're looking for:</p>
<pre><code>class Person(name : String, age : Int){
def toXml() = <person><name>{ name }</name><age>{ age }</age></person>
}
object xml {
val people = List(
new Person("Alice", 16),
new Person("Bob", 64)
)
val data = <people>{ people.map(p => p.toXml()) }</people>
def main(args : Array[String]){
println(data)
}
}
</code></pre>
<p>Results in:</p>
<pre><code><people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>
</code></pre>
<p>A formatted result (for a better read):</p>
<pre><code><people>
<person>
<name>Alice</name>
<age>16</age>
</person>
<person>
<name>Bob</name>
<age>64</age>
</person>
</people>
</code></pre>
|
<p>Actually, the line yield person.toXml() does not compile for me, but yield person.toXml (without the parentheses) does. The original version complains of 'overloaded method value apply' even if I change the def of 'ToXml' to explicitly return a scala.xml.Elem</p>
| 26,526
|
<p>I've been looking into different web statistics programs for my site, and one promising one is <a href="http://www.hping.org/visitors/" rel="nofollow noreferrer">Visitors</a>. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's <a href="http://us.php.net/manual/en/function.shell-exec.php" rel="nofollow noreferrer">shell_exec</a>, but my web host (<a href="https://www.nearlyfreespeech.net/" rel="nofollow noreferrer">NFSN</a>) has PHP's <a href="http://us2.php.net/features.safe-mode" rel="nofollow noreferrer">safe mode</a> on and it's giving me an error message.</p>
<p>Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)</p>
|
<p>Visitors looks like a log analyzer and report generator. Its probably best setup as a chron job to create static HTML pages once a day or so.</p>
<p>If you don't have shell access to your hosting account, or some sort of control panel that lets you setup up chron jobs, you'll be out of luck.</p>
|
<p>Is there any reason not to just use <a href="http://www.google.com/analytics/" rel="nofollow noreferrer">Google Analytics</a>? It's free, and you don't have to write it yourself. I use it, and it gives you a lot of information.</p>
<p>Sorry, I know it's not a "programming" answer ;)</p>
| 7,100
|
<p>I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc.
I'm looking for something like <code>File.CanCreate(@"C:\myfolder\myfile.aaa"</code>), but haven't found such a method.
The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance.
Do you know a better solution?</p>
|
<p>In reality, creating a dummy file isn't going to have a huge performance impact in most applications. Of course, if you have advanced permissions with create but not destroy it might get a bit hairy...</p>
<p>Guids are always handy for random names (to avoid conflicts) - something like:</p>
<pre><code>string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");
// perhaps check File.Exists(file), but it would be a long-shot...
bool canCreate;
try
{
using (File.Create(file)) { }
File.Delete(file);
canCreate = true;
}
catch
{
canCreate = false;
}
</code></pre>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/930b76w0.aspx" rel="nofollow noreferrer">CAS</a> to verify that there are no <strong>.NET policies (caspol)</strong> restricting the creating and writing of a file on that location.</p>
<p>But this will not cover the windows policies. You'll have to manually check the NTFS policies. And even then there are processes that can decide you're not allowed to create a file (for instance a virus scanner).</p>
<p>The best and most complete way is to try it.</p>
| 40,926
|
<p>I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on).
I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.</p>
<p>How can I check that I'll not delete data that should not be deleted?</p>
<p>I have a test database - just a copy of real one where I can do what I want :)</p>
<p>The only idea I have is dump database before and after and check it. But it not looks comfortable.
Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?</p>
<p>Any other ideas how to solve the problem?</p>
|
<p>You can query the information_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always. </p>
<p>Something like (for constraints)</p>
<pre><code>select table_catalog,table_schema,table_name,column_name,rc.* from
information_schema.constraint_column_usage ccu,
information_schema.referential_constraints rc
where ccu.constraint_name = rc.constraint_name
</code></pre>
|
<p>If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, then use queries to find any keys that now point to invalid targets. (while you're doing this you can also make sure the part that should be unaffected did not change)</p>
<p>A better solution would be to spend time mapping out the delete cascades so you know what to expect - knowing how your database works is pretty valuable so the effort spent on this will be useful beyond this particular deletion.</p>
<p>And no matter how sure you are back the DB up before doing big changes!</p>
| 16,014
|
<p>A feature in Eclipse that I really miss is how you can auto-complete method parameters with currently in-scope variables. This feature will, with a single key combo (<kbd>ctrl</kbd>+<kbd>space</kbd>) fill in all method parameters. As long as my variables were named similarly to the method parameters, I never had a problem with this auto-complete. Is there a plugin or a native way to accomplish this in Intellij?</p>
|
<p><a href="http://blogs.jetbrains.com/idea/2009/09/super-method-completion/" rel="noreferrer">IntelliJ IDEA 9 now supports</a> what they call "super completion" which matches the behavior you are looking for and is available through their early access program.</p>
<p><a href="https://i.stack.imgur.com/V0vwl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V0vwl.png" alt="alt text"></a><br>
<sub>(source: <a href="https://blogs.jetbrains.com/idea/wp-content/uploads/2009/09/super.png" rel="noreferrer">jetbrains.com</a>)</sub> </p>
<p>IntelliJ IDEA 8 does not allow you to autocomplete more than one parameter at a time. You are forced to use <kbd>Control</kbd>-<kbd>Shift</kbd>-<kbd>Space</kbd> once for each parameter.</p>
|
<p>from this post: <a href="https://stackoverflow.com/a/55160515/405749">https://stackoverflow.com/a/55160515/405749</a>:</p>
<p>The plugin <a href="https://plugins.jetbrains.com/plugin/8638-auto-filling-java-call-arguments" rel="nofollow noreferrer">https://plugins.jetbrains.com/plugin/8638-auto-filling-java-call-arguments</a> at least will provide a smart fix to do it when pressing alt+enter.</p>
<p>I have not found a away to do this completely automatically as it works in eclipse.</p>
| 11,914
|
<p>I'm working on a project that's been accepted as a proof of concept and is now on the schedule as an actual production project. I'm curious how others approach this transition.</p>
<p>I've heard from various sources that when a project starts as a proof of concept it's often a good idea to trash all of the code written during that rapidly-evolving phase and essentially to start over with a clean slate, relying on what you learned from the conceptual phase but without working to clean up the potentially messy code that you wrote the first time around. Kind of the programming version of "throw away the first copy of that angry email you're about to send and start all over" theory.</p>
<p>I've done it this was in the past and I've also refactored the conceptual code to use in production, but since I'm in the transition phase for a new project I wanted to get an idea how others do this. Obviously a lot depends on the project itself, and on the conceptual code (if what you generated works but won't scale for example, it's probably best to start afresh, but if you have a very compressed timeline for the project you might be forced to build on what you've already written). </p>
<p>That said, if all things were equal what would you all choose as an approach?</p>
|
<p>As you already kind of hinted at, the answer is, "It Depends"</p>
<p>Starting over is good because you can help trim out the stuff that was added while you were initially working out the kinks but isn't really needed.</p>
<p>It also gives you a chance to give more consideration to how you want the architecture to be -- without already being dependent on how the proof-of-concept was written...</p>
<p>In practice, though, unless you're in the business of selling the software to the outside world, building upon the prototype is pretty commonplace. Just don't get into the habit of thinking "I'll fix it later" if you run into some code that smells or seems like it could be done in a better way...</p>
|
<p>If the code works, use it. Spend a little bit of time refactoring the messiest parts in order to ease future maintenance. But don't fall into the trap of building a new system from scratch.</p>
| 12,864
|
<p>I am using ANTLRWorks to create ANTLR grammars. I have a valid grammar and the parser and lexer source files are generated as well. I have also tried debugging the generated code and the output is as expected in the debugger output. </p>
<p>But when I try to invoke the __Test__ class generated by the debugger nothing is coming up in the console. I have properly set up the classpath as I can successfully compile the __Test__.java with the same classpath. </p>
<p>What would be the problem? Is there any clear tutorial for writing and compiling a sample parser with antlr and antlrworks?</p>
|
<p>You could as easily have asked about implementing a first-class backend getting the server side right, while avoiding the latest trendy client-side fad. And I think it would be a legitimate goal in either case. You don't mention whether this is an existing application, but if it is, then I'd say, first memeorize the Fowler Refactoring book, and then go for it.</p>
<p>A lot of the churn in software is useful if you know how to properly apply what you'll need to know to accomplish your client side goals, because the same concepts (SOC, coupling-vs-cohesion, DRY, YAGNI, etc.) apply to both ends, and we increasingly have at hand useful tools for applying them (which can be accomplished more or less easily with a lot of technologies.)</p>
|
<p>Or don't even bother with the REST / Json part and use something like DWR to talk directly from your client side code to your server POJOs.</p>
| 39,792
|
<p>As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul?</p>
<p>ie (the only dump I have on hand with me actually)</p>
<pre>>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94
b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255
b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0
b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000</pre>
<p>I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[</p>
|
<p>First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type:</p>
<pre><code>SRV*c:\symbols*http://msdl.microsoft.com/download/symbols
</code></pre>
<p>You can find more information on how to correctly configure the symbols <a href="http://www.microsoft.com/whdc/devtools/debugging/debugstart.mspx#a" rel="noreferrer">here</a>.</p>
<p>Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. </p>
<p>Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type:</p>
<pre><code>kpn 200
</code></pre>
<p>This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you'll get something like:</p>
<pre><code>01 MODULE!CLASS.FUNCTIONNAME1(...)
02 MODULE!CLASS.FUNCTIONNAME2(...)
03 MODULE!CLASS.FUNCTIONNAME3(...)
04 MODULE!CLASS.FUNCTIONNAME4(...)
</code></pre>
<p>Where:</p>
<ul>
<li><strong>THE FIRST NUMBER</strong>: Indicates the frame number</li>
<li><strong>MODULE</strong>: The DLL that contains the code</li>
<li><strong>CLASS</strong>: (Only on C++ code) will show you the class that contains the code</li>
<li><strong>FUNCTIONAME</strong>: The method that was called. If you have the correct symbols you will also see the parameters.</li>
</ul>
<p>You might also see something like</p>
<pre><code>01 MODULE!+989823
</code></pre>
<p>This indicates that you don't have the proper Symbol for this DLL and therefore you are only able to see the method offset.</p>
<p>So, what is a callstack? </p>
<p>Imagine you have this code:</p>
<pre><code>void main()
{
method1();
}
void method1()
{
method2();
}
int method2()
{
return 20/0;
}
</code></pre>
<p>In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack:</p>
<pre><code>01 MYDLL!method2()
02 MYDLL!method1()
03 MYDLL!main()
</code></pre>
<p>You can follow from this callstack that "main" called "method1" that then called "method2" and it failed.</p>
<p>In your case you've got this callstack (which I guess is the result of running "kb" command)</p>
<pre><code>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94
b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255
b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0
b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000
</code></pre>
<p>The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4_disp) and the offset of the method that is being executed (+0x48b94). Since you don't have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can't get much information from here.</p>
<p>I recommend you run "kpn 200". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you).</p>
<p>At least you know it's related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version.</p>
<p>In case you want to learn more about WinDBG debugging I recommend the following links:</p>
<ul>
<li><a href="http://blogs.msdn.com/tess/default.aspx" rel="noreferrer">If broken it is, fix it you should</a></li>
<li><a href="http://www.microsoft.com/events/EventDetails.aspx?CMTYSvcSource=MSCOMMedia&Params=~CMTYDataSvcParams%5E~arg+Name%3D%22ID%22+Value%3D%221032298076%22%2F%5E~arg+Name%3D%22ProviderID%22+Value%3D%22A6B43178-497C-4225-BA42-DF595171F04C%22%2F%5E~arg+Name%3D%22lang%22+Value%3D%22en%22%2F%5E~arg+Name%3D%22cr%22+Value%3D%22US%22%2F%5E~sParams%5E~%2FsParams%5E~%2FCMTYDataSvcParams%5E" rel="noreferrer">TechNet Webcast: Windows Hang and Crash Dump Analysis</a> </li>
<li><a href="http://delicious.com/popular/windbg" rel="noreferrer">Delicious.com popular links on WinDBG</a></li>
</ul>
|
<p>It might help to include an example of the stack you are trying to read. A good tip is to ensure you have correct debug symbols for all modules shown in the stack. This includes symbols for modules in the OS, Microsoft has made their symbol server publicly available.</p>
| 10,330
|
<p>When you create a Microsoft Access 2003 link to an Oracle table using Oracle's ODBC driver, you are sometimes asked to state which columns are the primary key(s).</p>
<p>I would like to know how to change that initial assignment, or even how to get Access/ODBC to forget the assignment. In my limited testing I wonder if the assignment isn't cached by the ODBC driver itself.</p>
<p>The columns I initial chose are not correct.</p>
<p>Update: I never did get a full answer on this one, deleting the links then restoring them didn't work. I think it's an obscure bug. I've moved on and haven't had to worry about this oddity since.</p>
|
<p>You must delete the link to the table and create a new one. When a table is linked all the connection info about the table's path, structure (including primary key), permissions, passwords and statistics are stored in the Access db. If any of those items change in the linked table, refreshing links won't automatically update it on the Access side because Access continues to use the previously stored info. You must delete or drop the linked table and recreate the link, storing the current connection information.</p>
<p>Don't know for sure if this next bit also applies to odbc linked tables, but I suspect it does. For Jet tables, it's a good idea to periodically delete all links and recreate them to improve query performance, because if a linked table's statistics are made on a table with few records, once that table is filled with many more records, new statistics will tell Jet's optimizer whether using indexes or a full table scan would be the better course of action when running a query.</p>
|
<p>It is not possible to delete the link and then relink?</p>
| 11,348
|
<p>At the moment we use <a href="http://www.hsqldb.org/" rel="noreferrer">HSQLDB</a> as an embedded database, but we search for a database with less memory footprint as the data volume grows.</p>
<p><a href="http://developers.sun.com/javadb/" rel="noreferrer">Derby / JavaDB</a> is not an option at the moment because it stores properties globally in the system properties. So we thought of <a href="http://www.h2database.com/html/main.html" rel="noreferrer">h2</a>.</p>
<p>While we used HSQLDB we created a Server-object, set the parameters and started it. This is described <a href="http://hsqldb.org/doc/guide/ch04.html#N10BBC" rel="noreferrer">here</a> (and given as example in the class org.hsqldb.test.TestBase).</p>
<p>The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.</p>
|
<p>From the download, I see that the file tutorial.html has this </p>
<pre><code>import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
</code></pre>
|
<p>If for some reason you need an embedded H2 database in server mode you can do it either manually using the API
at <a href="http://www.h2database.com/javadoc/org/h2/tools/Server.html" rel="noreferrer">http://www.h2database.com/javadoc/org/h2/tools/Server.html</a> - or by
appending ;AUTO_SERVER=TRUE to the database URL.</p>
| 18,695
|
<p>I am using ActiveScaffold in a Ruby on Rails app, and to save space in the table I have replaced the default "actions" text in the table (ie. "edit", "delete", "show") with icons using CSS. I have also added a couple of custom actions with action_link.add ("move" and "copy").</p>
<p>For clarity, <strong>I would like to have a tooltip pop up with the related action</strong> (ie. "edit", "copy") when I hover the mouse over the icon.</p>
<p>I thought I could do this by adding a simple "alt" definition to the tag, but that doesn't appear to work.</p>
<p>Can somebody point me in the right direction?</p>
|
<p>The <code>alt</code> attribute is to be used as an alternative to the image, in the case of the image missing, or in a text only browser.</p>
<p>IE got it wrong, when they made <code>alt</code> appear as a tooltip. It was never meant to be that.</p>
<p>The correct attribute for this is <code>title</code>, which of course doesn't do a tooltip in IE.</p>
<p>So, to do have a tooltip show up in both IE, and FireFox/Safari/Chrome/Opera, use both an <code>alt</code> attribute and a <code>title</code> attribute.</p>
|
<p>As Prestaul pointed out, the alt tag should work for images and title for links. However, this is also browser dependent...most browsers <strong>should</strong> implement functionality that displays this metadata as tooltips but they aren't required to do so.</p>
| 8,378
|
<p>I need any tool or IDE environment to debug and test the vb scripts code. Please suggest any free ones. My vb scripts are standalone (vbs extenstion).</p>
|
<p>Sadly not free....<a href="http://support.microsoft.com/kb/308364" rel="nofollow noreferrer">How to debug Windows Script Host, VBScript, and JScript files</a></p>
|
<p>I think you'll have a hard time finding a free tool that supports real VBS debugging. But I've used this "poor man's technique" in the past. Create a variable at the beginning of your script</p>
<p>blnDebug=False</p>
<p>Then throughout your script add lines to echo what the script is doing or the value of different variables:</p>
<p>if blnDebug Then wscript.echo "Now starting script strFoo=" & strFoo</p>
<p>When you set blnDebug=True then all your debug messages will be written to the console (I always use CScript when running this). By adding these debug messages as you write your script, you can have debugging available simply by changing the bldDebug value.</p>
<p>Certainly commercial editors like PrimalScript include a debugger. SAPIEN also has a standalone debugger, <a href="http://www.primalscope.com/" rel="nofollow noreferrer">http://www.primalscope.com/</a>, that while not free is a relatively inexpensive option. You can download an eval copy to try it out.</p>
| 21,837
|
<p>I need help to replace all \n (new line) caracters for <br /> in a String, but not those \n inside [code][/code] tags.
My brain is burning, I can't solve this by my own :(</p>
<p>Example:</p>
<pre><code>test test test
test test test
test
test
[code]some
test
code
[/code]
more text
</code></pre>
<p>Should be:</p>
<pre><code>test test test<br />
test test test<br />
test<br />
test<br />
<br />
[code]some
test
code
[/code]<br />
<br />
more text<br />
</code></pre>
<p>Thanks for your time.
Best regards.</p>
|
<p>I would suggest a (simple) parser, and not a regular expression. Something like this (bad pseudocode):</p>
<pre><code>stack elementStack;
foreach(char in string) {
if(string-from-char == "[code]") {
elementStack.push("code");
string-from-char = "";
}
if(string-from-char == "[/code]") {
elementStack.popTo("code");
string-from-char = "";
}
if(char == "\n" && !elementStack.contains("code")) {
char = "<br/>\n";
}
}
</code></pre>
|
<p>To get it right, you really need to make three passes:</p>
<ol>
<li>Find [code] blocks and replace them with a unique token + index (saving the original block), e.g., "foo [code]abc[/code] bar[code]efg[/code]" becomes "foo TOKEN-1 barTOKEN-2"</li>
<li>Do your newline replacement.</li>
<li>Scan for escape tokens and restore the original block.</li>
</ol>
<p>The code looks something* like:</p>
<pre><code>Matcher m = escapePattern.matcher(input);
while(m.find()) {
String key = nextKey();
escaped.put(key,m.group());
m.appendReplacement(output1,"TOKEN-"+key);
}
m.appendTail(output1);
Matcher m2 = newlinePatten.matcher(output1);
while(m2.find()) {
m.appendReplacement(output2,newlineReplacement);
}
m2.appendTail(output2);
Matcher m3 = Pattern.compile("TOKEN-(\\d+)").matcher(output2);
while(m3.find()) {
m.appendReplacement(finalOutput,escaped.get(m3.group(1)));
}
m.appendTail(finalOutput);
</code></pre>
<p>That's the quick and dirty way. There are more efficient ways (others have mentioned parser/lexers), but unless you're processing millions of lines and your code is CPU bound (rather than I/O bound, like most webapps) and you've confirmed with a profiler that this is the bottleneck, they probably aren't worth it.</p>
<p>* I haven't run it, this is all from memory. Just check the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html" rel="nofollow noreferrer">API</a> and you'll be able to work it out.</p>
| 42,552
|
<p>We work extensively in the .Net Compact Framework and Windows Mobile. I've seen plenty of questions come up regarding specifics to development of ASP.Net apps or other .Net based desktop apps but nothing CF specific.</p>
<p>Anyone else a mobile developer out there that can share some things to start doing, stop doing, and avoid doing when developing in the Compact Framework?</p>
|
<p>Sure:</p>
<ul>
<li>Use a physical device whenever possible (not the emulator)</li>
<li>Test with multiple devices (different vendors, different models)</li>
<li>Concentrate testing around sleep/wakeup behaviors</li>
<li>When using MSTEST unit tests, never use private accessors</li>
<li>Avoid ActiveSync like the plague - debug using CoreCon direct</li>
<li>Get familiar with RPM and start using it early</li>
<li>Reuse objects when possible</li>
<li>Avoid doing a lot of work in a Form's ctor - off load it for lazy load or in a background thread</li>
<li>Load Forms on demand when possible (not all of them at once)</li>
<li>Cache the frequently used Forms, create infrequent ones on demand</li>
<li>Keep image resolutions low</li>
<li>If a class exposes Dispose <em>use it</em>. Always.</li>
<li>No app is too small to benefit from MVC/MVP patterns</li>
<li>Don't use the Microsoft CAB/SCSF port for the CF (the people who ported it obviously never actually used a resource-limited device)</li>
<li>Get familiar with the concept of "occasionally connected" if you will be doing any remote data/service activity</li>
<li>Docking and Anchoring are your friend and your enemy - test run-time screen rotations and multiple resolutions (even if you think you won't target them, because you're probably wrong in that thinking)</li>
<li>Look at, but don't heavily invest in the device deployment package project type. It has major limitations that will likely bite you. A batch file works surprisingly well or a custom MSBUILD task to call CabWiz</li>
<li>Brush up on your C++ and P/Invoke skills. You <strong>will</strong> need them. It's almost impossible to write a useful CF app without P/Invoking something.</li>
<li>Code to the lowest common denominator for targets.</li>
<li>Partial classes are your friend, especially for dividing logic between target types (PPC, Phone, non-mobile CE).</li>
<li>Avoid running an app from persistent storage, especially for CE and pre-WInMo 5. Copy to RAM and run from there to prevent demand-paging from killing you, especially after a sleep/wake cycle.</li>
<li>Apps should not care about sleep/wake transitions, but that's pure theory. Sleep wake **will* change your app behavior, so again test, test, test.</li>
<li>Did I mention test? Especially on every device you can get your hands on? Buy cheap hardware off of eBay for your test lab. Having more devices is more important than having the latest unless you intend to use a specific feature of a newer device.</li>
<li>Ask for divine intervention if you plan to use bluetooth programmatically. Get familiar with the Widcomm and Microsoft stacks and understand that they aren't the same.</li>
<li>Watch the MSDN webcast on memory management in the Compact Framework. Watch it again for the stuff you missed the first time.</li>
<li>Watch out for sleep/wake invalidating internal handles and causing access violations. This is more esoteric but certainly happens. For example, if you're running an application off of a storage card, the entire app isn't loaded into RAM. Pieces in use are demand-paged in for execution. This is all well and good. Now if you power the device off, the drivers all shut down. When you power back up, many devices simply re-mount the storage devices. When your app needs to demand-page in more program, it's no longer where it was and it dies. Similar behavior can happen with databases on mounted stores. If you have an open handle to the database, after a sleep/wake cycle the connection handle may no longer be valid.</li>
<li>Install the <a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7e286847-6e06-4a0c-8cac-ca7d4c09cb56" rel="noreferrer">evaluation version of Platform Builder</a>. The source code for a whole lot of things is in there (like the network UI, many drivers, etc) and when your P/Invoke code isn't doing what you expect you'll at least have a place to go look for the "why".</li>
</ul>
<p><strong>added 5/25/10</strong></p>
<ul>
<li><a href="http://blog.opennetcf.com/ctacke/2010/05/18/WhyWindowsMobileSucksACaseStudy.aspx" rel="noreferrer">Don't expect the power management APIs under WinMo to work consistenly or properly</a> (or even at all) across devices. In fact even with the same hardware it might change from OS build to OS build.</li>
</ul>
<p><strong>added 7/27/10</strong></p>
<ul>
<li>If you're after a aesthetic UI, be prepared to do a lot of custom or manual drawing. </li>
<li>If you're doing custom or manual drawing and you need to use transparency, get ready for a load of <a href="http://blog.opennetcf.com/ctacke/2009/10/26/ProjectResistanceTransparencyInTheCompactFrameworkSucks.aspx" rel="noreferrer">frustrations</a> and having to write <a href="http://blog.opennetcf.com/ctacke/2010/07/21/GettingAPixelsTransparencyInTheCompactFramework.aspx" rel="noreferrer">wacky code</a> or call <a href="http://msdn.microsoft.com/en-us/library/aa452250.aspx" rel="noreferrer">native code</a> directly to <a href="http://blog.opennetcf.com/ctacke/2010/07/23/KeepingABitmapsTransparencyWhenCopying.aspx" rel="noreferrer">work around</a> <a href="http://blog.opennetcf.com/ctacke/2009/10/28/ProjectResistanceDay4GraphicFixesAndMoreGesturing.aspx" rel="noreferrer">shortcomings</a> in the CF.</li>
</ul>
<p><strong>added 11/22/11</strong></p>
<ul>
<li>Don't assume that just because a namespace or class exists in the BCL that it is actually implemented in any useful manner. <a href="http://blog.opennetcf.com/ctacke/2011/11/22/X509CertificatesCompactFrameworkWTF.aspx" rel="noreferrer">Certificates certainly aren't</a>. </li>
</ul>
<p>I'm simply adding to the list as they occur to me...</p>
|
<p>When doing anything with OutlookSession, always</p>
<ul>
<li>instantiate it on the main (application) thread</li>
<li>execute against it on the main thread
(I use a Control object to Invoke
against)</li>
<li>and dispose of it within a decent
timeframe (if you don't you'll have
strange behavior in Pocket Outlook)</li>
</ul>
| 47,407
|
<p>My cygwin xterm is not responding to the keyboard.</p>
<p>I am able to run rxvt, but when I start other X applications I have the same problem.</p>
<p>From the rxvt command prompt, I get the following:</p>
<pre><code>$ xterm
xterm Xt error: Can't open display: :0
</code></pre>
<p>The contents of my XWin.0.log are:</p>
<pre><code>$ cat XWin.0.log
Welcome to the XWin X Server
Vendor: The Cygwin/X Project
Release: 1.5.3.0 (10503000)
Contact: cygwin-xfree@cygwin.com
XWin was started with the following command line:
/usr/bin/XWin -multiwindow -clipboard -silent-dup-error
ddxProcessArgument - Initializing default screens
winInitializeDefaultScreens - w 1440 h 900
winInitializeDefaultScreens - Returning
Fatal server error:
Server is already active for display 0
If this server is no longer running, remove /tmp/.X0-lock
and start again.
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
GetWindowProp - pWin or name was NULL
</code></pre>
<p>Removing /tmp/.X0-lock didn't help.</p>
|
<p>See <a href="http://x.cygwin.com/docs/faq/cygwin-x-faq.html#q-i-cant-type-anything" rel="nofollow noreferrer">this</a>.</p>
<ol>
<li><p>First stop the server by right-clicking on the X icon in the system tray and choosing exit.</p></li>
<li><p>Run the startxwin.bat file that is located in /usr/bin.</p></li>
</ol>
|
<p>Something in the back of my mind is saying "turn off Num Lock".</p>
<p>I'm not sure why.</p>
| 43,905
|
<p>I need some resources for implementing a simple virtual machine and interpreted language. Something that is pratical is most useful. I have read the Virtual Machine Implementation book and found that it is quite old and doesn't represent the vms I see today. Also if someone know of a fairly simplistic language that would be great as well.</p>
|
<p>check <a href="http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf" rel="nofollow noreferrer">The implementation of Lua 5.0</a></p>
|
<p>You don't say if this is for a new project, to work with an existing project, for learning, or what target environment, language, and OS you're using.</p>
<p>If you want to learn about implementing your own VM and scripting language, get the book <a href="https://rads.stackoverflow.com/amzn/click/com/1931841578" rel="nofollow noreferrer" rel="nofollow noreferrer">Game Scripting Mastery</a>. Despite its title, it is actually about implementing your own virtual machine and scripting language. The source code is for Win32, but the concepts can be applied to .Net or Linux.</p>
<p>As a bonus, when you're done you will have a playable, scriptable, 2D adventure game.</p>
| 48,318
|
<p>I started to write an application that calculates the estimated total print time from the G-code file for an already sliced model.</p>
<p>The program works and it's pretty accurate.</p>
<p>It works as follows: </p>
<ol>
<li>It scans the entire G-code file to identify all of the movements</li>
<li>It calculates the time for each move by dividing segment distance by the speed in mm/s.</li>
</ol>
<p>Let's assume this is the G-code:</p>
<pre><code>G28 ; home all axes
G1 Z0.200 F5400.000
G1 X158.878 Y27.769 E6.65594 F900.000
</code></pre>
<p>This is the calculation it does:</p>
<pre><code>totalTime = 0
# G28 ; home all axes
currentX = 0 mm
currentY = 0 mm
currentZ = 0 mm
# G1 Z0.200 F5400.000
newZ = 0.2 mm
mmPerSecond = 5400 / 60 = 90 mm/s
deltaZ = newZ - currentZ = 0.2 - 0 = 0.2 mm
segmentLength = deltaZ = 0.2 mm
moveTime = segmentLength / mmPerSecond = 0.2 / 90 = 0.002 s
totalTime = totalTime + moveTime = 0 + 0.002 = 0.002 s
# G1 X158.878 Y27.769 E6.65594 F900.000
newX = 158.878 mm
newY = 27.769 mm
mmPerSecond = 900 / 60 = 15 mm/s
deltaX = newX - currentX = 158.878 - 0 = 158.878 mm
deltaY = newY - currentY = 27.769 - 0 = 27.769 mm
segmentLength = square_root(deltaX² + deltaY²) = 161.287 mm
moveTime = deltaZ / mmPerSecond = 161.287 / 15 = 10.755 s
totalTime = totalTime + moveTime = 0.002 + 10.755 = 10.757 s
</code></pre>
<p>In this example, the print will take approximately 10.7 seconds.</p>
<p>More generally, the formula used is, for each movement:</p>
<pre><code>moveTime = segmentLength / mmPerSecond
</code></pre>
<p>By summing up all the move times, we have the total estimated print time.</p>
<p>I've seen that some forums state that the 3D print time also depends on some settings on the 3D printer, especially Acceleration X, Acceleration Y, Acceleration Z, Jerk, and Z-Jerk.</p>
<p>I'd like to make it possible to use those values to more accurately calculate print time; however, I don't understand how those values affect the move time:</p>
<ol>
<li>How should Acceleration and Jerk be considered; and, how do they speed up or slow down the print time? </li>
<li>How should I edit my formula in order to include Acceleration and Jerk in the print time calculation?</li>
</ol>
|
<p>I have tried looking into the printer firmware to see how the <em>Acceleration</em> setting affects the machine movement. From what I could tell, <em>Acceleration</em> seemed to be implemented differently depending on what firmware I looked at and was also affected by what the settings used on the printer were. I didn't look any further because writing different rules for every different firmware seemed like too much trouble. Maybe someone that knows more about this would know if most firmware uses the same calculations. </p>
<p>I suspect that the acceleration setting will not make a lot of difference to the time that the print takes. They haven't seemed to make a difference on the small prints that I have done printing with slow speeds. If you were printing larger prints at faster speeds that had long paths where the nozzle had time to accelerate and decelerate then I suspect you would notice a bigger difference with the time.</p>
<p>I have found that the biggest error between the predicted time and the actual time has been the time the machine spends processing the instructions. When printing a model that has a lot of short movements that need to be sent to the printer and they need to be processed and calculated by the printer, I have noticed the printer will pause for a fraction of a second. It is not long enough to see a difference in the printers movements, but it is noticeable enough to hear. I suspect that on cheaper printers this would cause a bigger error than the acceleration. </p>
<p>If someone can find out how the acceleration settings are calculated by the printer and what G-code command can be used to get the acceleration settings out of the printer, I would be really interested in knowing more about this.</p>
|
<p>I have tried looking into the printer firmware to see how the <em>Acceleration</em> setting affects the machine movement. From what I could tell, <em>Acceleration</em> seemed to be implemented differently depending on what firmware I looked at and was also affected by what the settings used on the printer were. I didn't look any further because writing different rules for every different firmware seemed like too much trouble. Maybe someone that knows more about this would know if most firmware uses the same calculations. </p>
<p>I suspect that the acceleration setting will not make a lot of difference to the time that the print takes. They haven't seemed to make a difference on the small prints that I have done printing with slow speeds. If you were printing larger prints at faster speeds that had long paths where the nozzle had time to accelerate and decelerate then I suspect you would notice a bigger difference with the time.</p>
<p>I have found that the biggest error between the predicted time and the actual time has been the time the machine spends processing the instructions. When printing a model that has a lot of short movements that need to be sent to the printer and they need to be processed and calculated by the printer, I have noticed the printer will pause for a fraction of a second. It is not long enough to see a difference in the printers movements, but it is noticeable enough to hear. I suspect that on cheaper printers this would cause a bigger error than the acceleration. </p>
<p>If someone can find out how the acceleration settings are calculated by the printer and what G-code command can be used to get the acceleration settings out of the printer, I would be really interested in knowing more about this.</p>
| 459
|
<p>Assuming some background in mathematics, how would you give a general overview of computational complexity theory to the naive?</p>
<p>I am looking for an explanation of the P = NP question. What is P? What is NP? What is a NP-Hard?</p>
<p>Sometimes Wikipedia is written as if the reader already understands all concepts involved.</p>
|
<p>Hoooo, doctoral comp flashback. Okay, here goes.</p>
<p>We start with the idea of a decision problem, a problem for which an algorithm can always answer "yes" or "no." We also need the idea of two models of computer (Turing machine, really): deterministic and non-deterministic. A deterministic computer is the regular computer we always thinking of; a non-deterministic computer is one that is just like we're used to except that is has unlimited parallelism, so that any time you come to a branch, you spawn a new "process" and examine both sides. Like Yogi Berra said, when you come to a fork in the road, you should take it.</p>
<p>A decision problem is in P if there is a known polynomial-time algorithm to get that answer. A decision problem is in NP if there is a known polynomial-time algorithm for a non-deterministic machine to get the answer.</p>
<p>Problems known to be in P are trivially in NP --- the nondeterministic machine just never troubles itself to fork another process, and acts just like a deterministic one. There are problems that are known to be neither in P nor NP; a simple example is to enumerate all the bit vectors of length n. No matter what, that takes 2<sup>n</sup> steps. </p>
<p>(Strictly, a decision problem is in NP if a nodeterministic machine can arrive at an answer in poly-time, and a deterministic machine can <em>verify</em> that the solution is correct in poly time.)</p>
<p>But there are some problems which are known to be in NP for which no poly-time deterministic algorithm is known; in other words, we know they're in NP, but don't know if they're in P. The traditional example is the decision-problem version of the Traveling Salesman Problem (decision-TSP): given the cities and distances, is there a route that covers all the cities, returning to the starting point, in less than <em>x</em> distance? It's easy in a nondeterministic machine, because every time the nondeterministic traveling salesman comes to a fork in the road, he takes it: his clones head on to the next city they haven't visited, and at the end they compare notes and see if any of the clones took less than <em>x</em> distance. </p>
<p>(Then, the exponentially many clones get to fight it out for which ones must be killed.)</p>
<p>It's not known whether decision-TSP is in P: there's no known poly-time solution, but there's no proof such a solution doesn't exist.</p>
<p>Now, one more concept: given decision problems P and Q, if an algorithm can transform a solution for P into a solution for Q in polynomial time, it's said that Q is <em>poly-time reducible</em> (or just reducible) to P.</p>
<p>A problem is NP-complete if you can prove that (1) it's in NP, and (2) show that it's poly-time reducible to a problem already known to be NP-complete. (The hard part of that was provie the <em>first</em> example of an NP-complete problem: that was done by Steve Cook in <a href="http://en.wikipedia.org/wiki/Cook%27s_theorem" rel="noreferrer">Cook's Theorem</a>.)</p>
<p>So really, what it says is that if anyone ever finds a poly-time solution to one NP-complete problem, they've automatically got one for <em>all</em> the NP-complete problems; that will also mean that P=NP.</p>
<p>A problem is NP-hard if and only if it's "at least as" hard as an NP-complete problem. The more conventional Traveling Salesman Problem of finding the shortest route is NP-hard, not strictly NP-complete.</p>
|
<p>My simplified answer would be: "Computational complexity is the analysis of how much harder a problem becomes when you add more elements."</p>
<p>In that sentence, the word "harder" is deliberately vague because it could refer either to processing time or to memory usage.</p>
| 39,692
|
<p>My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). </p>
<p>I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the coverage data directly from the IDE, as it's designed to do)</p>
<p>PyDev seems to be using the same coverage tool (or something very similar to it) to generate its coverage information, so I'm guessing there should be some way of integrating my external coverage files into Eclipse/PyDev.</p>
<p>Any idea on how to do this?</p>
|
<p>Here's what I've used successfully in the past:</p>
<p>MsgQueue table schema</p>
<pre><code>MsgId identity -- NOT NULL
MsgTypeCode varchar(20) -- NOT NULL
SourceCode varchar(20) -- process inserting the message -- NULLable
State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL
CreateTime datetime -- default GETDATE() -- NOT NULL
Msg varchar(255) -- NULLable
</code></pre>
<p>Your message types are what you'd expect - messages that conform to a contract between the process(es) inserting and the process(es) reading, structured with XML or your other choice of representation (JSON would be handy in some cases, for instance). </p>
<p>Then 0-to-n processes can be inserting, and 0-to-n processes can be reading and processing the messages, Each reading process typically handles a single message type. Multiple instances of a process type can be running for load-balancing. </p>
<p>The reader pulls one message and changes the state to "A"ctive while it works on it. When it's done it changes the state to "C"omplete. It can delete the message or not depending on whether you want to keep the audit trail. Messages of State = 'N' are pulled in MsgType/Timestamp order, so there's an index on MsgType + State + CreateTime.</p>
<p>Variations:<br>
State for "E"rror.<br>
Column for Reader process code.<br>
Timestamps for state transitions. </p>
<p>This has provided a nice, scalable, visible, simple mechanism for doing a number of things like you are describing. If you have a basic understanding of databases, it's pretty foolproof and extensible.</p>
<hr>
<p>Code from comments:</p>
<pre><code>CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) )
AS
DECLARE @MsgId INT
BEGIN TRAN
SELECT TOP 1 @MsgId = MsgId
FROM MsgQueue
WHERE MessageType = @pMessageType AND State = 'N'
ORDER BY CreateTime
IF @MsgId IS NOT NULL
BEGIN
UPDATE MsgQueue
SET State = 'A'
WHERE MsgId = @MsgId
SELECT MsgId, Msg
FROM MsgQueue
WHERE MsgId = @MsgId
END
ELSE
BEGIN
SELECT MsgId = NULL, Msg = NULL
END
COMMIT TRAN
</code></pre>
|
<p>You are trying to implement de "Database as IPC" antipattern. Look it up to understand why you should consider redesigning your software properly.</p>
| 38,032
|
<p>I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows.</p>
<p>When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary.</p>
<p>If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text Editors/Spelling" preference pane. This preference pane however states that <strong>"The selected spelling engine does not exist"</strong>, but has no control to add or install an engine.</p>
<p>How can I put a spelling engine in existence?</p>
<p>Update: What solved my problem was to install also the JDT. This solution was brought up on 2008-09-07 and was accepted, but is now missing.</p>
|
<p>The CDT version of Ganymede apparently shipped improperly configured. After playing around for a while, I have come up with the following steps that fix the problem.</p>
<ol>
<li>Export your Eclipse preferences (File > Export > General > Preferences).</li>
<li>Open the exported file in a text editor.</li>
<li><p>Find the line that says</p>
<pre>/instance/org.eclipse.ui.editors/spellingEngine=org.eclipse.jdt.internal.ui.text.spelling.DefaultSpellingEngine</pre></li>
<li><p>Change it to</p>
<p><pre>/instance/org.eclipse.ui.editors/spellingEngine=org.eclipse.cdt.internal.ui.text.spelling.CSpellingEngine</pre></p></li>
<li><p>Save the preferences file.</p></li>
<li>Import the preferences back into Eclipse (File > Import > General > Preferences).</li>
</ol>
<p>You should now be able to access the Spelling configuration page as seen above.</p>
<p>Note: if you want to add a custom dictionary, Eclipse must be able to access and open the file (i.e. it must exist - an empty file will work)</p>
|
<p>Just a word of warning: If you follow the advice to replace the preference as above, it will affect spell checking if you also use Java. I think all I needed to do was change the "Select spelling engine to use" to the C++ engine (near the top of the preference setting on the preference page General->Editors->Text Editors->Spelling).</p>
| 7,081
|
<p>All right, say I have this:</p>
<pre><code><select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
</code></pre>
<p>What would the selector look like if I wanted to get "Option B" when I have the value '2'?</p>
<p>Please note that this is not asking how to get the <em>selected</em> text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:</p>
<pre><code>$("#list[value='2']").text();
</code></pre>
<p>But it is not working.</p>
|
<p>It's looking for an element with id <code>list</code> which has a property <code>value</code> equal to <code>2</code>.<br>
What you want is the <code>option</code> child of the <code>list</code>:</p>
<pre><code>$("#list option[value='2']").text()
</code></pre>
|
<p>Try</p>
<pre><code>[...list.options].find(o=> o.value=='2').text
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let text = [...list.options].find(o=> o.value=='2').text;
console.log(text);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select></code></pre>
</div>
</div>
</p>
| 23,896
|
<p>This may appear a newbie question but forgive me I am new to the world of dot Net.</p>
<p>I have to make a desktop application that connects to a local SQL Server database. However in some cases the same database will be running on a server which can be accessed via the internet.</p>
<p>What is the best way to design such a program.
Basically the program is a collection of data entry forms,
I was thinking of making every query as a webservice to fetch data from the server and then post it back as a webservice.
But is there a better way to tackle such a problem ?
I want to use the same program in both cases, just make a change in a config file to tell the program to use local database or the database on the remote server.
Since I am new I dont know how to architect the program. I've heard a bit about ADO.Net data services ? is that the best way to go around this problem and where will LLB Gen pro fit in??</p>
<p>Thank you for your help</p>
|
<p>I would personally build that sort of logic into your DAL (Data Access Layer). Be it using ADO.Net or otherwise, the concept remains the same in that you build a flexible way of connecting to both remote databases as well as local databases based on the fact that it's a requirement for your application.</p>
<p>The devil is in the details after that. You'll certainly want to have a look at links such as <a href="http://msdn.microsoft.com/en-us/sync/bb887608.aspx" rel="nofollow noreferrer">this one</a> on occasionally connected applications from Microsoft.</p>
<p>Also check out <a href="http://msdn.microsoft.com/en-us/magazine/cc188750.aspx" rel="nofollow noreferrer">this link</a> on building a DAL with ADO.Net.</p>
<p>Best of luck!</p>
|
<p>You could just go the normal route of using ADO.NET connecting to the database server with a connection string through a SqlConnection object. Just make sure the "connecting over the internet" permits that kind of connection (it probably will unless you got some nasty firewall blocking it).</p>
| 38,369
|
<p>Should I create two <code>CFile</code> objects and copy one into the other character by character? Or is there something in the library that will do this for me?</p>
|
<p>I would just use the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfile" rel="nofollow noreferrer"><code>CopyFile</code></a> Win32 API function, but the example code in the <a href="https://learn.microsoft.com/en-us/cpp/mfc/reference/cfile-class?view=msvc-160#open" rel="nofollow noreferrer"><code>CFile::Open</code></a> documentation shows how to copy files with <code>CFile</code> (using pretty much the method you suggest).</p>
|
<p>While I appreciate the previous answers, I have found that this <code>FileOperations</code> is a nice wrapper that mimics the way copy operations are performed in Windows Explorer, which also includes Copy, Move and Delete files and rename directories:</p>
<p><a href="http://www.ucancode.net/Visual_C_Source_Code/Copy-Move-Delete-files-rename-directories-SHFileOperation-CFileFind-FindFirstFile-FindNextFile-mfc-example.htm" rel="nofollow noreferrer">http://www.ucancode.net/Visual_C_Source_Code/Copy-Move-Delete-files-rename-directories-SHFileOperation-CFileFind-FindFirstFile-FindNextFile-mfc-example.htm</a></p>
<pre><code>#include "stdafx.h"
#include "FileOperations.h"
//
// this code copy 'c:\source' directory and
// all it's subdirectories and files
// to the 'c:\dest' directory.
//
CFileOperation fo; // create object
fo.SetOverwriteMode(false); // reset OverwriteMode flag (optional)
if (!fo.Copy("c:\\source", "c:\\dest")) // do Copy
{
fo.ShowError(); // if copy fails show error message
}
//
// this code delete 'c:\source' directory and
// all it's subdirectories and files.
//
fo.Setucancode.netIfReadOnly(); // set ucancode.netIfReadonly flag (optional)
if (!fo.Delete("c:\\source")) // do Copy
{
fo.ShowError(); // if copy fails show error message
}
</code></pre>
<p>Here is the source code for completeness:</p>
<pre><code>#include "resource.h"
#define PATH_ERROR -1
#define PATH_NOT_FOUND 0
#define PATH_IS_FILE 1
#define PATH_IS_FOLDER 2
class CFExeption
{
public:
CFExeption(DWORD dwErrCode);
CFExeption(CString sErrText);
CString GetErrorText() {return m_sError;}
DWORD GetErrorCode() {return m_dwError;}
private:
CString m_sError;
DWORD m_dwError;
};
//*****************************************************************************************************
class CFileOperation
{
public:
CFileOperation(); // constructor
bool Delete(CString sPathName); // delete file or folder
bool Copy(CString sSource, CString sDest); // copy file or folder
bool Replace(CString sSource, CString sDest); // move file or folder
bool Rename(CString sSource, CString sDest); // rename file or folder
CString GetErrorString() {return m_sError;} // return error description
DWORD GetErrorCode() {return m_dwError;} // return error code
void ShowError() // show error message
{MessageBox(NULL, m_sError, _T("Error"), MB_OK | MB_ICONERROR);}
void SetAskIfReadOnly(bool bAsk = true) // sets behavior with readonly files(folders)
{m_bAskIfReadOnly = bAsk;}
bool IsAskIfReadOnly() // return current behavior with readonly files(folders)
{return m_bAskIfReadOnly;}
bool CanDelete(CString sPathName); // check attributes
void SetOverwriteMode(bool bOverwrite = false) // sets overwrite mode on/off
{m_bOverwriteMode = bOverwrite;}
bool IsOverwriteMode() {return m_bOverwriteMode;} // return current overwrite mode
int CheckPath(CString sPath);
bool IsAborted() {return m_bAborted;}
protected:
void DoDelete(CString sPathName);
void DoCopy(CString sSource, CString sDest, bool bDelteAfterCopy = false);
void DoFileCopy(CString sSourceFile, CString sDestFile, bool bDelteAfterCopy = false);
void DoFolderCopy(CString sSourceFolder, CString sDestFolder, bool bDelteAfterCopy = false);
void DoRename(CString sSource, CString sDest);
bool IsFileExist(CString sPathName);
void PreparePath(CString &sPath);
void Initialize();
void CheckSelfRecursion(CString sSource, CString sDest);
bool CheckSelfCopy(CString sSource, CString sDest);
CString ChangeFileName(CString sFileName);
CString ParseFolderName(CString sPathName);
private:
CString m_sError;
DWORD m_dwError;
bool m_bAskIfReadOnly;
bool m_bOverwriteMode;
bool m_bAborted;
int m_iRecursionLimit;
};
//*****************************************************************************************************
</code></pre>
<p>C++ file:</p>
<pre><code>#include "stdafx.h"
#include "resource.h"
#include "FileOperations.h"
//************************************************************************************************************
CFExeption::CFExeption(DWORD dwErrCode)
{
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dwErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
m_sError = (LPTSTR)lpMsgBuf;
LocalFree(lpMsgBuf);
m_dwError = dwErrCode;
}
CFExeption::CFExeption(CString sErrText)
{
m_sError = sErrText;
m_dwError = 0;
}
//************************************************************************************************************
CFileOperation::CFileOperation()
{
Initialize();
}
void CFileOperation::Initialize()
{
m_sError = _T("No error");
m_dwError = 0;
m_bAskIfReadOnly = true;
m_bOverwriteMode = false;
m_bAborted = false;
m_iRecursionLimit = -1;
}
void CFileOperation::DoDelete(CString sPathName)
{
CFileFind ff;
CString sPath = sPathName;
if (CheckPath(sPath) == PATH_IS_FILE)
{
if (!CanDelete(sPath))
{
m_bAborted = true;
return;
}
if (!DeleteFile(sPath)) throw new CFExeption(GetLastError());
return;
}
PreparePath(sPath);
sPath += "*.*";
BOOL bRes = ff.FindFile(sPath);
while(bRes)
{
bRes = ff.FindNextFile();
if (ff.IsDots()) continue;
if (ff.IsDirectory())
{
sPath = ff.GetFilePath();
DoDelete(sPath);
}
else DoDelete(ff.GetFilePath());
}
ff.Close();
if (!RemoveDirectory(sPathName) && !m_bAborted) throw new CFExeption(GetLastError());
}
void CFileOperation::DoFolderCopy(CString sSourceFolder, CString sDestFolder, bool bDelteAfterCopy)
{
CFileFind ff;
CString sPathSource = sSourceFolder;
BOOL bRes = ff.FindFile(sPathSource);
while (bRes)
{
bRes = ff.FindNextFile();
if (ff.IsDots()) continue;
if (ff.IsDirectory()) // source is a folder
{
if (m_iRecursionLimit == 0) continue;
sPathSource = ff.GetFilePath() + CString("\\") + CString("*.*");
CString sPathDest = sDestFolder + ff.GetFileName() + CString("\\");
if (CheckPath(sPathDest) == PATH_NOT_FOUND)
{
if (!CreateDirectory(sPathDest, NULL))
{
ff.Close();
throw new CFExeption(GetLastError());
}
}
if (m_iRecursionLimit > 0) m_iRecursionLimit --;
DoFolderCopy(sPathSource, sPathDest, bDelteAfterCopy);
}
else // source is a file
{
CString sNewFileName = sDestFolder + ff.GetFileName();
DoFileCopy(ff.GetFilePath(), sNewFileName, bDelteAfterCopy);
}
}
ff.Close();
}
bool CFileOperation::Delete(CString sPathName)
{
try
{
DoDelete(sPathName);
}
catch(CFExeption* e)
{
m_sError = e->GetErrorText();
m_dwError = e->GetErrorCode();
delete e;
if (m_dwError == 0) return true;
return false;
}
return true;
}
bool CFileOperation::Rename(CString sSource, CString sDest)
{
try
{
DoRename(sSource, sDest);
}
catch(CFExeption* e)
{
m_sError = e->GetErrorText();
m_dwError = e->GetErrorCode();
delete e;
return false;
}
return true;
}
void CFileOperation::DoRename(CString sSource, CString sDest)
{
if (!MoveFile(sSource, sDest)) throw new CFExeption(GetLastError());
}
void CFileOperation::DoCopy(CString sSource, CString sDest, bool bDelteAfterCopy)
{
CheckSelfRecursion(sSource, sDest);
// source not found
if (CheckPath(sSource) == PATH_NOT_FOUND)
{
CString sError = sSource + CString(" not found");
throw new CFExeption(sError);
}
// dest not found
if (CheckPath(sDest) == PATH_NOT_FOUND)
{
CString sError = sDest + CString(" not found");
throw new CFExeption(sError);
}
// folder to file
if (CheckPath(sSource) == PATH_IS_FOLDER && CheckPath(sDest) == PATH_IS_FILE)
{
throw new CFExeption("Wrong operation");
}
// folder to folder
if (CheckPath(sSource) == PATH_IS_FOLDER && CheckPath(sDest) == PATH_IS_FOLDER)
{
CFileFind ff;
CString sError = sSource + CString(" not found");
PreparePath(sSource);
PreparePath(sDest);
sSource += "*.*";
if (!ff.FindFile(sSource))
{
ff.Close();
throw new CFExeption(sError);
}
if (!ff.FindNextFile())
{
ff.Close();
throw new CFExeption(sError);
}
CString sFolderName = ParseFolderName(sSource);
if (!sFolderName.IsEmpty()) // the source is not drive
{
sDest += sFolderName;
PreparePath(sDest);
if (!CreateDirectory(sDest, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr != 183)
{
ff.Close();
throw new CFExeption(dwErr);
}
}
}
ff.Close();
DoFolderCopy(sSource, sDest, bDelteAfterCopy);
}
// file to file
if (CheckPath(sSource) == PATH_IS_FILE && CheckPath(sDest) == PATH_IS_FILE)
{
DoFileCopy(sSource, sDest);
}
// file to folder
if (CheckPath(sSource) == PATH_IS_FILE && CheckPath(sDest) == PATH_IS_FOLDER)
{
PreparePath(sDest);
char drive[MAX_PATH], dir[MAX_PATH], name[MAX_PATH], ext[MAX_PATH];
_splitpath(sSource, drive, dir, name, ext);
sDest = sDest + CString(name) + CString(ext);
DoFileCopy(sSource, sDest);
}
}
void CFileOperation::DoFileCopy(CString sSourceFile, CString sDestFile, bool bDelteAfterCopy)
{
BOOL bOvrwriteFails = FALSE;
if (!m_bOverwriteMode)
{
while (IsFileExist(sDestFile))
{
sDestFile = ChangeFileName(sDestFile);
}
bOvrwriteFails = TRUE;
}
if (!CopyFile(sSourceFile, sDestFile, bOvrwriteFails)) throw new CFExeption(GetLastError());
if (bDelteAfterCopy)
{
DoDelete(sSourceFile);
}
}
bool CFileOperation::Copy(CString sSource, CString sDest)
{
if (CheckSelfCopy(sSource, sDest)) return true;
bool bRes;
try
{
DoCopy(sSource, sDest);
bRes = true;
}
catch(CFExeption* e)
{
m_sError = e->GetErrorText();
m_dwError = e->GetErrorCode();
delete e;
if (m_dwError == 0) bRes = true;
bRes = false;
}
m_iRecursionLimit = -1;
return bRes;
}
bool CFileOperation::Replace(CString sSource, CString sDest)
{
if (CheckSelfCopy(sSource, sDest)) return true;
bool bRes;
try
{
bool b = m_bAskIfReadOnly;
m_bAskIfReadOnly = false;
DoCopy(sSource, sDest, true);
DoDelete(sSource);
m_bAskIfReadOnly = b;
bRes = true;
}
catch(CFExeption* e)
{
m_sError = e->GetErrorText();
m_dwError = e->GetErrorCode();
delete e;
if (m_dwError == 0) bRes = true;
bRes = false;
}
m_iRecursionLimit = -1;
return bRes;
}
CString CFileOperation::ChangeFileName(CString sFileName)
{
CString sName, sNewName, sResult;
char drive[MAX_PATH];
char dir [MAX_PATH];
char name [MAX_PATH];
char ext [MAX_PATH];
_splitpath((LPCTSTR)sFileName, drive, dir, name, ext);
sName = name;
int pos = sName.Find("Copy ");
if (pos == -1)
{
sNewName = CString("Copy of ") + sName + CString(ext);
}
else
{
int pos1 = sName.Find('(');
if (pos1 == -1)
{
sNewName = sName;
sNewName.Delete(0, 8);
sNewName = CString("Copy (1) of ") + sNewName + CString(ext);
}
else
{
CString sCount;
int pos2 = sName.Find(')');
if (pos2 == -1)
{
sNewName = CString("Copy of ") + sNewName + CString(ext);
}
else
{
sCount = sName.Mid(pos1 + 1, pos2 - pos1 - 1);
sName.Delete(0, pos2 + 5);
int iCount = atoi((LPCTSTR)sCount);
iCount ++;
sNewName.Format("%s%d%s%s%s", "Copy (", iCount, ") of ", (LPCTSTR)sName, ext);
}
}
}
sResult = CString(drive) + CString(dir) + sNewName;
return sResult;
}
bool CFileOperation::IsFileExist(CString sPathName)
{
HANDLE hFile;
hFile = CreateFile(sPathName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return false;
CloseHandle(hFile);
return true;
}
int CFileOperation::CheckPath(CString sPath)
{
DWORD dwAttr = GetFileAttributes(sPath);
if (dwAttr == 0xffffffff)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND)
return PATH_NOT_FOUND;
return PATH_ERROR;
}
if (dwAttr & FILE_ATTRIBUTE_DIRECTORY) return PATH_IS_FOLDER;
return PATH_IS_FILE;
}
void CFileOperation::PreparePath(CString &sPath)
{
if(sPath.Right(1) != "\\") sPath += "\\";
}
bool CFileOperation::CanDelete(CString sPathName)
{
DWORD dwAttr = GetFileAttributes(sPathName);
if (dwAttr == -1) return false;
if (dwAttr & FILE_ATTRIBUTE_READONLY)
{
if (m_bAskIfReadOnly)
{
CString sTmp = sPathName;
int pos = sTmp.ReverseFind('\\');
if (pos != -1) sTmp.Delete(0, pos + 1);
CString sText = sTmp + CString(" is read olny. Do you want delete it?");
int iRes = MessageBox(NULL, sText, _T("Warning"), MB_YESNOCANCEL | MB_ICONQUESTION);
switch (iRes)
{
case IDYES:
{
if (!SetFileAttributes(sPathName, FILE_ATTRIBUTE_NORMAL)) return false;
return true;
}
case IDNO:
{
return false;
}
case IDCANCEL:
{
m_bAborted = true;
throw new CFExeption(0);
return false;
}
}
}
else
{
if (!SetFileAttributes(sPathName, FILE_ATTRIBUTE_NORMAL)) return false;
return true;
}
}
return true;
}
CString CFileOperation::ParseFolderName(CString sPathName)
{
CString sFolderName = sPathName;
int pos = sFolderName.ReverseFind('\\');
if (pos != -1) sFolderName.Delete(pos, sFolderName.GetLength() - pos);
pos = sFolderName.ReverseFind('\\');
if (pos != -1) sFolderName = sFolderName.Right(sFolderName.GetLength() - pos - 1);
else sFolderName.Empty();
return sFolderName;
}
void CFileOperation::CheckSelfRecursion(CString sSource, CString sDest)
{
if (sDest.Find(sSource) != -1)
{
int i = 0, count1 = 0, count2 = 0;
for(i = 0; i < sSource.GetLength(); i ++) if (sSource[i] == '\\') count1 ++;
for(i = 0; i < sDest.GetLength(); i ++) if (sDest[i] == '\\') count2 ++;
if (count2 >= count1) m_iRecursionLimit = count2 - count1;
}
}
bool CFileOperation::CheckSelfCopy(CString sSource, CString sDest)
{
bool bRes = false;
if (CheckPath(sSource) == PATH_IS_FOLDER)
{
CString sTmp = sSource;
int pos = sTmp.ReverseFind('\\');
if (pos != -1)
{
sTmp.Delete(pos, sTmp.GetLength() - pos);
if (sTmp.CompareNoCase(sDest) == 0) bRes = true;
}
}
return bRes;
}
</code></pre>
| 23,325
|
<p>How do you get a pointer to the .text section of memory for a program from within that program? I also need the length of the section to do a "Flash to Memory" compare as part of a continuous selftest that runs in the background.</p>
<p>The toolset automatically generates the linker .cmd file for the tools I'm using, and the Board Support Package for the board I'm using requires I use the generated .cmd file instead of making my own. (No make file either to add a script to muck with it afterwords.)</p>
<p>Edit:
I'm working with a TI TMS 6713 DSP using the code composer 3.1 environment. The card I'm using was contracted by our customer and produced by another organization so I can't really point you to any info on it. However the BSP is dependant upon TI's "DSP BIOS" config tool, and I can't really fudge the settings too much without digging into an out of scope effort.</p>
|
<p>You need to put "variables" in the linker script.</p>
<p>In one of my projects I have this in one of my sections:</p>
<pre><code> __FlashStart = .;
</code></pre>
<p>In the C program I have this:</p>
<pre><code>extern unsigned long int _FlashStart;
unsigned long int address = (unsigned long int)&_FlashStart;
</code></pre>
|
<p>Could you clarify which tool chain and architecture you are interested in.</p>
<p>On the compiler I am using right now (IAR ARM C/C++) there are operators built into the compiler which return the segment begin address <code>__sfb(...)</code>, segment end address <code>__sfe(...)</code>, and segment size <code>__sfs(...)</code></p>
| 24,771
|
<p>How do I make one? I am kind of a newbie in Windows API. Is there some sort of manual for this sort of thing? I am specifically interested in a Core API. Thank you for any help.</p>
|
<p>There are three ways of doing scroll bars: A window's scroll bar; a scroll bar control; or a custom control.</p>
<p>Windows have scroll bars in the non-client (NC) area. These are part of the window frame, and as such they do not have their own window handle or anything.</p>
<p>Scroll bar controls are child window implementations of a scroll bar. Because they are child windows, they offer you a bit more flexibility. You could subclass or superclass one of these controls to implement "infinite" functionality.</p>
<p>The final option is a custom control: you just create your own scroll bar from scratch. Create a single child window, draw it yourself, handle all the mouse and keyboard input yourself, and implement the scroll bar messages yourself. This isn't actually as hard as it may sound.</p>
<p>I'd probably recommend <a href="http://msdn.microsoft.com/en-us/library/ms633569.aspx" rel="nofollow noreferrer">superclassing</a> a scroll bar control. Process the scroll messages in your own scroll bar wndproc, and fall back to the standard scroll bar wndproc for painting and such.</p>
|
<p>What do you mean with "infinite"?</p>
<p>If you mean a scroll bar where the user can never scroll to the ends, you have to handle the scroll bar's position change notifications and reset the position to the middle.</p>
| 9,735
|
<p>Several months ago my work deployed an in-house function that wraps the standard, php, mysql_query() function with additional options and abilities. A sample feature would be some handy debugging tools we can turn on/off. </p>
<p>I was wondering how popular query handlers are and what features people like to build into them.</p>
|
<p>I use a DBAL like <a href="http://pear.php.net/package/MDB2" rel="nofollow noreferrer">MDB2</a>, <a href="http://framework.zend.com/manual/en/zend.db.html" rel="nofollow noreferrer">Zend_Db</a> or <a href="http://www.doctrine-project.org/" rel="nofollow noreferrer">Doctrine</a> for similar reason. Primarily to be able to utilize all the shortcuts it offers, not so much for the fact that it supports different databases.</p>
<p>E.g., old:</p>
<pre><code><?php
$query = "SELECT * FROM table";
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
} else {
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_obj($result)) {
...
}
}
}
?>
</code></pre>
<p>Versus (Zend_Db):</p>
<pre><code><?php
try {
$result = $db->fetchAll("SELECT * FROM table");
foreach($result as $row) {
...
}
} catch (Zend_Exception $e) {
echo $e->getMessage();
}
?>
</code></pre>
<p>IMHO, more intuitive.</p>
|
<p>We implemented something similar at my office too. It's proven to be an invaluable to tool for the associated handling features it offers. Error tracking, pre-formatted output and it also works as an 'AL' between MsSQL and MySQL.</p>
<p>Aside from the above features I think it'd be cool to have some low-resource intensive performance monitoring or tracking. For larger or more complicated data sets the queries can be quite weighty and being able to monitor that real-time (or post) would be helpful for any optimization needed on larger-scale websites.</p>
<p>Just my two cents.</p>
| 15,672
|
<p>I want to search for <code>$maximumTotalAllowedAfterFinish</code> and replace it with <code>$minimumTotalAllowedAfterFinish</code>. Instead of typing the long text:</p>
<pre><code>:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g
</code></pre>
<p>Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "<code>p</code>" to paste?</p>
|
<p>You can insert the contents of a numbered or named register by typing <kbd>CTRL</kbd><kbd>R</kbd> <kbd><code>{0-9a-z"%#:-=.}</code></kbd>. By typing <kbd>CTRL-R</kbd> <kbd>CTRL-W</kbd> you can paste the current word under the cursor. See:</p>
<pre><code>:he cmdline-editing
</code></pre>
<p>for more information.</p>
|
<p>Typically, you would do that with mouse selecting (perhaps <kbd>Ctrl</kbd><kbd>Ins</kbd> or <kbd>Ctrl</kbd><kbd>C</kbd> after selecting) and then, when in the command/search line, middle-clicking (or <kbd>Shift</kbd><kbd>Ins</kbd> or <kbd>Ctrl</kbd><kbd>V</kbd>).</p>
<p>Another way, is to write your command/search line in the text buffer with all the editing available in text buffers, starting with <code>:</code> and all, then, on the line, do:</p>
<pre><code>"add@a
</code></pre>
<p>which will store the whole command line in buffer <code>a</code>, and then execute it. It won't be stored in the command history, though.</p>
<p>Try creating the following line in the text buffer as an example for the key presses above:</p>
<pre><code>:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g
</code></pre>
<p>Finally, you can enter <code>q:</code> to enter history editing in a text buffer.</p>
| 12,667
|
<p>If you are writing a <em>simple</em> little loop, what <em>should</em> you name the counter?</p>
<p><em>Provide example loops!</em></p>
|
<p>I always use a <strong>meaningful name</strong> unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use <code>i</code>.</p>
<p>When using meaningful names:</p>
<ul>
<li>the code is more understandable to colleagues reading your code,</li>
<li>it's easier to find bugs in the loop logic, and</li>
<li>text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.</li>
</ul>
<h2>Example - spot the bug</h2>
<p>It can be tricky to find the bug in this nested loop using single letters:</p>
<pre><code>int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int i, j, total;
total = 0;
for (i = 0; i < MAX_COLS; i++)
for (j = 0; j < MAX_ROWS; j++)
total += values[i][j];
return total;
}
</code></pre>
<p>whereas it is easier when using meaningful names:</p>
<pre><code>int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int row_num, col_num, total;
total = 0;
for (row_num = 0; row_num < MAX_COLS; row_num++)
for (col_num = 0; col_num < MAX_ROWS; col_num++)
total += values[row_num][col_num];
return total;
}
</code></pre>
<h3>Why <code>row_num</code>? - rejected alternatives</h3>
<p>In response to some other answers and comments, these are some alternative suggestions to using <code>row_num</code> and <code>col_num</code> and why I choose not to use them:</p>
<ul>
<li><strong><code>r</code></strong> and <strong><code>c</code></strong>: This is slightly better than <code>i</code> and <code>j</code>. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code.</li>
<li><strong><code>rr</code></strong> and <strong><code>cc</code></strong>: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than <code>r</code> and <code>c</code>.</li>
<li><strong><code>row</code></strong> and <strong><code>col</code></strong>: At first glance this seems more succinct than <code>row_num</code> and <code>col_num</code>, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If <code>row</code> could mean <em>either</em> the row structure itself, <em>or</em> a row number, then confusion will result.</li>
<li><strong><code>iRow</code></strong> and <strong><code>iCol</code></strong>: This conveys extra information, since <code>i</code> can mean it's a loop counter while <code>Row</code> and <code>Col</code> tell you what it's counting. However, I prefer to be able to read the code almost in English:
<ul>
<li><code>row_num < MAX_COLS</code> reads as "the <strong>row num</strong>ber is <strong>less than</strong> the <strong>max</strong>imum (number of) <strong>col</strong>umn<b>s</b>";</li>
<li><code>iRow < MAX_COLS</code> at best reads as "the <strong>integer loop counter</strong> for the <strong>row</strong> is <strong>less than</strong> the <strong>max</strong>imum (number of) <strong>col</strong>umn<b>s</b>".</li>
<li>It may be a personal thing but I prefer the first reading.</li>
</ul></li>
</ul>
<p>An alternative to <code>row_num</code> I would accept is <code>row_idx</code>: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.</p>
<p>My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.</p>
<p>In summary, my aim with all variable naming (not just loops) is to be <strong>completely unambiguous</strong>. If <em>anybody</em> reads any portion of my code and can't work out what a variable is for immediately, then I have failed.</p>
|
<p>I've started using perlisms in php. </p>
<p>if its a singular iteration, <code>$_</code> is a good name for those who know its use.</p>
| 12,643
|
<p>I'm using SharpZipLib version 0.85.5 to unzip files. My code has been working nicely for a couple of months until I found a ZIP file that it doesn't like.</p>
<pre><code>ICSharpCode.SharpZipLib.Zip.ZipException: End of extra data
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.ReadCheck(Int32 length) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 933
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.Skip(Int32 amount) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 921
at ICSharpCode.SharpZipLib.Zip.ZipEntry.ProcessExtraData(Boolean localHeader) in C:\C#\SharpZLib\Zip\ZipEntry.cs:line 925
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry() in C:\C#\SharpZLib\Zip\ZipInputStream.cs:line 269
at Constellation.Utils.Tools.UnzipFile(String sourcePath, String targetDirectory) in C:\C#\Constellation2\Utils\Tools.cs:line 90
--- End of inner exception stack trace ---
</code></pre>
<p>Here is my unzip method:</p>
<pre><code> public static void UnzipFile(string sourcePath, string targetDirectory)
{
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (targetDirectory.Length > 0)
{
Directory.CreateDirectory(targetDirectory);
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(targetDirectory + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
}
}
</code></pre>
<p>The file unzips fine using XP's built-in ZIP support, WinZIP, and 7-Zip. The exception is being thrown at <code>s.GetNextEntry()</code>. </p>
|
<p>It's possible that the other zip tools are ignoring extra data which is corrupt - or it's equally possible that there's a bug in #ZipLib. (I found one a while ago - a certain file that wouldn't compress and then decompress cleanly with certain options.)</p>
<p>In this particular case, I suggest you post on the #ZipLib forum to get the attention of the developers. If your file doesn't contain any sensitive data and you can get them a short but complete program along with it, I suspect that will help enormously.</p>
|
<p>I agree with Jon. Couldn't fit following in the comment:</p>
<p>(Though this doesn't answer your question)
Isn't it easier to use something like this:</p>
<pre><code>public static void UnzipFile(string sourcePath, string targetDirectory)
{
try
{
FastZip fastZip = new FastZip();
fastZip.CreateEmptyDirectories = false;
fastZip.ExtractZip(sourcePath, targetDirectory,"");
}
catch(Exception ex)
{
throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
}
}
</code></pre>
| 18,668
|
<p>I want do something like this:</p>
<pre><code>Button btn1 = new Button();
btn1.Click += new EventHandler(btn1_Click);
Button btn2 = new Button();
// Take whatever event got assigned to btn1 and assign it to btn2.
btn2.Click += btn1.Click; // The compiler says no...
</code></pre>
<p>Where btn1_Click is already defined in the class:</p>
<pre><code>void btn1_Click(object sender, EventArgs e)
{
//
}
</code></pre>
<p>This won't compile, of course ("The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -="). Is there a way to take the event handler from one control and assign it to another at runtime? If that's not possible, is duplicating the event handler and assigning it to another control at runtime doable?</p>
<p>A couple of points: I have googled the heck out of this one for awhile and found no way of doing it yet. Most of the attempted approaches involve reflection, so if you read my question and think the answer is incredibly obvious, please try to compile the code in Visual Studio first. Or if the answer really is incredibly obvious, please feel free to slap me with it. Thanks, I'm really looking forward to seeing if this is possible.</p>
<p>I know I could just do this:</p>
<pre><code>btn2.Click += new EventHandler(btn1_Click);
</code></pre>
<p>That's not what I'm looking for here.</p>
<p>This is also not what I'm looking for:</p>
<pre><code>EventHandler handy = new EventHandler(btn1_Click);
Button btn1 = new Button();
btn1.Click += handy;
Button btn2 = new Button();
btn2.Click += handy;
</code></pre>
|
<p>Yeah, it's technically possible. Reflection is required because many of the members are private and internal. Start a new <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> project and add two buttons. Then:</p>
<pre><code>using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
// Get secret click event key
FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);
object secret = eventClick.GetValue(null);
// Retrieve the click event
PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList events = (EventHandlerList)eventsProp.GetValue(button1, null);
Delegate click = events[secret];
// Remove it from button1, add it to button2
events.RemoveHandler(secret, click);
events = (EventHandlerList)eventsProp.GetValue(button2, null);
events.AddHandler(secret, click);
}
void button1_Click(object sender, EventArgs e) {
MessageBox.Show("Yada");
}
}
}
</code></pre>
<p>If this convinces you that Microsoft tried really hard to prevent your from doing this, you understood the code.</p>
|
<p>You could use a common event handler for your buttons and your picture boxes (as per the comments on an earlier answer) and then use the 'sender' object to determine how to handle the event at runtime.</p>
| 37,394
|
<p>Some of the most efficient engineers, developers and IT professionals I know usually carry around a common "toolkit" of useful programs, add-ins or utilities which help them for day-to-day debugging, developing or designing.</p>
<p>The question is:<br>
<i>What is in your utility toolkit.. What tools couldn't you live without?</i></p>
|
<p><a href="http://unxutils.sourceforge.net" rel="noreferrer">Unix Utilities for Windows</a></p>
|
<p>Here's <a href="https://web.archive.org/web/20080914042228/http://rabdullin.com/development-software-requirements-for-the-xlim-2-solutions/" rel="nofollow noreferrer">list of tools, utils and progs</a> I use for my .NET software development projects.</p>
| 20,884
|
<p>Good morning,</p>
<p>I work in a small shop (only two of us) and we currently manage more .vbs scripts that we would like to (we would like to manage zero). One of the nice things about these scripts is that it's quick to make changes (as necessary) and go back to our day jobs. </p>
<p>That's all nice and good until we decide that the job needs to be changed substantially, and then a PITA to develop and debug, mostly because it feels like I'm shooting pool with a baseball bat.</p>
<p>Is there a more DotNet-y way to do Windows Scripting Host-like stuff that people have used and like? I'd prefer free/cheap tools, naturally.</p>
<p>Regards,</p>
<p>-Alan.</p>
|
<p><a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" rel="noreferrer">PowerShell</a> is the "next generation, .NET-based scripting platform" from Microsoft. I haven't looked at it in detail, but from what I've heard it's trying to combine the simplicity of Unix-style pipelines with the power of a rich object model.</p>
<p>Whether or not it fits in with exactly what you want to achieve is something I can't really say, of course - but it's certainly worth a look.</p>
<p>There are other .NET languages which are amenable to scripting - there are the dynamic languages such as <a href="http://www.ironruby.net/" rel="noreferrer">IronRuby</a> and <a href="http://www.codeplex.com/IronPython" rel="noreferrer">IronPython</a>, and also <a href="http://boo.codehaus.org/" rel="noreferrer">Boo</a> (mostly static, but with duck-typing where you want it).</p>
|
<p>Trying to get a fix on the future of VBScript is problematic. Microsoft have said that they're <a href="https://web.archive.org/web/20060511012208/http://www.visualbasicscript.com/m_26652/mpage_1/key_/tm.htm#26652" rel="nofollow noreferrer">committed to keeping it going</a> (second entry). However, whilst there is a <a href="http://en.wikipedia.org/wiki/JScript_.NET" rel="nofollow noreferrer">JScript.NET</a> there's no sign yet of a VBScript.NET. </p>
<p>There are various approaches to the issue apart from JScript.NET, for example <a href="http://www.dotnetframework.de/scripting/dotnetscripting/dsh.en.asp" rel="nofollow noreferrer">DOTNET Scripting Host (DSH)</a>. </p>
<p>So VBScript seems to be more or less alive and well. A while back there was even a CodeProject article <a href="http://www.codeproject.com/KB/system/mScriptable.aspx" rel="nofollow noreferrer">Scripting .NET applications with VBScript</a>.</p>
<p>It's ultimately your choice; for me learning PowerShell is not high on my list of things to do, so I'll just plod on with VBScript as it stands and, as Fozzie Bear suggests, "hope that something better comes along."</p>
| 41,504
|
<p>Does anyone know of a freeware shipping calculator for PHP? I do not want anything too fancy, and it can be compatible with any of the major US domestic shipping services.</p>
<p>If anyone knows of one that is a plugin for CodeIgniter that would be nice.</p>
<p>Travis</p>
|
<p>Usually services like this are based on web services offered from the various couriers. You would send the weight and dimensions of the box you want to ship to their web service, and they would return a corresponding shipping price. Each couriers API would be different. I'm not sure if there are any libraries that aggregate all these services together, but I've never seen one. Since prices can change at any time, you pretty much have to use some kind of web service to access this information. That is, unless you are Amazon sized and have preexisting arrangements for pricing rates on shipping with the various couriers. Just from a quick lookup, here is some of the services that <a href="http://www.fedex.com/us/developer/product/basics.html" rel="noreferrer">FedEx</a> offers.</p>
|
<p>There is a service that allows you access to their API that intergrates with the APIs of Fedex, USPS, UPS, and DHL. It costs $25/month to be allowed to make requests but its a complete solution. The OP stated "freeware" but I figured others will come across this and appreciate a solution even if you have to pay.</p>
<p><a href="http://www.auctioninc.com/info/page/shipping_api" rel="nofollow">http://www.auctioninc.com/info/page/shipping_api</a></p>
<p>They have a php sdk so its even easier on php. From what they explained they weren't sure if you could use AJAX, so we just built it out to post via AJAX to the php. Works great!</p>
<p>Old post, I know. But new options become available and old threads still pull up in search results.</p>
| 41,320
|
<p>I've got a pretty basic question about how to start using Castle Windsor. I've read up on IOC/DI and would like to try Castle Windsor in an existing solution. I typically like to put any external assemblies in a Lib folder within the solution's folder tree so that the references are relative (I believe this is best practice). </p>
<p>Which assemblies from the Castle\Bin... folder do I need to copy to my Lib folder? And do I need to add an explicit reference to each assembly or only some of them?</p>
<p>There are 30 assemblies in the C:\dev\oss\Castle\Bin\net-2.0 folder and 18 assemblies in the C:\dev\oss\Castle\Bin\Dependencies folder.</p>
|
<p>I reckon this should be enough to get you started.</p>
<ul>
<li>Castle.Core</li>
<li>Castle.MicroKernel</li>
<li>Castle.Windsor</li>
</ul>
<p>and if you want to use log4net for logging then....</p>
<ul>
<li>log4net </li>
<li>Castle.Facilities.Logging </li>
<li>Castle.Services.Logging.Log4netIntegration</li>
</ul>
|
<p>Only Castle.Core, Castle.MicroKernel and Castle.Windsor are required to be able to use Windsor.</p>
| 49,237
|
<p>I've managed to mostly ignore all this multi-byte character stuff, but now I need to do some UI work and I know my ignorance in this area is going to catch up with me! Can anyone explain in a few paragraphs or less just what I need to know so that I can localize my applications? What types should I be using (I use both .Net and C/C++, and I need this answer for both Unix and Windows).</p>
|
<p>Check out Joel Spolsky's <strong><a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></strong></p>
<p><strong>EDIT 20140523</strong>: Also, watch <strong><a href="https://www.youtube.com/watch?v=MijmeoH9LT4" rel="noreferrer">Characters, Symbols and the Unicode Miracle</a></strong> by Tom Scott on YouTube - it's just under ten minutes, and a wonderful explanation of the brilliant 'hack' that is UTF-8</p>
|
<p>There is also the issue with fonts. There are two ways to handle fonts. Either you use a gigantic font with glyphs for all the Unicode characters you need (I think recent versions of Windows comes with one or two such fonts). Or you use som library capable of combining glyphs from various fonts dedicated to subsets of the Unicode standard.</p>
| 20,745
|
<p>Ideally, something cross-platform.</p>
|
<p>The CPAN is probably the best way to go. Take a look at <a href="http://search.cpan.org/~tpaba/Term-Screen-Uni-0.04/lib/Term/Screen/Uni.pm" rel="noreferrer">Term::Screen:Uni</a>:</p>
<pre><code>require Term::Screen::Uni;
my $scr = new Term::Screen::Uni;
$scr->clrscr()
</code></pre>
|
<p><strong>I disagree with the above</strong></p>
<ol>
<li>Connecting additional modules = Increase the attack surface.</li>
<li>Reduce the Amount of Running Code.</li>
<li>Code refactoring.</li>
</ol>
<hr />
<pre><code>#!/usr/bin/perl -w
use strict;
my
( $over, $cleaning );
( $cleaning ) = qq([J\033[H\033[J);
( $over ) = <<EOF;
1. Connecting additional modules = Increase the attack surface.
2. Reduce the Amount of Running Code.
3. Code refactoring.
EOF
print ($cleaning.$over);
__END__
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>FOO</th>
<th>BAR</th>
</tr>
</thead>
<tbody>
<tr>
<td>\033</td>
<td>stands for ESC ANSI value 27</td>
</tr>
<tr>
<td>[J</td>
<td>erases the screen from the current line down screen</td>
</tr>
<tr>
<td>[H</td>
<td>move the cursor to the home position</td>
</tr>
</tbody>
</table>
</div>
| 24,093
|
<p><strong>Problem:</strong></p>
<p>Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length.</p>
<p><strong>Example:</strong></p>
<p><code>"foo"</code>, <code>"fool"</code>, <code>"bar"</code></p>
<p>The result is: "foo" as the base string with the strings <code>"\0"</code>, <code>"\0l"</code>, <code>"bar"</code> and a total length of 9 bytes. <code>"\0"</code> is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte.</p>
<p><strong>A naive algorithm would look like:</strong></p>
<pre><code>for string in list
for i = 1, i < length of string
calculate total length based on prefix of string[0..i]
if better than last best, save it
return the best prefix
</code></pre>
<p>That will give us the answer, but it's something like O((n*m)^2), which is too expensive.</p>
|
<p>Use a forest of prefix trees (trie)...</p>
<pre><code> f_2 b_1
/ |
o_2 a_1
| |
o_2 r_1
|
l_1
</code></pre>
<p>then, we can find the best result, and guarantee it, by maximizing <code>(depth * frequency)</code> which will be replaced with your escape character. You can optimize the search by doing a branch and bound depth first search for the maximum.</p>
<p>On the complexity: O(C), as mentioned in comment, for building it, and for finding the optimal, it depends. If you order the first elements frequency (O(A) --where A is the size of the languages alphabet), then you'll be able to cut out more branches, and have a good chance of getting sub-linear time.</p>
<p>I think this is clear, I am not going to write it up --what is this a homework assignment? ;)</p>
|
<p>I would try starting by sorting the list. Then you simply go from string to string comparing the first character to the next string's first char. Once you have a match you would look at the next char. You would need to devise a way to track the best result so far.</p>
| 18,166
|
<p>How do you access the response from the Request
object in MooTools? I've been looking at the documentation and the MooTorial, but
I can't seem to make any headway. Other Ajax stuff I've done with
MooTools I haven't had to manipulate the response at all, so I've just
been able to inject it straight into the document, but now I need to
make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated.
Thanks.</p>
<p>Edit:</p>
<p>I'd like to be able to access
the response after the request has already been made, preferably
outside of the Request object. It's for an RSS reader, so I need to do
some parsing and Request is just being used to get the feed from a
server file. This function is a method in a class, which should return
the response in a string, but it isn't returning anything but
undefined:</p>
<pre><code> fetch: function(site){
var feed;
var req = new Request({
method: this.options.method,
url: this.options.rssFetchPath,
data: { 'url' : site },
onRequest: function() {
if (this.options.targetId) { $
(this.options.targetId).setProperty('html',
this.options.onRequestMessage); }
}.bind(this),
onSuccess: function(responseText) {
feed = responseText;
}
});
req.send();
return feed;
}
</code></pre>
|
<p>The response content is returned to the anonymous function defined in onComplete.</p>
<p>It can be accessed from there.</p>
<pre><code>var req = new Request({
method: 'get',
url: ...,
data: ...,
onRequest: function() { alert('Request made. Please wait...'); },
// the response is passed to the callback as the first parameter
onComplete: function(response) { alert('Response: ' + response); }
}).send();
</code></pre>
|
<p>I was able to find my answer on the <a href="http://groups.google.com/group/mootools-users/browse_thread/thread/7ade43ef51c91922" rel="nofollow noreferrer">MooTools Group at Google</a>.</p>
| 12,208
|
<p><strong>Question</strong></p>
<p>How would you go adding automated testing to a game?</p>
<p>I believe you can unit test a lot of the game engine's functionality (networking, object creation, memory management, etc), but is it possible to automate test the actual game itself?</p>
<p>I'm not talking about gameplay elements (like Protoss would beat Zerg in map X), but I'm talking about the interaction between the game and the engine.</p>
<p><strong>Introduction</strong></p>
<p>In game development, the engine is just a platform for the game. You could think of the game engine as an OS and the game as a software the OS would run. The game could be a collection of scripts or an actual subroutine inside the game engine.</p>
<p><strong>Possible Answers</strong></p>
<p>My idea is this: </p>
<p>You would need an engine that is deterministic. This means that given one set of input, the output would be exactly the same. This would inlude the random generator being seeded with the same input.</p>
<p>Then, create a bare-bone level which contains a couple of objects the avatar/user can interact with. Start small and then add objects into the level as more interactions are developed.</p>
<p>Create a script which follows a path (tests pathfinding) and interact with the different objects (store the result or expected behavior). This script would be your automated test. After a certain amount of time (say, one week), run the script along with your engine's unit tests.</p>
|
<p><a href="http://gamesfromwithin.com/?p=97" rel="noreferrer">This post</a> at <a href="http://gamesfromwithin.com" rel="noreferrer">Games From Within</a> might be relevant/interesting. </p>
|
<p>This doesn't really answer your question but I was listening to a podcast on <a href="http://research.microsoft.com/pex/" rel="nofollow noreferrer">Pex from microsoft</a> which does a similar thing to the solution you're proposing and when I was listening to it I remember thinking that it would be really interesting to see if it would be able to test games. I don't know if it would be able to help you specifically, but perhaps you could take a look at some of the ideas they use and apply it to your unit testing.</p>
| 3,493
|
<p>I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble.</p>
<p>This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception:</p>
<p>Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See <a href="http://www.gnome.org/projects/gconf/" rel="nofollow noreferrer">http://www.gnome.org/projects/gconf/</a> for information. (Details - 1: <strong>Not running within active session</strong>)</p>
<p>Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?).</p>
<p>Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions?</p>
<p>(More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.)</p>
|
<p>I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it.</p>
<p>GConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again.</p>
<p>I tried to spawn the D-Bus session bus by doing the following:</p>
<pre><code>import dbus
dummy_bus = dbus.SessionBus()
</code></pre>
<p>...but got this:</p>
<pre><code>dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed.
</code></pre>
<p>Weird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the <a href="http://www.python.org/doc/2.5.2/lib/os-process.html" rel="noreferrer">os.system()</a> call):</p>
<pre><code>$ dbus-launch
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268
DBUS_SESSION_BUS_PID=15836
</code></pre>
<p>You'll need to parse the output somehow and inject them into environment variables (you'll probably want to use <a href="http://www.python.org/doc/2.5.2/lib/os-procinfo.html" rel="noreferrer">os.putenv</a>). For my testing, I just used the shell, and set the environment vars manually with <code>export DBUS_SESSION_BUS_ADDRESS=blahblah...</code>, etc.</p>
<p>Next, you need to launch <code>gconftool-2 --spawn</code> with those environment variables you received from <code>dbus-launch</code>. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch.</p>
<p>Then, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon.</p>
<p>I know it's complicated.</p>
<p><code>gconftool-2</code> provides a <code>--direct</code> option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually).</p>
<p><em>Edit:</em> For future reference, if anybody wants to run <code>dbus-launch</code> from within a normal <code>bash</code> script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script:</p>
<pre><code>#!/bin/bash
eval `dbus-launch --sh-syntax`
export DBUS_SESSION_BUS_ADDRESS
export DBUS_SESSION_BUS_PID
do_other_stuff_here
</code></pre>
|
<p>Well, I think I understand the question. Looks like your script just needs to start the dbus daemon, or make sure its started. I believe "session" here refers to a dbus session. <a href="http://mail.gnome.org/archives/svn-commits-list/2008-May/msg01997.html" rel="nofollow noreferrer">(here is some evidence)</a>, not a Gnome session. Dbus and gconf both run fine without Gnome.</p>
<p>Either way, faking an "active session" sounds like a pretty bad idea. It would only look for it if it needed it.</p>
<p>Perhaps we could see the script in a pastebin? I should have really seen it before making any comment.</p>
| 32,153
|
<p>I have a Prusa i3 3D printer and am using Slic3r for slicing.</p>
<p>I've noticed that my extruder is underextruding. I've correctly set the nozzle diameter and the filament diameter and I've already tried to increment the extrusion multiplier (which is currently set to 1.1). As Slic3r suggests this is a maximum value, I'm wondering if there is something else wrong.</p>
<p>Does anybody a have suggestions on which settings I can look at?</p>
<p><a href="https://i.stack.imgur.com/mYACg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mYACg.jpg" alt="enter image description here" /></a></p>
|
<p>I have a Prusa i3 pro b, and was having a similar issues. Turns out the spring for the plastic extruder feeder can be too slack. I printed <a href="https://www.thingiverse.com/thing:1936289" rel="nofollow noreferrer">these</a> at 2 mm and put it under the spring and it solved my issue.</p>
|
<p>It looks like the nozzle is too far from the bed, try leveling the bed again - that should solve the problem.</p>
| 1,710
|
<p>The print is a collapsible sword I'm using as a test. Everything seems fine on the outside, but inside it seems the segment parts of the sword inside the hilt are fusing together at the seam lines causing them to stick together.</p>
<p><strong>Model</strong>: <a href="https://thangs.com/designer/3dprintingworld/3d-model/Collapsing%20Katana-22696" rel="nofollow noreferrer">https://thangs.com/designer/3dprintingworld/3d-model/Collapsing%20Katana-22696</a></p>
<p><strong>Finished Print</strong> (looks fine)
<a href="https://i.stack.imgur.com/DZa3o.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DZa3o.jpg" alt="enter image description here" /></a></p>
<p><strong>Concentric blade pieces</strong> (fuse marks that I sheared off and broke to get out)
<a href="https://i.stack.imgur.com/peViY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peViY.jpg" alt="enter image description here" /></a></p>
<p><strong>Seams on exterior of hilt look great</strong>
<a href="https://i.stack.imgur.com/2dxXC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2dxXC.jpg" alt="enter image description here" /></a></p>
<p><strong>Print settings/info</strong></p>
<p><strong>Printer</strong>: Prusa MK3S+</p>
<p><strong>Slicer</strong>: PrusaSlicer 2.5.0a3</p>
<p><strong>Settings preset</strong>: 0.15 mm QUALITY</p>
<p><strong>Filament</strong>: Prusa PLA</p>
<p><strong>Nozzle temp</strong>: 205 °C (default is 215 °C, but lower eases stringing and has never been a problem for many past prints)</p>
<p><strong>Nozzle size</strong>: 0.4 mm</p>
<p><strong>Full config</strong>: <a href="https://pastebin.com/ECa6KkYK" rel="nofollow noreferrer">https://pastebin.com/ECa6KkYK</a></p>
|
<p>After some trial and error I found that the issue was stringing due to excess moisture in the filament from being stored outside of a sealed low-humidity container for long periods.</p>
<p>After placing it in a heated dehydrator for 2 days, my next print had low stringing and did not bond interlaced parts together significantly.</p>
|
<p>You did well to decrease the temperature. You could go even lower to 200°C
As you noticed, You really have a little bit of stringing between the elements. That's what binds the parts together. Many times when you print only a single part this will be no problem. With many nested parts, you retraction really has to be set to optimal values.</p>
<p>Try increasing the retraction distance in the slicer.</p>
| 2,178
|
<p>Are there any conflicts with having any combination of Visual Studio 2003, 2005 and/or 2008 installed? I noticed a related question <a href="https://stackoverflow.com/questions/9693/visual-studio-2005-macros-stop-working-when-visual-studio-2008-is-installed">here</a> but wanted a more general answer.</p>
|
<p>6, 2000/2001 (I can't remember which is .net 1.0), 2003, 2005, 2008... of course within .NET you may have issues with getting the right solution with the right version. I haven't really seen any conflicts in particular.</p>
|
<p>I've got 2005 and 2008 installed concurrently.</p>
<p>2008 is a superset of 2005, so I have no reason whatsoever to have them both, I just haven't gotten around to un-installing it yet</p>
| 4,892
|
<p>I would like to intercept the event in a .NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it).</p>
<p>Do you have any idea of how I can do that?</p>
|
<p>The MouseDoubleClick event of the TabControl seems to respond just fine to double-clicking. The only additional step I would do is set a short timer after the TabIndexChanged event to track that a new tab has been selected and ignore any double-clicks that happen outside the timer. This will prevent double-clicking on the selected tab.</p>
|
<p>How about subclassing the TabControl class and adding your own DoubleClick event? </p>
| 5,273
|
<p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
|
<p>Contextual imports are technically more efficient, but I think they can create other problems.</p>
<p>Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.</p>
|
<p>The performance differences between these two approaches will be very small in practice. I have never seen a case where this has made a difference that was noticeable. </p>
<p>It is worth remembering that the python interpreter will only ever do the work of parsing the module once when it is 1st imported.</p>
<p>In general you will end up with more maintainable code it you just import all the modules you need at the top of the file.</p>
| 37,888
|
<p>I print a lot of stuff, and I was thinking I could get several magnetic bed-plates and when 1 print is done simply have my wife pull the plate off and stick on clean plate and start the print again.
But a friend of mine says that won't work. Because even if the plates are made by the same manufacturer you can't guarantee the bed will be level. 〰</p>
<p>Has anyone ever tried this? </p>
|
<p>It is a question of quality:</p>
<p>You better make sure that your plates are the same thickness evenly, and level very similarly. If that can be assured, they can be swapped easily.</p>
<p>In case you have a bed leveling sensor of some sort, you might include a whole bed-leveling cycle in front of every print and exchange between numerous beds, even of slightly variant thicknesses and with dings.</p>
|
<p>Yes ,I was also facing the same problem couples of month ago and to solution I had buyed extra plates and <strong>It works perfectly</strong> . Go for the extra beds and buy only from the same manufacturer.</p>
<p>Hope your get your answer</p>
| 2,104
|
<p>SVN externals allow you to make an SVN folder appear as if it's at another location. A good use for this is having a common folder shared across all of your projects in SVN.</p>
<p>I have a /trunk/common folder in SVN that I share via several different project.</p>
<p>Example:</p>
<ul>
<li>Project1 : /trunk/project1/depends</li>
<li>Project2 : /trunk/project2/depends</li>
<li>Project3 : /trunk/project3/depends</li>
<li>Project4 : /trunk/project4/depends</li>
</ul>
<p>Each of these depends folders are empty, but have an svn:external defined to point to my /trunk/common folder. </p>
<p>The problem is when I view log within any of the projects: /trunk/projectX/ it does not show changes from the svn:externals. I am using tortoise SVN as my SVN client. </p>
<p>Does anyone know how to change this behavior? I would like for the show log of /trunk/projectX to include any changes to any defined svn:externals as well.</p>
|
<p>This is not possible with the current release of Subversion, other than explicitly calling svn log on the target of the externals directory</p>
<p>You can try issueing a feature request at <a href="http://subversion.apache.org/" rel="nofollow noreferrer">the Apache Subversion website</a></p>
|
<p>When you display the log for a local versioned folder, it will show the changes that are relative to this particular folder. Externals are only <strong>a link</strong> to a different folder on the repository. The only thing you can track about external references, from a folder which depends on this external project, is the <strong>reference definition itself</strong>. That is because the reference is a subversion property of the dependent folder.</p>
<p>Imagine you have the following repo hierarchy :</p>
<pre><code>repo
myfirstproject
trunk
mysecondproject
trunk
mycommonlib
trunk
</code></pre>
<p>and that <code>mysecondproject\trunk</code> folder has the following <em>svn:external</em> property :</p>
<pre><code>svn://mysrv/repo/mysharedlib@2451 sharedlib
</code></pre>
<p>A checkout of <em>mysecondproject\trunk</em> inside a new folder <em>secondproject</em> will create something like this on your file system :</p>
<pre><code>secondproject Folder (refers mysecondproject/trunk)
sharedlib Folder (refers mycommonlib/trunk @ revision #2451)
</code></pre>
<p>Calling "Show log" command of Tortoise from <em>secondproject</em> folder will only show <em>secondproject</em> files changes, and eventually changes that occurred on the <em>svn:external</em> property of the folder.</p>
<p>To get change log of the external project, you need to call "Show log" from the inner folder <em>sharedlib</em>, which makes sense.</p>
| 8,822
|
<p>If I notice that a hash table (or any other data structure built on a hash table) is filling up, at what point should you build a new table with more buckets. And given n items in the table so far, how do you figure out how many buckets to use in the new one?</p>
<p>So let's say I have 100 buckets. Should I reorganize it when there are 50 items in it? 500? 5000? Or should I look for the most-full bucket and key on that? Then when I hit that point how big do I make the new hash table?</p>
<p>Related to this, if you know beforehand roughly how many items will go in, is there a way to compute the number of buckets to get a good average performance?</p>
<p>I know the real answer depends on a lot of other considerations like how important is speed vs. size in a specific example, but I'm looking for general guildlines.</p>
<p>I also know that I shouldn't be optimizing this sort of thing unless good profiling has indicated that this is a bottleneck. I'm just thinking about a project that would use a lot of hash tables and wondered how to approach this.</p>
|
<p>A good rule of the thumb (not always ideal, well, just a rule of the thumb) is to re-hash if the hashtable is filled up to 80%. That means if you have 100 buckets and 80 items inside, regardless how many collision you had before, it's getting time to increase capacity.</p>
<p>How much should you increase it? Well, there is also no perfect value. Simplest solution is to double capacity on each increase. So it goes to 200, 400, 800, and so on. If you think this is too much (after all it will jump from 8 MB memory to 16 MB when the hashtable gets really large and you may never fill up the 16 MB), choose a smaller grow factor. At least 1/3 is recommend (growing it from 100 to 133) I'd say, maybe let it grow by 50% each time as a compromise.</p>
<p>Note that all this also depends how collisions are handled. A simple way to handle them (my personal favorite) is to store the items in a linked list when there is a collision. If 3 items are placed at the same key, there are still only up to 3 compares to find it. Since linked list are very ineffective for searching, you may want to increase capacity earlier, e.g. if 60% capacity is used to keep the hashtable fast. OTOH, you can do something more sophisticated and keep stats about the number of collisions. As long as you hardly have any collisions (if you have a very good hash function) there is no need to re-hash at all, even if 99% of its capacity is in use. Also if you handle collisions in a sophisticated way (e.g. each node is again a sorted table and you can perform binary search within these) your lookup might still be fast enough if the table is loaded to 200% (so you have twice as many items as capacity). In that case you could keep stats how big the largest sorted table is and when it gets bigger than, let's say, 8 entries, you think this is getting too slow and then you re-hash. </p>
<p>Re-hashing is very slow, so it should be avoided as often as possible. Thus if you need to re-hash, don't just grow capacity too little, otherwise you have to re-hash again pretty soon when adding more items. So when you need to re-hash, make the capacity significantly larger than the number of items currently in the table, everything else is too little capacity.</p>
|
<p>Depends on the type of hash table you are building. If you are using a fixed array based hash table (as opposed to linked lists for buckets), you should resize the array either when the table is full or when you have hit a max probe count (depending on whether you care more about speed or memory). If you are using linked lists, memory isn't as much of a concern since and don't have to probe for empty spaces, so resizing isn't as big of a deal.</p>
<p>The key with hash tables is the hashing algorithm, not the number of buckets. Ideally, you always want at most one item in each bucket, so you should ideally be resizing when the number of items in the hash table = the number of buckets. If your data isn't evenly distributed, you are better of with a better hash algorithm than a better resize strategy.</p>
| 27,890
|
<p>In general 3D printers are compact and smaller than RP machines. That's ok. But, what's the difference? 3D printers can be used as RP machine too.</p>
|
<p>All rapid prototyping means is automatically producing a physical part from a cad model. 3D printing is a way to achieve rapid prototyping. There are 2 main methods of rapid prototyping: additive, and subtractive.</p>
<p>A 3D printer is additive- you add materials to an object layer by layer.</p>
<p>Usually, when people talk about a subtractive machine, they are talking about a CNC mill (or lathe), which tend to be extremely large (most are over one ton). You start with all the material there, and you subtract the material that you don't want. This might be what you are thinking of.</p>
|
<p>A sintered metal printer is a version of a 3D printer that is rapid, but expensive. Seen 1 for 800,000$aud
Uses laser to melt metal particles like titanium.</p>
| 176
|
<p>C++ just sucks too much of my time by making me micro-manage my own memory, making me type far too much (hello <code>std::vector<Thingy>::const_iterator it = lotsOfThingys.begin()</code>), and boring me with long compile times. What's the single best alternative for serious real-time graphics programming? Garbage collection is a must (as is the ability to avoid its use when necessary), and speed must be competitive with C++. A reasonable story for accessing C libs is also a must.</p>
<p>(Full disclosure: I have my own answer to this, but I'm interested to see what others have found to be good alternatives to C++ for real-time graphics work.)</p>
<p><strong>Edit:</strong> Thanks everyone for the thoughtful replies. Given that there's really no "right" answer to this question I won't be selecting any particular answer. Besides I'd just pick the language I happen to like as a C++ alternative, which wouldn't really be fair.</p>
|
<p>C# is a nice language that fits your requirements, and it is definitely suited for graphics, thanks to the efforts of Microsoft to provide it with great tools and libraries like Visual Studio and XNA.</p>
|
<p>If your target is a PC, I think you can try C#, or embed <strong>Lua</strong> in your C++ app and run scripts for 'high-level' stuff. However if your target is a console, you <strong>must</strong> manage your own memory!</p>
| 9,853
|
<p>I am implementing a "locking" system in my app which protects my app against being copied and used illegally. The system checks the signature of a hardware-based code and expects it to be signed with a Private Key that only my company owns. (The app has got the Public Key to validate the signature.)</p>
<p>I want to make sure that no one changes my locking mechanism in the app, so I want to sign my app's assembly and I think it makes sense.</p>
<ol>
<li>Since I haven't seen the CLR ever talk about an assembly's signature being invalid, I want to make sure this system really works. Does it? What should I do to make it work?</li>
<li>Can an attacker concentrate his efforts on the CLR to make it not care about my signature? That is, if he can't tamper with my code because I've signed it, can he tamper with CLR?</li>
<li>Generally, I would like to know your experience about such safe-guards and protection technologies. Can any one suggest anything else?</li>
</ol>
|
<p>Assembly signing is designed to allow applications/assemblies to reference an assembly and be sure that they get the assembly they originally referenced. If someone wanted to, they could in theory decompile your entire app and recompile with no signing. (ie: they could recompile the <em>referencing assembly</em> so that it referenced an unsigned version of the <em>referenced assembly</em>).</p>
<p>They would then be able to modify the code as they wanted, because the client (exe) would now reference an unsigned (or 're-signed') dll.</p>
<p>To make the process of decompilation and recompilation more difficult, you could try creating a mixed-mode C++/CLI assembly containing both managed and native code. But yeah... ultimately people have all your binaries to hand and with enough effort can probably get round any licensing system you think up.</p>
|
<p>One technique you can use is to prevent tampering is to use the public key of your assembly to encrypt essential parts of your software such as application/algorithm parameters. If the public key has been changed, the decryption will not work and your app will crash.</p>
<p>Some obfuscators such as <a href="http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm" rel="nofollow noreferrer">Crypto Obfuscator</a> use this technique with the string encryption feature. It uses the public key of your assembly to encrypt all strings. If the public key has been changed or removed, decryption will fail and your app wont even start.</p>
| 49,448
|
<p>I'm new to ruby and I'm playing around with the IRB.</p>
<p>I found that I can list methods of an object using the ".methods" method, and that self.methods sort of give me what I want (similar to Python's dir(<strong>builtins</strong>)?), but how can I find the methods of a library/module I've loaded via include and require?</p>
<pre><code>irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
"extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>
</code></pre>
<p>I'm used to python, where I use the dir() function to accomplish the same thing:</p>
<pre><code>>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
</code></pre>
|
<p><a href="http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928" rel="noreferrer">ObjectSpace.each_object</a> could be what you are looking for.</p>
<p>To get a list of included modules you could use <a href="http://www.ruby-doc.org/core/classes/Module.html#M001697" rel="noreferrer">Module.included_modules</a>.</p>
<p>You can also check if an object responds to a method on a case-by-case basis using <a href="http://ruby-doc.org/core/classes/Object.html#M000333" rel="noreferrer">object.respond_to?</a>.</p>
|
<p>You can pass the .methods messages to the library/module even before loading it, to see all the available methods. Doing <code>self.methods</code> just returns all the methods that the Object object contains. You can see this by doing <code>self.class</code>. So let's say you want to see all the methods in the File module. You simply do <code>File.methods</code> and you'll get a list of all the methods that exist in the File module. This, perhaps, isn't what you want, but it should be somewhat helpful.</p>
| 28,295
|
<p>I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.</p>
<p>on Linux platforms i can do it by using following way.</p>
<pre><code>char exepath[1024] = {0};
char procid[1024] = {0};
char exelink[1024] = {0};
sprintf(procid, "%u", getpid());
strcpy(exelink, "/proc/");
strcat(exelink, procid);
strcat(exelink, "/exe");
readlink(exelink, exepath, sizeof(exepath));
</code></pre>
<p>Here exepath gives us the full path of the executable.</p>
<p>Similarly for windows we do it using </p>
<pre><code>GetModuleFileName(NULL, exepath, sizeof(exepath)); /* get fullpath of the service */
</code></pre>
<p>Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.</p>
|
<p>First, I'd like to comment on your Linux solution: it is about 5 times as long as it needs to be, and performs a lot of completely unnecessary operations, as well as using 1024 magic number which is just plain wrong:</p>
<pre><code>$ grep PATH_MAX /usr/include/linux/limits.h
#define PATH_MAX 4096 /* # chars in a path name */
</code></pre>
<p>Here is a correct minimal replacement:</p>
<pre><code>#include <limits.h>
...
char exepath[PATH_MAX] = {0};
readlink("/proc/self/exe", exepath, sizeof(exepath));
</code></pre>
<p>Second, on HP-UX you can use <code>shl_get_r()</code> to obtain information about all loaded modules. At index 0, you will find information about the main executable. The <code>desc.filename</code> will point to the name of the executable at <code>execve(2)</code> time.</p>
<p>Unfortunately, that name is relative, so you may have to search <code>$PATH</code>, and may fail if the application did <code>putenv("PATH=some:new:path")</code> or if the original exename was e.g. <code>./a.out</code> and the application has performed <code>chdir(2)</code> since.</p>
|
<p>I have done this before in a general case. The general idea is to grab argv[0], and do some processing on it:</p>
<pre><code>int main( int argc, char** argv )
{
string full_prog_path = argv[0];
if ( full_prog_path[0] == "/" )
{ // It was specified absolutely; no processing necessary.
}
else
{
string check_cwd = getcwd();
check_cwd += argv[0];
if ( FileExists( check_cwd ) )
{ // It was specified relatively.
full_prog_path = check_cwd;
}
else
{ // Check through the path to find it
string path = getenv( "PATH" );
list<string> paths = path.split( ":" );
foreach( test_path, paths )
{
if ( FileExists( test_path + argv[0] ) )
{ // We found the first path entry with the program
full_prog_path = test_path + argv[0];
break;
}
}
}
}
cout << "Program path: " << full_prog_path << endl;
return 0;
}
</code></pre>
<p>Obviously, this has some assumptions that might break at some point, but it should work for most cases.</p>
| 24,495
|
<p>If I am inserting elements into a wrap panel and there is still space in the panel before it overflows on the next line, can I specifically make it wrap over so that the subsequent elements are on the next line?</p>
<p>I am looking for something like this:</p>
<pre><code><WrapPanel>
<Element/>
<Element/>
<NewLine???/>
<Element/>
<Element/>
<Element/>
</WrapPanel>
</code></pre>
|
<p>This works:</p>
<pre><code><WrapPanel>
<TextBlock>1</TextBlock>
<TextBlock>2</TextBlock>
<TextBlock>3</TextBlock>
<TextBlock>4</TextBlock>
<TextBlock Width="10000" Height="0" />
<TextBlock>5</TextBlock>
<TextBlock>6</TextBlock>
</WrapPanel>
</code></pre>
<p>I have to add though... this is pretty much a hack. You might want to consider using a StackPanel, and inside of that, have a WrapPanel with the items you want to Wrap... Example:</p>
<pre><code><StackPanel>
<WrapPanel>
<TextBlock>1</TextBlock>
<TextBlock>2</TextBlock>
<TextBlock>3</TextBlock>
<TextBlock>4</TextBlock>
</WrapPanel>
<WrapPanel>
<TextBlock>5</TextBlock>
<TextBlock>6</TextBlock>
</WrapPanel>
</StackPanel>
</code></pre>
|
<p>Could just add a Margin to the control that is to be on the new line: </p>
<pre><code><TextBlock Margin="0,20,0,0">5</TextBlock>
</code></pre>
| 44,440
|
<p>I'm generating titles out of a few other fields, and want the "right" way to do:</p>
<pre><code>Me.Title.Value = Join(Array([Conference], [Speaker], partstr), " - ")
</code></pre>
<p>Except any of [conference], [speaker] or partstr might be null, and I don't want the extra "-"'s. Are there any functions that'll make this job straightforward?</p>
|
<p>Nope - you'll have to check each one and then cleanup at the end</p>
<pre><code>Dim Temp As String
If Not IsNull([Conference]) Then
Temp = Temp & [Conference] & " - "
End If
If Not IsNull([Speaker]) Then
Temp = Temp & [Speaker] & " - "
End If
If Not IsNull(partstr) Then
Temp = Temp & partstr & " - "
End If
If Temp > "" then
Me.Title.Value = Left(Temp, Len(Temp) - 3)
Else
Me.Title.Value = Null
End If
</code></pre>
<p>Revised with generic function:</p>
<pre><code>Public Function JoinEx(ByVal pArray As Variant, ByVal pDelimiter As String) As String
Dim sTemp As String
Dim iCtr As Integer
For iCtr = 0 To UBound(pArray)
If Not IsNull(pArray(iCtr)) Then
sTemp = sTemp & pArray(iCtr) & pDelimiter
End If
Next
If sTemp > "" Then
JoinEx = Left(sTemp, Len(sTemp) - Len(pDelimiter))
End If
End Function
</code></pre>
<p>Calling Example:</p>
<pre><code> JoinEx(Array("one","two","three"), " - ") 'Returns "One - Two - Three"
JoinEx(Array(null,"two","three"), " - ") 'Returns "Two - Three"
</code></pre>
|
<p>A complete re-write, and this time properly tested:</p>
<pre><code> IIf(IsNull(Partstr), IIf(IsNull(Conference), Speaker, Conference & " - " + Speaker), Conference + " - " & Speaker + " - " & Partstr)
</code></pre>
| 41,115
|
<p>Our organization has a lot of its essential data in a mainframe Adabas database. We have ODBC access to this data and from C# have queried/updated it successfully using ODBC/Natural "stored procedures".</p>
<p>What we'd like to be able to do now is to query a mainframe table from within SQL Server 2005 stored procs, dump the results into a table variable, massage it, and join the result with native SQL data as a result set.</p>
<p>The execution of the Natural proc from SQL works fine when we're just selecting it; however, when we insert the result into a table variable SQL seems to be starting a distributed transaction that in turn seems to be wreaking havoc with our connections.</p>
<p>Given that we're not performing updates, is it possible to turn off this DTC-escalation behavior? </p>
<p>Any tips on getting DTC set up properly to talk to DataDirect's (formerly Neon Systems) Shadow ODBC driver?</p>
|
<p>Check out <a href="http://msdn.microsoft.com/en-us/library/ms178549(SQL.90).aspx" rel="nofollow noreferrer"><code>SET REMOTE_PROC_TRANSACTIONS OFF</code></a> which should disable it.
Or <a href="http://msdn.microsoft.com/en-us/library/ms178532.aspx" rel="nofollow noreferrer"><code>sp_serveroption</code></a> to configure the linked server generally, not per batch.</p>
<p>Because you are writing on the MS SQL side, you start a transaction.
By default, it escalates whether it needs to or not.
Even though the table variable does not particapate in the transaction.</p>
<p>I've had similar issues before where the MS SQL side behaves differently based on if MS SQL writes, in a stored proc and other stuff. The most reliable way I found was to use dynamic SQL calls to my Sybase linked server...</p>
|
<p>I'm not sure about DTC, but DTSX (Integration Services) may be useful for moving the data. However, if you can simply query the data, you may want to look at adding a linked server for direct access. You could then just write a simple query to populate your table based on a select from the linked server's table.</p>
| 14,127
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.