instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have a laptop running Ubuntu to which I connect an external monitor when I'm at the office. Usually this requires me to run <code>xrandr --auto</code> in order for the laptop to re-size the display to match the external monitor. It would be nice if this could be done automatically, either triggered when the monitor is connected, but it would be enough to actually run <code>xrandr --auto</code> when the laptop wakes up from suspend/hibernate.</p>
<p>I created a script <code>/etc/pm/sleep.d/00xrandr.sh</code> containing the line</p>
<pre><code>xrandr --auto
</code></pre>
<p>but this fails since the script does not have access to the X display.</p>
<p>Any ideas?</p>
|
<p>I guees that the problem is that the script is being run as root, with no access to your xauth data. Depending on your setup, something like this could work:</p>
<pre><code>xauth merge /home/your_username/.Xauthority
export DISPLAY=:0.0
xrandr --auto
</code></pre>
<p>You could use something more clever to find out which user you need to extract xauth data from if you need to.</p>
|
<p>Have you tried to set the DISPLAY variable in the script correctly and granted access for other users to your DISPLAY with xhost + localhost? Don't know if that helps, but it's worth a try.</p>
| 15,720
|
<p>MS SQL Server and Oracle, which one is better in terms of scalability?<br>
For example, if the data size reach 500 TB etc.</p>
|
<p>Both Oracle and SQL Server are shared-disk databases so they are constrained by disk bandwidth for queries that table scan over large volumes of data. Products such as <a href="http://www.teradata.com/enterprise-data-warehouse" rel="nofollow noreferrer">Teradata</a>, <a href="http://www.netezza.com/products/dwa.aspx" rel="nofollow noreferrer">Netezza</a> or <a href="http://www-01.ibm.com/software/data/db2/9/edition-enterprise.html" rel="nofollow noreferrer">DB/2 Parallel Edition</a> are <a href="http://en.wikipedia.org/wiki/Shared_nothing_architecture" rel="nofollow noreferrer">'shared nothing'</a> architectures where the database stores horizontal partitions on the individual nodes. This type of architecture gives the best parallel query performance as the local disks on each node are not constrained through a central bottleneck on a SAN.</p>
<p>Shared disk systems (such as Oracle <a href="http://www.oracle.com/database/rac_home.html" rel="nofollow noreferrer">Real Application Clusters</a> or <a href="http://www.sql-server-performance.com/articles/clustering/clustering_intro_p1.aspx" rel="nofollow noreferrer">Clustered SQL Server</a> installations still require a shared <a href="http://en.wikipedia.org/wiki/Storage_area_network" rel="nofollow noreferrer">SAN</a>, which has constrained bandwidth for streaming. On a VLDB this can seriously restrict the table-scanning performance that is possible to achieve. Most data warehouse queries run table or range scans across large blocks of data. If the query will hit more than a few percent of rows a single table scan is often the optimal query plan. </p>
<p>Multiple local direct-attach disk arrays on nodes gives more disk bandwidth. </p>
<p>Having said that I am aware of an Oracle DW shop (a major european telco) that has an oracle based data warehouse that loads 600 GB per day, so the shared disk architecture does not appear to impose unsurmountable limitations.</p>
<p>Between MS-SQL and Oracle there are some differences. IMHO Oracle has better VLDB support than SQL server for the following reasons:</p>
<ul>
<li><p>Oracle has native support for <a href="http://en.wikipedia.org/wiki/Bitmap_index" rel="nofollow noreferrer">bitmap indexes</a>, which are an index structure suitable for high speed data warehouse queries. They essentially do a CPU for I/O tradeoff as they are run-length encoded and use relatively little space. On the other hand, Microsoft claim that <a href="http://www.databasejournal.com/features/mssql/article.php/1438821" rel="nofollow noreferrer">Index Intersection</a> is not appreciably slower.</p></li>
<li><p>Oracle has better table partitioning facilities than SQL Server. IIRC The table partitioning in SQL Server 2005 can only be done on a single column.</p></li>
<li><p>Oracle can be run on <a href="http://www.sun.com/servers/index.jsp?cat=Sun%20Fire%20High-End%20Servers&tab=3" rel="nofollow noreferrer">somewhat</a> <a href="http://www-03.ibm.com/systems/p/hardware/highend/595/index.html" rel="nofollow noreferrer">larger</a> <a href="http://h20341.www2.hp.com/integrity/cache/342254-0-0-0-121.html" rel="nofollow noreferrer">hardware</a> than SQL Server, although one can run SQL server on some <a href="http://www.sun.com/servers/x64/x4600/" rel="nofollow noreferrer">quite</a> <a href="http://h10010.www1.hp.com/wwpc/us/en/en/WF04a/15351-15351-3328412-241644-3328423.html" rel="nofollow noreferrer">respectably</a> <a href="http://www.unisys.com/products/enterprise__servers/high_d_end__servers/index.htm" rel="nofollow noreferrer">large</a> systems.</p></li>
<li><p>Oracle has more mature support for <a href="http://en.wikipedia.org/wiki/Materialized_view" rel="nofollow noreferrer">Materialized views</a> and <a href="http://www.oracle.com/technology/oramag/oracle/03-sep/o53business.html" rel="nofollow noreferrer">Query rewrite</a> to optimise relational queries. SQL2005 does have some query rewrite capability but it is poorly documented and I haven't seen it used in a production system. However, Microsoft will suggest that you use <a href="http://msdn.microsoft.com/en-us/library/ms175609(SQL.90).aspx" rel="nofollow noreferrer">Analysis Services</a>, which does actually support shared nothing configurations.</p></li>
</ul>
<p>Unless you have truly biblical data volumes and are choosing between Oracle and a shared nothing architecture such as Teradata you will probably see little practical difference between Oracle and SQL Server. Particularly since the introduction of SQL2005 the partitioning facilities in SQL Server are viewed as good enough and there are <a href="http://www.intelalliance.com/microsoft/assets/Allscripts%20-%20SQL%20Server%202005%20Case%20Study%2008-22-07.pdf" rel="nofollow noreferrer">plenty</a> of <a href="http://joesack.com/WordPress/?p=22#more-22" rel="nofollow noreferrer">examples</a> of <a href="http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel5/10435/33129/01559994.pdf?isnumber=33129&prod=CNF&arnumber=1559994&arSt=+42&ared=+42&arAuthor=+Cai%2C+Y.D.%3B++Aydt%2C+R.%3B++Brunner%2C+R.J." rel="nofollow noreferrer">multi-terabyte</a> systems that have been successfully implemented on it.</p>
|
<p>Oracle like a high-quality manual film camera, which needs the best photographer to take the best picture while MS SQL like an automatic digital camera. In old days, of course, all professional photographers will use film camera, now think about how many professional photographers use automatic digital camera.</p>
| 15,348
|
<p>My boss thinks the VS 2008 IDE Window Manager(autohiding, docking of Solution Explorer, Properties, etc) is the best thing since sliced bread. I can't find a control that resembles that functionality in the Toolbox. Is there a control like that available that you know of? Or should I go ahead and implement it myself? Btw, we're using VS 2008 Express.</p>
|
<p>You don't have to create something that looks <em>like</em> the VS window manager - you can use the actual VS one with the <a href="http://msdn.microsoft.com/en-us/vsx2008/products/bb933751.aspx" rel="nofollow noreferrer">Visual Studio Shell</a>.</p>
<p>I believe it's aimed at creating developer tools, but I see no reason why it would have to be used that way. It's a bit like the Eclipse RCP, as I understand it.</p>
|
<p>You should check out <a href="http://www.divil.co.uk/net/controls/sanddock/" rel="nofollow noreferrer">SandDock</a>. The older versions were freely licenced (dunno if they are still available) and the newer versions are relatively cheap, especially considering the amount of time/money/sanity they would save you.</p>
<p>I would strongly recommend against trying to roll your own VM component. There is just too much work involved, and it wouldn't be worth it, if it wasn't your primary product.</p>
| 22,520
|
<p>I was reading <em><a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html" rel="nofollow noreferrer">Java Platform Performance</a></em> (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.</p>
<p>I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that.</p>
<p>Do recent JVMs, in particular Sun's 1.6.0_07 version, still have this limitation? If so, then I have a lot of code to analyse...</p>
<p>I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC.</p>
<hr/>
<p>As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected.</p>
<p>This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope.</p>
<p>The code from the <a href="https://stackoverflow.com/a/271824/7938">chosen answer</a> illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference.</p>
<p>This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.</p>
|
<p>This code should clear it up:</p>
<pre><code>public class TestInvisibleObject{
public static class PrintWhenFinalized{
private String s;
public PrintWhenFinalized(String s){
System.out.println("Constructing from "+s);
this.s = s;
}
protected void finalize() throws Throwable {
System.out.println("Finalizing from "+s);
}
}
public static void main(String[] args) {
try {
PrintWhenFinalized foo = new PrintWhenFinalized("main");
} catch (Exception e) {
// whatever
}
while (true) {
// Provoke garbage-collection by allocating lots of memory
byte[] o = new byte[1024];
}
}
}
</code></pre>
<p>On my machine (jdk1.6.0_05) it prints:</p>
<blockquote>
<p>Constructing from main</p>
<p>Finalizing from main</p>
</blockquote>
<p>So it looks like the problems has been fixed.</p>
<p>Note that using System.gc() instead of the loop does not cause the object to be collected for some reason.</p>
|
<p>Would you really have that much code to analyse? Basically I can only see this being a significant problem for very long-running methods - which are typically just the ones at the top of each thread's stack.</p>
<p>I wouldn't be at all surprised if it's unfixed at the moment, but I don't think it's likely to be as significant as you seem to fear.</p>
| 34,165
|
<p>I've found this piece of code on <a href="http://www.koders.com/csharp/fidACD7502AA845419FF59B7DA804D3C8FCA0E40138.aspx?s=basecodegeneratorwithsite#L76" rel="nofollow noreferrer">Koders</a>:</p>
<pre><code>private ServiceProvider SiteServiceProvider
{
get
{
if (serviceProvider == null)
{
serviceProvider = new ServiceProvider(site as VSOLE.IServiceProvider);
Debug.Assert(serviceProvider != null, "Unable to get ServiceProvider from site object.");
}
return serviceProvider;
}
}
</code></pre>
<p>I'm wondering, is there <em>any</em> possible way the <code>Debug.Assert(serviceProvider != null</code> could trigger? I'm under the impression that <code>new</code> could only be aborted by an exception, in which case the assert would never be reached.</p>
|
<p>It's possible that the ServiceProvider overrides the !=/== operator, so that for an <em>invalid</em> state the comparison to null returns true.</p>
<p>Looks strange anyway.</p>
|
<p>I agree. If the normal != operator (inherited from Object) is being used, this can never happen. A constructor always returns an object reference and, as you have pointed out, if an exception was thrown in the constructor the execution point would leave the property entirely.</p>
<p>I would check what this code is intended to do. The constructor could, of course, have left the constructed object in an inconsistent state, and that is presumably what should have been tested for.</p>
<p>If your ServiceProvider class implements System.IServiceProvider, you may well want to check to make sure that GetService() does not return null.</p>
| 48,516
|
<p>Should I have background color for a form input? Or this is really a subjective matter?</p>
<p>For me personally I thought having background color for a form, kind of makes it more organized and clean.</p>
<p>What are your views on this?</p>
|
<p>Two techniques that I don't see often enough are highlighting input fields with a background color <a href="http://www.dhtmlgoodies.com/index.html?whichScript=highlight-active-input" rel="nofollow noreferrer">when they are focused while filling out a form</a> and <a href="http://blog.jc21.com/staging/jsvalidate_yui.php" rel="nofollow noreferrer">when a validation error occurs</a> after a form submission. You can use these two techniques in conjunction with a subtle style for normal inputs to match the rest of your website design.</p>
|
<p>It really depends on the layout of the rest of the site. In my opinion it's good to have the form offset somehow, even if just with top/bottom borders - often you can make the whole thing a small box within the page. For something like a registration system, though, you might as well make the entire page the form - the less distractory extra-content the better.</p>
| 28,773
|
<p>In the context of a Google App Engine Webapp framework application:</p>
<p>I want to changed the request verb of a request in the case a
parameter _method is provided, for example if a POST request comes in
with a parameter _method=PUT, I need to change the request to call the
put method of the handler. This is to cope with the way prototype.js
works with verbs like PUT and DELETE(workaround for IE). Here is my
first attempt:</p>
<pre>
class MyRequestHandler(webapp.RequestHandler):
def initialize(self, request, response):
m = request.get('_method')
if m:
request.method = m.upper()
webapp.RequestHandler.initialize(self, request, response)
</pre>
<p>The problem is, for some reason whenever the redirect is done, the
self.request.params are emptied by the time the handling method(put or
delete) is called, even though they were populated when initialize was
called. Anyone have a clue why this is? As a workaround I thought I
could clone the params at initialize() time, but .copy() did not work,
and I haven't found a way to do that either.</p>
<p><em>Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.</em></p>
|
<p>Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.</p>
<p>Instead, you have a couple of options:</p>
<ul>
<li>You can subclass webapp.WSGIApplication and override <strong>call</strong> to select the method based on _method when it exists.</li>
<li>You can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.</li>
</ul>
<p>Either way, take a look at google/appengine/ext/webapp/<strong>init</strong>.py in the SDK so you can see how it works.</p>
|
<p>Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.</p>
<p>Instead, you have a couple of options:</p>
<ul>
<li>You can subclass webapp.WSGIApplication and override <strong>call</strong> to select the method based on _method when it exists.</li>
<li>You can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.</li>
</ul>
<p>Either way, take a look at google/appengine/ext/webapp/<strong>init</strong>.py in the SDK so you can see how it works.</p>
| 31,837
|
<p>I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients?</p>
<p>I'm using TAO.</p>
|
<p>Recompilation of clients is not required (and should not be, regardless of the ORB that you use). As Adam indicated, lookups are done by operation name (a straight text comparison).</p>
<p>I've done what you're describing with our ACE/TAO-based system, and encountered no issues (servers were in ACE/TAO C++, clients were ACE/TAO C++, C# using Borland's Janeva, and OmniORBPy).</p>
|
<p>It depends on usage of new idl method.
If Corba invocation is static(SII), meaning your client is linked with stub, you have to recompile a stub if you want to use your new added method interface. </p>
<p>If corba invocation is dynamic(DII), there is no stub required for client. None of recompilation is required. In this case, your client code should be like: </p>
<pre><code> remoteObjRef->invoke("methodname", args); // send("methodname", args)
</code></pre>
<p>I did CORBA DII invocation four years ago and it works with TAO client&TAO/Jacorb/IONA corba service. </p>
| 5,750
|
<p>I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to <code>Date.toMonth()</code>, <code>Date.toYear()</code> and other deprecated <code>Date</code> methods. All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use <code>Calendar</code> methods.</p>
<p>Has Sun/Oracle actually said when these things are going away, or does <code>@deprecated</code> just mean you lose style points?</p>
|
<p>Regarding the APIs, ... it is not specified they will be removed anytime soon.</p>
<p><a href="http://java.sun.com/j2se/1.5.0/compatibility.html" rel="nofollow noreferrer">Incompatibilities in J2SE 5.0 (since 1.4.2)</a>:</p>
<p>Source Compatibility</p>
<blockquote>
<p>[...]<br>
In general, the policy is as follows, except for any incompatibilities listed further below: </p>
<p>Deprecated APIs are interfaces that are supported only for backwards compatibility. The javac compiler generates a warning message whenever one of these is used, unless the -nowarn command-line option is used. It is recommended that programs be modified to eliminate the use of deprecated APIs, <strong>though there are no current plans to remove such APIs</strong> – with the exception of JVMDI and JVMPI – entirely from the system.</p>
</blockquote>
<p>Even in its <a href="http://java.sun.com/javase/6/docs/technotes/guides/javadoc/deprecation/deprecation.html" rel="nofollow noreferrer">How and When To Deprecate APIs</a>, nothing is being said about a policy regarding actually <em>removing</em> the deprected APIs...</p>
<hr>
<p>Update 10 years later, the new <a href="https://docs.oracle.com/javase/9/core/enhanced-deprecation1.htm#JSCOR-GUID-23B13A9E-2727-42DC-B03A-E374B3C4CE96" rel="nofollow noreferrer">JDK9+ <strong>Enhanced Deprecation</strong></a> clarifies the depreciation policy.<br>
See <a href="https://stackoverflow.com/users/7641/jens-bannmann">Jens Bannmann</a>'s <a href="https://stackoverflow.com/a/50445603/6309">answer</a> for more details.<br>
This is also detailed in this blog post by <a href="https://twitter.com/vojtechruzicka" rel="nofollow noreferrer">Vojtěch Růžička</a>, following <a href="https://blog.jooq.org/2015/12/22/jep-277-enhanced-deprecation-is-nice-but-heres-a-much-better-alternative/" rel="nofollow noreferrer">criticisms on JEP 277</a>.</p>
<blockquote>
<p>The convention for JDK is that once a JDK API is marked as <code>forRemoval=true</code> in a certain Java version, <strong>it will be removed in the directly following major Java release</strong>.<br>
That means - when something is marked as <code>forRemoval=true</code> in Java 9, it is supposed to be completely removed in Java 10.<br>
<strong>Keep that in mind when using API marked for removal.</strong></p>
<p>Note that this convention applies only to JDK itself and third-party libraries are free to choose any convention they see fit.</p>
</blockquote>
|
<p>Sun tend to be extremely paranoid when it comes to changes that impact backwards compatibility, so I wouldn't expect to see the methods go away any time soon.</p>
<p>But deprecated methods <strong>could</strong> go away at any time in the future, and are normally deprecated for a reason - either because they're unreliable, because they have unpleasant side effects, or simply because there's a better or more elegant way of doing things. The JavaDoc for the method will normally detail which of these is the case and what the acceptable way of carrying out the same operation is these days. Quite frequently the deprecated method will have been replaced with an implementation that calls the 'correct' method anyway, so you're just adding a level of indirection anyway.</p>
<p>You'll also have plenty of compilation warnings if you use these methods, which could be reason enough to avoid them in itself...</p>
| 40,586
|
<p>Is there a way to take over the Entity Framework class builder? I want to be able to have my own class builder so i can make some properties to call other methods upon materialization or make the entity classes partial.</p>
|
<p>Actually they are already in partial classes. See <a href="http://msdn.microsoft.com/en-us/library/bb738612.aspx" rel="nofollow noreferrer">MSDN</a></p>
|
<p>I'll add that not only can you can tack on your own class <strong>partial classes</strong> to those emitted by the Entity Framework, but you can also write out all the <strong>partial methods</strong> created by the generated code.</p>
<p>IE. There'll be a lot of partial method code which get called but the method itself in the generated code isn't really implemented. For that you can write a partial method to catch events when properties change and such. It's not a terrible way to handle some business rules.</p>
| 6,046
|
<p>Robocopy is the best reliable and feature rich way to batch copy files on Windows. However, it is a command line tool.</p>
<p>I am looking for a library/API that I could do the same in my program. I tried to use Process.Start(), but then I have to capture and to parse stdout for progress bar and no way to the overwrite behavior.</p>
<p>For example, exclude file base on delegate function; rename file if it is older; (re)start copy based on some events.</p>
<p>I guess copy, xcopy, recursive copy and etc, should be the most frequency wheel programmers do reinvent. Are there any API/library I missed?</p>
|
<p>I realize that this is a very old post, but just in case someone stumbles upon it...</p>
<p>I wrote a wrapper for robocopy in c# called RoboSharp. It does exactly what the OP originally requested.</p>
<p><a href="https://github.com/tjscience/RoboSharp" rel="nofollow noreferrer">https://github.com/tjscience/RoboSharp</a></p>
|
<p>There seems to be some stuff out there which puts a GUI on it, e.g. <a href="http://www.microsoft.com/downloads/details.aspx?familyid=50FA5932-0685-4FE3-9605-536F39BD6C86&displaylang=en" rel="nofollow noreferrer">Synchronizing Images and Files in Windows Vista and XP Using Microsoft SyncToy</a> (forum <a href="http://forums.microsoft.com/sync/ShowForum.aspx?ForumID=2026&SiteID=75" rel="nofollow noreferrer">here</a>) and <a href="http://technet.microsoft.com/en-us/magazine/cc160891.aspx" rel="nofollow noreferrer">Utility Spotlight - Robocopy GUI</a>. I haven't found an API as yet, nor whether Robocopy exposes ActiveX-style control.</p>
<p><em>Edit</em>: The rather large online description of <a href="http://www.ss64.com/nt/robocopy.html" rel="nofollow noreferrer">Robocopy</a> says something about </p>
<blockquote>
<p>Robocopy 'Jobs' and the 'MOnitor source' option provide an alternative to setting up a Scheduled Task to run a batchfile with a RoboCopy command.</p>
</blockquote>
<p>Might help. Might not.</p>
| 47,688
|
<p>I recently wrote a webservice to be used with Silverlight which uses the ASP.net membership and roles.</p>
<p>To validate the client in the service I look at the HTTPContext.Current.User (Which works when the service is called from Silverlight)</p>
<p>However, I've been trying to call the same service from an asp.net postback. But when I step-thru to the service the HTTPContext.Current has an emplty string for the username.</p>
<p>I'm guessing there is something that I'm not doing in the web.config file which is causing the httpContext to not be sent through the proxy to my service?</p>
<p>Any ideas would be appreciated. I need to be able to validate the client somehow using asp.net membership and roles and have it work from both an asp.net client and a silverlight client.</p>
|
<p>I have solved it!</p>
<p>Looks like by default the Silverlight application was sending all the browsers cookies to the service. One of these cookies is the ".ASPXAUTH" cookie to authenticate against the membership and roles.</p>
<p>The asp.net application however was not sending the cookies to the service. To send the authorisation cookie I used the following code before calling my webservice method.</p>
<pre><code> using (OperationContextScope scope = new OperationContextScope(ws.InnerChannel))
{
HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
HttpCookieCollection cc = Page.Request.Cookies;
if (Request.Cookies[".ASPXAUTH"] != null)
{
HttpCookie aCookie = Request.Cookies[".ASPXAUTH"];
String authcookieValue = Server.HtmlEncode(aCookie.Value);
httpRequest.Headers.Add("Cookie: " + ".ASPXAUTH=" + authcookieValue);
}
// Webservice call goes here
}
</code></pre>
|
<p>Not sure how it is working from Silverlight but not ASP.Net, but for starters here is a good <a href="http://nayyeri.net/blog/use-asp-net-membership-and-role-providers-in-windows-communication-foundation/" rel="nofollow noreferrer">blog post on how to setup WCF to work with ASP.Net membership providers</a>. There are quite a few steps so this could be pretty easy to miss a setting. </p>
<p>Once you get that working correctly then I imagine both should work correctly. </p>
| 35,316
|
<p>Before I get flamed and down-voted without mercy, my company will not allow the install of .NET3.5 on non-dev machines yet (others are currently on 3.0).</p>
<p>I have a managed exe on network share that needs to be able to run from there. This is a common problem with pre-.NET3.5SP1, but I cannot figure out how to solve it. I have read <a href="https://stackoverflow.com/questions/197835/how-to-get-rid-of-security-exception">this question</a>, as well as, <a href="http://blogs.msdn.com/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx" rel="nofollow noreferrer">this article</a>, in addition to the MSDN CAS articles (which is like trying to read and understand a EULA). I cannot seem to solve this problem. </p>
<p>I've tried signing it; along with other suggestions found in the articles. The only way I've found to get it to run from the network is to make it a click-once application and publish it; which is unacceptable because it creates a bunch of different files in the published directory (which confuses our less-than-technical users) and creates entries in the Add/Remove Programs in the Control Panel.</p>
<p>I'm just a dev, so I don't have rights to set/alter machine policies and such. Can anyone give me step-by-step instructions (or point me to a easy-to-read site) on what needs to be done to enable this thing to run from the network? Is it even possible without setting machine/domain security/software policies (which I don't have access to)?</p>
<p><b>Edit</b><br>
Ok... I expected to get voted down; however, it would be really nice if people would explain why they down-voted. This is a serious question that many people seem to be having a problem with; and almost no one seems to know how to fix.</p>
|
<p>Pre 3.5 and without access to the machine itself or machine/domain policy, I think you're out of luck.</p>
<p>The brute force approach is to go to Control Panel > Administrative Tools > MS .NET Framework X.X Wizards > Adjust .NET Security on each machine and set the security level for the Local Intranet zone to FullTrust. The security risk with this approach is that now you're trusting <em>all</em> .NET code that's available on your intranet, which may not be what your organisation wants.</p>
<p>The more surgical approach is to give your .NET assemblies a strong name by signing them with your development team's private key (which can be generated by .NET). Then do a once-only install of a policy on your users' machines that trusts all assemblies signed with your team's key. Now all of your team's .NET assemblies will be fully-trusted no matter where they're physically located.</p>
|
<p>You could create an unmanaged bootstrapper that copies your .net code locally and launches it. Or you can use click once and create a shortcut in another directory to hide you other files.</p>
| 28,997
|
<p>What is the best way to refactor the attached code to accommodate multiple email addresses?</p>
<p>The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.</p>
<pre><code><html>
<head>
<script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
var validateUsername = $('#Email_Address_Status_Icon_1');
$('#Email_Address_1').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('Validating Email');
this.timer = setTimeout(function() {
if (IsEmail(t.value)) {
validateUsername.html('Valid Email');
} else {
validateUsername.html('Not a valid Email');
};
}, 200);
this.lastValue = this.value;
}
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</head>
<body>
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" ID="Email_Address_1">
<span id="Email_Address_Status_Icon_1"></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" id="Email_Address_2">
<span id="Email_Address_Status_Icon_2"></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" id="Email_Address_3">
<span id="Email_Address_Status_Icon_3"></span>
</div>
</form>
</body>
</html>
</code></pre>
|
<p>Instead of using IDs for your email fields, you can give them each a class:</p>
<pre><code><div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" class="email">
<span></span>
</div>
</code></pre>
<p>Then, instead of selecting $("#Email_Address_Status_Icon_1"), you can select $("input.email"), which would give you a jQuery wrapped set of all input elements of class email.</p>
<p>Finally, instead of referring to the status icon explicitly with an id, you could simply say:</p>
<pre><code>$(this).next("span").removeClass('error').html('Validating Email');
</code></pre>
<p>'this' would be the email field, so 'this.next()' would give you its next sibling. We apply the "span" selector on top of that just to be sure we're getting what we intend to. $(this).next() would work the same way.</p>
<p>This way, you are referring to the status icon in a relative manner.</p>
<p>Hope this helps!</p>
|
<p>Thanks! Here is the completed refactor with your suggested changes.</p>
<pre><code><script language="javascript">
$(document).ready(function() {
$('#Email_Address_1').keyup(function(){Update_Email_Validate_Status(this)});
$('#Email_Address_2').keyup(function() { Update_Email_Validate_Status(this)});
$('#Email_Address_3').keyup(function() { Update_Email_Validate_Status(this)});
});
function Update_Email_Validate_Status(field) {
var t = field;
if (t.value != t.lastValue) {
if (t.timer) clearTimeout(t.timer);
$(t).next("span").removeClass('error').html('Validating Email');
t.timer = setTimeout(function() {
if (IsEmail(t.value)) {
$(t).next("span").removeClass('error').html('Valid Email');
} else {
$(t).next("span").removeClass('error').html('Not a valid Email');
};
}, 200);
t.lastValue = t.value;
}
}
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</code></pre>
| 9,456
|
<p>Does anyone have any T4 example Templates (or links to same) that can be used to generate a Webservice?</p>
<p>I'm thinking of the fact that I guess the Webservice is not just the Vb or Cs field but also requires an appropriate asmx file.</p>
<p>I'm really not sure how to achieve this</p>
|
<p><a href="http://www.olegsych.com/2008/03/how-to-generate-multiple-outputs-from-single-t4-template/" rel="nofollow noreferrer">Oleg Sych: How to generate multiple outputs from single T4 template</a>; create another method that generates your asmx - should be pretty simple, as it's one line - and renders it to a file.</p>
<p><a href="http://www.codeplex.com/t4toolbox" rel="nofollow noreferrer">T4 Toolbox</a> also has some methods that are helpful for this. Oleg Sych's site also has other articles that will guide you through it, particularly these:</p>
<ul>
<li><a href="http://www.olegsych.com/2008/08/t4-toolbox/" rel="nofollow noreferrer">T4 Toolbox</a></li>
<li><a href="http://www.olegsych.com/2008/09/t4-tutorial-creating-complex-code-generators/" rel="nofollow noreferrer">Creating a complex code generator</a></li>
</ul>
|
<p>Perhaps <a href="http://www.codeplex.com/servicefactory" rel="nofollow noreferrer">Web Service Software Factory</a> will do what you need right out of the box. As I understand, it generates code with T4 templates you can extend.</p>
| 28,849
|
<p>Is there any way to generate project docs during automated builds? </p>
<p>I'd like to have a single set of source files (HTML?) with the user manual, and from them generate:</p>
<ul>
<li>PDF document</li>
<li>CHM help </li>
<li>HTML version of the help</li>
</ul>
<p>The content would be basically the same in all three formats.</p>
<p>Currently I'm using msbuild and CCNET, but I could change that if needed.</p>
|
<p>Yes!</p>
<ul>
<li>Use <a href="http://www.codeplex.com/SHFB" rel="nofollow noreferrer">SandCastle</a> to build CHM/HTM documentation of the APIs.</li>
<li>Use <a href="http://www.docbook.org/" rel="nofollow noreferrer">DocBook</a> + <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">FOP</a> and other tools to produce other kinds of documentation in PDF, RTF, HTML etc...</li>
</ul>
<p>They can be easily integrated with CruiseControl.NET through <a href="http://nant.sourceforge.net/" rel="nofollow noreferrer">NAnt</a>.</p>
|
<p>I've had an experience with Doxygen. It is nice and easy, but it makes you want overcommenting the code to ease later documetation work. </p>
| 13,929
|
<p>Last time I create WAS profile and WASService then I try to config and run many script for learn how to config WAS, Finally it crash so i use wasprofile delete this profile and forgot delete WASService.</p>
<p>Now I found IBM Webphere Application Server service display in services.msc list, so I tried to delete it with <code>WASService.exe</code> -remove command and windows <code>SC</code> command but I got message</p>
<pre><code>C:\Program Files\IBM\WebSphere\AppServer\bin>sc delete "IBMWAS61Service - DEV"
[SC] DeleteService FAILED 1072:
The specified service has been marked for deletion.
</code></pre>
|
<p>make sure the service is stopped, the services control panel is closed, and no open file handles are open by the service. </p>
<p>Also make sure ProcessExplorer is not running.</p>
|
<p>One situation where this can also happen is if there is some other service or application that is holding open a service handle obtained with OpenService. For example, a monitoring service that starts and stops services based on some external event can keep open handles to each of the services it monitors. In this case, uninstalling the service would leave it in the "marked for deletion" state until all handles obtained with OpenService are closed.</p>
| 39,225
|
<p>I'm looking for a pre-written component (w/source) for a Delphi project that I'm working on, to generate mind-maps / concept-maps similar to these:</p>
<p><a href="http://en.wikipedia.org/wiki/Image:MindMeister_screenshot_OS_X.jpg" rel="noreferrer">http://en.wikipedia.org/wiki/Image:MindMeister_screenshot_OS_X.jpg</a>
<a href="http://en.wikipedia.org/wiki/Image:XMIND_2008_in_Windows_Vista.png" rel="noreferrer">http://en.wikipedia.org/wiki/Image:XMIND_2008_in_Windows_Vista.png</a></p>
<p>Any ideas?</p>
|
<p>As a former Delphi developer, I sympathize. It used to be that you could find a free component with source for just about anything. You probably know about the <a href="http://delphi.icm.edu.pl/" rel="nofollow noreferrer">Delphi Super Page</a> (my old go-to source for everything Delphi). I looked; no mind-mapping components, there. (Of course, the site has not been updated in about 2 years).</p>
<p>I do have a suggestion, though, but it's not optimal: <a href="http://staruml.sourceforge.net/en/" rel="nofollow noreferrer">StarUML</a> was written in Delphi, and it contains custom components for creating UML diagrams. The source is available for download, and it seems to me that the UML primitives (boxes, lines, clouds and such) could be adapted to your purpose. The web site is <a href="http://staruml.sourceforge.net/en/" rel="nofollow noreferrer">http://staruml.sourceforge.net/en/</a>.</p>
<p>I know it's not ideal, but at least you would not have to start from scratch. </p>
<p>Good luck!</p>
|
<p>JVCL : Demo called
JvDesignerDemo</p>
| 3,440
|
<p>When using one's own iPhone for development it's easy enough to access any crash logs via XCode->Organizer->Crash Logs.</p>
<p>How does one access crash logs on another person's phone if they don't have it set up for development in XCode, as would likely be the case if you were distributing your app to them via ad hoc distribution for beta testing?</p>
|
<p>Two ways:</p>
<ul>
<li><p>iTunes syncs all crash reports during a regular sync. They can be found in Library/Logs/CrashReporter/MobileDevice on a Mac and probably somewhere in %APPDATA% on Windows.</p></li>
<li><p><strike> You can use the <a href="http://www.apple.com/downloads/macosx/apple/application_updates/iphoneconfigurationutility101formacosx.html" rel="noreferrer">iPhone Configuration Utility for Mac OS X</a> on any Mac to access the phone's console and crash logs. Note: <em>the iPhone Web Configuration Utility, which is available for Windows and Mac (note the "web" in the name) <strong>does not</strong> allow this kind of access and only provides a portion of the Configuration Utility's features</em>. </strike> Er, no you can't. Xcode provides this facility in the Organizer (from the Window menu), but not iPCU.</p></li>
</ul>
|
<p>On an iPhone 5, you do not need to connect the iPhone to iTunes to see the logs. Not sure about other iPhone versions but you can get to the logs by opening up Settings and then navigating to:</p>
<p>Settings -> General -> About -> Diagnostics & Usage -> Diagnostics & Usage Data</p>
<p>For the app you are looking for all crash logs should be in this area as:</p>
<p>-.ips</p>
<p>Not 100% sure if this works only for ad hoc apps or not. I think it works for any apps.</p>
| 20,694
|
<p>I noticed that there is one change about ASP.NET Routing. I cannot understand why such change.</p>
<p>In ASP.NET MVC Preview, the routing setting in Global.ascx is like "[controller]/[action]/[id]". Now, it is changed to be "{controller}/{action}/{id}". Why change [] to {} ? Is there some necessity to do that?</p>
|
<p>Wow, that happened a long while ago. Someday, I hope that the string class itself is augmented with named formats. Then this move will look like a very prescient move. We liked its similarity and consistency with string.format. Also, it is consistent with the UriTemplate format string.</p>
|
<p>In a route, you define placeholders (referred to as URL parameters) by enclosing them in braces ( { and } ). The / character is interpreted as a delimiter when the URL is parsed. </p>
<p>So now why they changed their code for parsing placeholders from [ ] to { } is something which the developers would know better!!! </p>
| 44,095
|
<p>Is it possible to build a .dmg file (for distributing apps) from a non-Mac platform?
And if yes, how?</p>
|
<p>Yep, mkfs.hfsplus does it.</p>
<pre><code>dd if=/dev/zero of=/tmp/foo.dmg bs=1M count=64
mkfs.hfsplus -v ThisIsFoo /tmp/foo.dmg
</code></pre>
<p>This creates a dmg file (in this case 64M) that can be mounted on a mac. It can also be mounted on linux, with something like</p>
<pre><code>mount -o loop /tmp/foo.dmg /mnt/foo
</code></pre>
<p>after wich you just copy the content you want to it (in /mnt/foo). Unmount it, and the dmg can be copied over to a mac and mounted there.</p>
|
<p>If you're distributing Mac apps, then surely you have a Mac to write and test them. Why not simply use that same Mac to create the disk image?</p>
<p>[Edit] Alternatively, if you're distributing a portable app, for example a Java .jar file, why bother with a disk image? Macs understand .zip and .tar.gz archives just fine.</p>
<p>I guess what I'm getting at is, I don't understand how one might need a DMG disk image, but not have a Mac with which to create it.</p>
| 36,396
|
<p>There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.</p>
<p>Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)</p>
|
<p>I'm not sure, whether this is considered a workaround, because you already referred to it in your question. You can use <a href="http://tools.hibernate.org/" rel="noreferrer">Hibernate Tools</a> to generate DDL from JPA annotated classes. You just need hibernate tools and its dependencies on the classpath and should be fine with something like the following:</p>
<pre><code><target name="schemaexport" description="Export schema to DDL file"
depends="compile-jpa"> <!-- compile model classes before running hibernatetool -->
<!-- task definition; project.class.path contains all necessary libs -->
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="project.class.path" />
<hibernatetool destdir="export/db"> <!-- check that directory exists -->
<jpaconfiguration persistenceunit="myPersistenceUnitName" />
<classpath>
<!--
compiled model classes and other configuration files don't forget
to put the parent directory of META-INF/persistence.xml here
-->
</classpath>
<hbm2ddl outputfilename="schemaexport.sql" format="true"
export="false" drop="true" />
</hibernatetool>
</target>
</code></pre>
<p>On the other hand, if you are using Eclipse with Webtools and have configured the project settings correctly, you can just right click and select <em>Generate DDL</em> from the context menu. More information about that on the <a href="http://www.eclipse.org/webtools/dali/" rel="noreferrer">Eclipse Dali website</a>.</p>
|
<p>Here's an explaination of how to use the hibernate SchemaExport class to do what you want. Similar to the anttask method mentioned before, but not everyone uses ant. You can execute this example code right from the commandline.</p>
<p><a href="http://jandrewthompson.blogspot.com/2009/10/how-to-generate-ddl-scripts-from.html" rel="nofollow noreferrer">http://jandrewthompson.blogspot.com/2009/10/how-to-generate-ddl-scripts-from.html</a></p>
<p>Hope this helps.</p>
| 35,681
|
<p>Has anyone managed to get subsonic or a variant working on Windows Mobile? We cant get it to work as it has a dependency on System.Configuration.</p>
<p>Any suggestions on an alternate ORMs that would work on a windows mobile device?</p>
|
<p>A colleague of mine used <a href="http://www.entityspaces.net" rel="nofollow noreferrer">EntitySpaces</a> on a Windows Mobile project and was pretty pleased with it.</p>
|
<p>You could look at something like <a href="http://www.llblgen.com/pages/features.aspx" rel="nofollow noreferrer">LLBLGEN</a> which shows support for the compact framework.</p>
| 31,561
|
<p>I am trying to format some bad html to output into a pop window. The html is stored in a field in a mysql database.</p>
<p>I have been performing json_encode and htmlspecialchars on the row in the php like so:</p>
<pre><code>$html = htmlentities(json_encode($row2['ARTICLE_DESC']));
</code></pre>
<p>and calling my makewindows function, which simply takes the html as a paramter and uses it withdocument.write like so:</p>
<pre><code> <p><a href='#' onclick=\"makewindows('".$html."'); return false;\">Click for full description </a></p>
</code></pre>
<p>This works ok, as in some html code is produced, such as the following:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22823&seen=true&wrap=on&langoverride=html4strict" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22823&seen=true&wrap=on&langoverride=html4strict</a></p>
<p>pasted there because I do not know how to wrap lines in SO</p>
<p>The problem is that htmlspecialchars does not seem to be stripping bad html data, as no popup window is created. The error I receive with firebug is</p>
<p>missing ) after argument list</p>
<p>However the html is outside of my control.</p>
<p>From what I have read, I am taking the correct steps. If I am missing something out, what is it?</p>
<p>My full make windows function:</p>
<pre><code>function makewindows(html){
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
</code></pre>
|
<p>You shouldn't have the single quotes in the function call. It should look like this:</p>
<pre><code><p><a href='#' onclick=\"makewindows(" . $html . "); return false;\">Click for full description </a></p>
</code></pre>
<p>Then the output will look like</p>
<pre><code><p><a href='#' onclick="makewindows(&quot;.....&quot;); return false;">Click for full description </a></p>
</code></pre>
<p>which is correct.</p>
|
<p>Try it the following way:</p>
<pre><code>$html = htmlentities(json_encode($row2['ARTICLE_DESC']),ENT_QUOTES);
</code></pre>
<p>I think the single quotation marks are not escaped by default.
Nevertheless I recommend you saving the html in a JavaScript variable before opening the window.</p>
| 48,928
|
<p>Has anyone found a good method of mocking out ADO.Net Data Service calls from a Silverlight application? </p>
<p>The power of Data Services seems to be the use of linq, client side, over entities. However when testing the objects that do the data access how can you mock out the service?</p>
<p>One way is to create an entire mock Data Service, but then all the objects would need to be recreated.</p>
<p>Are there any mocking frameworks that can help?</p>
|
<p>I understand, but one of the advantages of using ADO.Net Data Services appears to be that you get your entity objects for free. But if you can't mock the service it's calling this doesn't help.</p>
<p>Maybe one way is to pass in a different uri, but it would presumably still not all the same objects?</p>
<p>If you end up writing new interfaces or facades to hide the objects it feels like you've lost everything that has been gained?</p>
|
<p>I understand, but one of the advantages of using ADO.Net Data Services appears to be that you get your entity objects for free. But if you can't mock the service it's calling this doesn't help.</p>
<p>Maybe one way is to pass in a different uri, but it would presumably still not all the same objects?</p>
<p>If you end up writing new interfaces or facades to hide the objects it feels like you've lost everything that has been gained?</p>
| 39,205
|
<p>I work in VBA, and want to parse a string eg</p>
<pre><code><PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<X>24.365</X>
<Y>78.63</Y>
</PointN>
</code></pre>
<p>and get the X & Y values into two separate integer variables.</p>
<p>I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.</p>
<p>How do I do this?</p>
|
<p>This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.</p>
<p>You can find more on MSXML2.DOMDocument at the following sites:</p>
<ul>
<li><a href="https://web.archive.org/web/20161217090033/http://en.allexperts.com/q/XML-1469/Manipulating-XML-files-Excel.htm" rel="noreferrer">Manipulating XML files with Excel VBA & Xpath</a></li>
<li>MSXML - <a href="http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx</a></li>
<li><a href="https://web.archive.org/web/20161030020427/http://www.xml.com:80/lpt/a/979" rel="noreferrer">An Overview of MSXML 4.0</a></li>
</ul>
|
<p>Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.</p>
<pre><code>Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")
</code></pre>
<p>And the result line E1 will have your parsed value:</p>
<pre><code>Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365
</code></pre>
| 3,245
|
<p>I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.</p>
|
<p>Basically, dynamic binding means that the address for a function call is not hard-coded into the code segment of your program when it's translated into assembly language, and is instead obtained from elsewhere, i.e. stack variables, array lookups, etc.</p>
<p>At a higher level, if you have a line of code:</p>
<pre><code>foo(bar) //Calls a funciton
</code></pre>
<p>If it can be known at compile time exactly what function this will call, this is static binding. If foo could mean multiple functions depending on things not knowable at compile time, this is dynamic binding.</p>
|
<p>I understand it being evident in polymorphism. Typically when creating multiple classes that derive from a base class. If each one of the derived classes contains a function that each one uses. The base class can be used to execute a function of the derived classs and it will be properly call the correct function.</p>
<p>For example:</p>
<pre><code>class Animal
{
void talk();
}
class Dog extends Animal
{
public void talk() { System.out.println("woof"); }
}
class Cat extends Animal
{
public void talk() { System.out.println("meow"); }
}
....
Animal zoo[2];
zoo[0] = new Dog();
zoo[1] = new Cat();
for(Animal animalToggle: zoo)
{
animalToggle.talk();
}
</code></pre>
<p>will print:
woof
meow</p>
<p>My interpretation hopefully it helps.</p>
| 32,130
|
<p>Does anyone know if it is possible to embed a file open dialog inside your own form?</p>
<p>We have a tabbed dialog and on one of the tabs we want the user to be able to browse for a file with the same functionality as the the standard open dialog e.g. 'Look in' combobox, places bar, shell file list, file name comboedit with name completion etc etc.</p>
<p>I've looked at recreating the dialog with some 3rd party components, namely <a href="http://www.jam-software.com/shellbrowser_delphi/components.shtml" rel="nofollow noreferrer">Jam Shell Browser Components</a> </p>
<p>I can get most of the functionality this way, but I'm missing a couple of things e.g. the places bar and the filename auto completion\suggestion</p>
|
<p>I don't want to say it's impossible but considering the amount of ugly winapi hacks you'd probably involve I suggest "recreating the dialog with some 3rd party components" but with <strike><a href="http://www.mustangpeak.net/" rel="nofollow noreferrer">VirtualShellTools</a></strike>.<br>
VirtualShellTools can be downloaded from <a href="http://www.mswil.ch/websvn/listing.php?repname=devphp&path=/component/VirtualShellTools/&opt=dir&sc=1" rel="nofollow noreferrer">this SVN archive</a>.<br>
And <a href="https://code.google.com/p/mustangpeakvirtualshelltools/" rel="nofollow noreferrer">here's the google code project page</a>.</p>
<p>(At least it has the filename autocompletion combobox though i am not sure if it has the places bar). Hope it helps.</p>
|
<p>I would re-create it: it shouldn't take long with the VCL Components. The autocomplete is not hard, and you can get the rest of the data if you look through the windows docs long enough.</p>
<p>You can try and cheat by detecting the tab change and displaying the open dialog as if it were the tab page. You will have to detect the user clicking outside of the dialog (e.g. on a different tab) and prevent it closing until you want to change tabs.</p>
<p>Cheers</p>
| 34,294
|
<p>In our office, we regularly enjoy some rounds of foosball / table football after work. I have put together a small java program that generates random 2vs2 lineups from the available players and stores the match results in a database afterwards.</p>
<p>The current prediction of the outcome uses a simple average of all previous match results from the 4 involved players. This gives a very rough estimation, but I'd like to replace it with something more sophisticated, taking into account things like:</p>
<ul>
<li>players may be good playing as attacker but bad as defender (or vice versa)</li>
<li>players do well against a specific opponent / bad against others</li>
<li>some teams work well together, others don't</li>
<li>skills change over time</li>
</ul>
<p>What would be the best algorithm to predict the game outcome as accurately as possible?</p>
<p>Someone suggested using a neural network for this, which sounds quite interesting... but I do not have enough knowledge on the topic to say if that could work, and I also suspect it might take too many games to be reasonably trained.</p>
<p>EDIT:<br>
Had to take a longer break from this due to some project deadlines. To make the question more specific:</p>
<p>Given the following mysql table containing all matches played so far:</p>
<pre><code>table match_result
match_id int pk
match_start datetime
duration int (match length in seconds)
blue_defense int fk to table player
blue_attack int fk to table player
red_defense int fk to table player
red_attack int fk to table player
score_blue int
score_red int
</code></pre>
<p>How would you write a function predictResult(blueDef, blueAtk, redDef, redAtk) {...}<br>
to estimate the outcome as closely as possible, executing any sql, doing calculations or using external libraries?</p>
|
<p>Use the TrueSkill algorithm, it is very good at this. I've implemented it for foosball and chess and it works very well. Coworkers have told me that it's almost <em>too</em> good at this.</p>
<p>For complete details on how it works as well as a link to my implementation, see my "<a href="http://www.moserware.com/2010/03/computing-your-skill.html" rel="noreferrer">Computing Your Skill</a>" blog post.</p>
|
<p>Try applying Naive Bayes classifier.</p>
<blockquote>
<p>Bayesian learning is a probabilistic
approach which is based on an
assumption that the quantities of
interest are governed by probability
distributions and that optimal
decisions can be made by reasoning
about these probabilities together
with observed data. [Mitchell, T.
(1997), Machine Learning]</p>
</blockquote>
<p>The same exact distribution of the players may result in different match results. If your data has a pattern in it, a pattern based on your variables, Naive Bayes classifier may produce good results.</p>
<p>The algorithm is not very complex. I think, one with some knowledge in probability, can understand & apply it.</p>
<p>In intrusion detection systems, it is being used for determining network anomalies, by looking at various network parameters. Bayesian approach may be very successful in particular types of data and produce high TP & low FP rates. But it may also result in high FP rates, depending on your data. Your data will determine the best approach.</p>
<p>You can use Weka (<a href="http://www.cs.waikato.ac.nz/~ml/weka/" rel="nofollow noreferrer">http://www.cs.waikato.ac.nz/~ml/weka/</a>), a data mining software library, and try different algorithms. It contains the Naive Bayes classifier.
Just try and see.</p>
| 32,756
|
<p>In most of the commercial jobs I've had to date, my role has mostly been confined to "writing the code", whereas the reason I wanted to get into development in the first place was because I enjoyed usability and design aspect of software.</p>
<p>I feel a bit dissalusioned now, because now, pretty much all my working day is spend "plugging things together". It seems like the most mundane work imaginable and it's no surprise programmers tend to be looked down upon in some industries if that's all people think we're capable of.</p>
<p>To get to my question - are there any jobs out there for developers who want a bit of creative control? For developers who aren't just code monkeys, but who want to build a beautiful product and be heavily involved, not just in the code, but in the whole design and vision of the product?</p>
|
<p>Yes, the jobs exist; and they're not that hard to get into. The thing that I've found is that those opportunities, though, are at the smaller companies.</p>
<p>In general, larger companies have more of a "structure" in place, where the senior people do the design, and then the implementation trickles down. Generally, design is considered to be a much more "senior" activity, and with good reason, because only with experience can you learn what makes a good design.</p>
<p>But in smaller companies, there's a much less solid and fixed strata; and even in junior positions in small companies, you can have a significant amount of input into design. Particularly if you show interest and skill.</p>
<p>My recommendation would be to find a position at a smallish sort of company; there'll almost certainly be an opportunity for you to use your design skills there.</p>
|
<p>It sounds like you might be happiest starting your own software company, or at least working on your own projects in your spare time.</p>
| 39,046
|
<p>I have a script that needs to extract data temporarily to do extra operations on it, but then doesn't need to store it any further after the script has run. I currently have the data in question in a series of temporary local tables (CREATE TABLE #table), which are then dropped as their use is completed. I was considering switching to physical tables, treated in the same way (CREATE TABLE table), if there would be an improvement in the speed of the script for it (or other advantages, maybe?).</p>
<p>...So, is there a difference in performance, between temporary tables and physical tables? From what I'm reading, temporary tables are just physical tables that only the session running the script can look at (cutting down on locking issues).</p>
<p>EDIT: I should point out that I'm talking about physical tables vs. temporary tables. There is a lot of info available about temporary tables vs. table variables, e.g. <a href="http://sqlnerd.blogspot.com/2005/09/temp-tables-vs-table-variables.html" rel="nofollow noreferrer"><a href="http://sqlnerd.blogspot.com/2005/09/temp-tables-vs-table-variables.html" rel="nofollow noreferrer">http://sqlnerd.blogspot.com/2005/09/temp-tables-vs-table-variables.html</a></a>.</p>
|
<p>Temporary tables are a big NO in SQL Server.</p>
<ul>
<li>They provoke query plan recompilations which is costly.</li>
<li>Creating and dropping the table are also costly operations that you are adding to your process.</li>
<li>If there is a big amount of data going to the temporary data your operations will be slow on the lack of indexes. You CAN create indexes on temporary tables. But I will never recommend a temporary table for anything with a big amount of records.</li>
</ul>
<p>Your other approach: To create and then drop regular tables just creates the same overhead.</p>
<p>Another approach: Using existing tables, augmenting the rows with an additional column to differentiate which rows pertain to each user/session could be used. Removes the burden to create/drop the tables but, then, you will need to be paranoid with the code that generate the value to differentiate the rows AND you will have to develop a way to maintain the table for those cases where a session ended prematurely and there are leftovers (rows that were not removed at the end of the processing).</p>
<p>I recommend you to rethink your processing strategy. Some alternatives are as easy as using correlated queries, derived tables or table variables. Take a look at: <a href="http://www.sql-server-performance.com/articles/per/temp_tables_vs_variables_p1.aspx" rel="nofollow noreferrer">http://www.sql-server-performance.com/articles/per/temp_tables_vs_variables_p1.aspx</a></p>
<hr>
<p><strong>Edit:</strong> The approach of creating and dropping regular tables and the approach of reusing a regular table augumented with an additional field: Both will generate query plan recompilations because the amount of data changed will trigger the reevaluation of table statistics. Again, your best approach is to find alternate ways to proccess your data.</p>
|
<p>For MySql at least, the only time savings you are going to get is the time savings of actually creating the temporary table. AFAIK all the tables are treated the same on disk, they just happen to go away at the end of your session. This is what I have seen in practice as well. Again, this is mysql 4.x and 5.x</p>
| 27,106
|
<p>In my current environment, we have a "clean" build machine, which has an exact copy of all committed changes, nothing more, nothing less.</p>
<p>And of course I have my own machine, with dozens of files in an "in-progress" state.</p>
<p>Often I need to build my application with only one change in place. For example, I've finished task ABC, and I want to build an EXE with <em>only</em> that change.</p>
<p>But of course I can't commit the change to the repository until it's tested.</p>
<p>Branching seems like overkill for this. What do you do in your environment to isolate changes for test builds and releases?</p>
<p>@Matt b: So while you wait for feedback on your change, what do you do? Are you always working on exactly one thing?</p>
|
<p>So you are asking how to handle working on multiple "tasks" at once, right? Except branching.</p>
<p>You can have multiple checkouts of the source on the local machine, suffixing the directory name with the name of the ticket you are working on. Just make sure to make changes in the right directory, depending on the task...</p>
<p>Mixing multiple tasks in one working copy / commit can get very confusing, especially if somebody needs to review your work later.</p>
|
<p>I prefer to make and test builds on my local machine/environment before committing or promoting any changes. </p>
<p>For your specific example, I would have checked out a clean copy of the source before starting task ABC, and after implementing ABC, created a build locally with that in it.</p>
| 7,608
|
<p>I would like to get a green tombow PITS adhesive stick. On Rakuten, it costs \$1 (USD). On my 3d printer's (XYZ) retailer's site, it costs \$20 (USD). Due to the costs and the fact that Rakuten does not ship to my country, I need an alternative. I am currently using Davinci 1.0 for my bed, which I believe is a glass bed. So, my questions are: </p>
<ol>
<li>What glue is best for PLA plastic?</li>
<li>What glue is best for ABS plastic?</li>
<li>Is there a glue that functions with both types of plastic?</li>
</ol>
|
<p>As mentioned by Matt - PVA glues work perfect for both filaments.
It works well because it's softening temperature is between 45..85C so it's more or less temperature of HB.</p>
<p>Advantages:</p>
<ul>
<li>cheap</li>
<li>easy to apply on HB</li>
<li>can be applied on cold as same as on hot HB</li>
<li>sticks model very well</li>
<li>non toxic, no solvent, odorless</li>
<li>easy to wash (from HB) (just wash it under water or scrape with sharp tool)</li>
<li>works very well even with old and dry layer of glue</li>
</ul>
<p>Disadvantages:</p>
<ul>
<li>quite hard to detach model (I use paper knife)</li>
<li>first layer is not glass-perfect</li>
<li>after detaching, model is a bit sticky (first layer)</li>
</ul>
<p>I use Scotch Glue Stick by 3M. </p>
|
<p>Most PVA glue works well for both (Poly Vinyl Acetate).<br>
There are different brands in every country.</p>
| 280
|
<p>I have a session class that needs to store session information in a MySQL database. Obviously I will need to query the database in the methods of this class. In general I may need to connect more than one database simultaneously and may or may not be connected to that database already. </p>
<p>Given that, what's the best way to access databases for the session class or any class for that matter. Would creating a class to manage connections make sense?</p>
|
<p>I'd advise to check out this presentation, among other things it talks about best practices when accessing database:</p>
<p><a href="http://laurat.blogs.com/talks/best_practices.pdf" rel="nofollow noreferrer">http://laurat.blogs.com/talks/best_practices.pdf</a></p>
|
<p>Database Connections are a prime example of when and where you can safely use a Singleton pattern; however, if you know that the Session Object will be a global object and it will be the only place that you need to create Database Connections, you could pretty safely store the db connections as instance members of the Session Class.</p>
| 31,166
|
<p>I have two collections of the same object, <code>Collection<Foo> oldSet</code> and <code>Collection<Foo> newSet</code>. The required logic is as follow:</p>
<ul>
<li>if <code>foo</code> is in(*) <code>oldSet</code> but not <code>newSet</code>, call <code>doRemove(foo)</code></li>
<li>else if <code>foo</code> is not in <code>oldSet</code> but in <code>newSet</code>, call <code>doAdd(foo)</code></li>
<li>else if <code>foo</code> is in both collections but modified, call <code>doUpdate(oldFoo, newFoo)</code></li>
<li>else if <code>!foo.activated && foo.startDate >= now</code>, call <code>doStart(foo)</code></li>
<li>else if <code>foo.activated && foo.endDate <= now</code>, call <code>doEnd(foo)</code></li>
</ul>
<p>(*) "in" means the unique identifier matches, not necessarily the content.</p>
<p>The current (legacy) code does many comparisons to figure out <code>removeSet</code>, <code>addSet</code>, <code>updateSet</code>, <code>startSet</code> and <code>endSet</code>, and then loop to act on each item.</p>
<p>The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info:</p>
<ul>
<li>As far as I know, the <code>oldSet</code> and <code>newSet</code> are actually backed by <code>ArrayList</code></li>
<li>Each set contains less than 100 items, most likely max out at 20</li>
<li>This code is called frequently (measured in millions/day), although the sets seldom differ</li>
</ul>
<p>My questions:</p>
<ul>
<li>If I convert <code>oldSet</code> and <code>newSet</code> into <code>HashMap<Foo></code> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion?</li>
<li>Would iterating the two sets and perform the appropriate operation be more efficient and concise?</li>
</ul>
|
<p>Apache's commons.collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.</p>
<p>The org.apache.commons.collections.CollectionUtils API docs are <a href="http://commons.apache.org/proper/commons-collections/javadocs/api-4.0/index.html" rel="noreferrer">here</a>.</p>
|
<p>For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.</p>
| 4,341
|
<p>What options are available for receiving instant alerts from web applications? </p>
<p>I have a time sensitive web application I need to tend to (approving expediated purchase order requests). I have thought of being notified by e-mail and SMS. </p>
<p>Are there any programs to let my website send a popup window directly to my screen? Or any other instant notification options?</p>
|
<p>If you have your application open and you want a popup to appear, you could have a javascript timer that does an ajax style poll of your server every so often to see if there is a notification it needs to post. You could then throw up a pop up with the notification?</p>
|
<p>You could also have an RSS feed tying into the application that would publish an update as soon as something occurred. Granted that would require you to have an RSS reader constantly pinging the application.</p>
<p>Similarly, if you use the log4j/log4net framework, you can log a "fatal" or other special event for these actions and configure the appender to notify you via SMS, e-mail, etc.</p>
<p>...ooh, come to think of it. If you are using a .NET based app, log4net has a NetSendAppender that "Writes logging events to the Windows Messenger service. These messages are displayed in a dialog on a users terminal."</p>
| 13,032
|
<p>I'm writing some RSS feeds in PHP and stuggling with character-encoding issues. Should I utf8_encode() before or after htmlentities() encoding? For example, I've got both ampersands and Chinese characters in a description element, and I'm not sure which of these is proper:</p>
<pre><code>$output = utf8_encode(htmlentities($source)); or
$output = htmlentities(utf8_encode($source));
</code></pre>
<p>And why?</p>
|
<p>It's important to pass the character set to the htmlentities function, as the default is ISO-8859-1:</p>
<pre><code>utf8_encode(htmlentities($source,ENT_COMPAT,'utf-8'));
</code></pre>
<p>You should apply htmlentities first as to allow utf8_encode to encode the entities properly.</p>
<p>(EDIT: I changed from my opinion before that the order didn't matter based on the comments. This code is tested and works well).</p>
|
<p>After much trial & error, I finally found a way to properly display a string from a utf8-encoded database value, through an xml file, to an html page:</p>
<pre><code>$output = '<![CDATA['.utf8_encode(htmlentities($string)).']]>';
</code></pre>
<p>I hope this helps someone.</p>
| 39,594
|
<p>Has anyone else run into this problem before? I've got a method that calls a generic method with a delegate, inside of a generic class. I've marked the class as Serializable, and it serializes without complaint. But, when I try to deserialize an object of this class, it pegs the CPU and hangs the machine.</p>
<p>Code example:</p>
<pre><code>public delegate T CombinationFunctionDelegate<T,U,V>(U a, V b);
[Serializable]
public class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public SDictionary()
: base()
{
}
protected SDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
public List<ListItem> ToListItems()
{
return Convert(delegate(TKey key, TValue value)
{
return new ListItem(key.ToString(), value.ToString());
});
}
public List<U> Convert<U>(CombinationFunctionDelegate<U, TKey, TValue> converterFunction)
{
List<U> res = new List<U>();
foreach (TKey key in Keys)
res.Add(converterFunction(key, this[key]));
return res;
}
}
</code></pre>
<p>I can put an instance of this class into ViewState (for example) just fine, but when I try to extract the object from ViewState again, the CPU on the machine spikes and the deserialization call never returns (ie, infinite loop).</p>
<p>When I remove the ToListItems() method, everything works wonderfully. Is this really weird, or do I just not understand serialization? =)</p>
|
<p>This is the code I currently have, which works fine?</p>
<pre><code> [Serializable]
public class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public SDictionary()
: base()
{
}
protected SDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public List<ListItem> ToListItems()
{
return this.Convert(delegate(TKey key, TValue value)
{
return new ListItem(key.ToString(), value.ToString());
});
}
public List<U> Convert<U>(CombinationFunctionDelegate<U, TKey, TValue> converterFunction)
{
List<U> res = new List<U>();
foreach (TKey key in Keys)
res.Add(converterFunction(key, this[key]));
return res;
}
}
class Program
{
static void Main(string[] args)
{
SDictionary<string, string> b = new SDictionary<string, string>();
b.Add("foo", "bar");
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
f.Serialize(memStream, b);
memStream.Position = 0;
b = f.Deserialize(memStream) as SDictionary<string, string>;
}
}
</code></pre>
<p>Does that help at all?</p>
<p>Edit: Tweaked again.</p>
|
<p>First of all, Dictionary<> already implements ISerializable, so you don't need to specify that explicity!</p>
<p>Second, you override GetObjectData(), but you don't seem to call Dictionary.GetObjectData(), so the dictionary may not be getting deserialised? Hence, when you access this.Keys, you end up with "an issue".</p>
<p>Yes, I'm thinking out loud here ;)</p>
<p>Perhaps you could try this:</p>
<pre><code>public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
// deserialize the dictionary first
base.GetObjectData(info, context);
// the rest of your code
// ...
}
</code></pre>
<p>I haven't tried or compiled this, but it could be something to consider?</p>
<p>Good luck :)</p>
| 34,048
|
<p>Why are the lists <code>list1Instance</code> and <code>p</code> in the <code>Main</code> method of the below code pointing to the same collection? </p>
<pre><code>class Person
{
public string FirstName = string.Empty;
public string LastName = string.Empty;
public Person(string firstName, string lastName) {
this.FirstName = firstName;
this.LastName = lastName;
}
}
class List1
{
public List<Person> l1 = new List<Person>();
public List1()
{
l1.Add(new Person("f1","l1"));
l1.Add(new Person("f2", "l2"));
l1.Add(new Person("f3", "l3"));
l1.Add(new Person("f4", "l4"));
l1.Add(new Person("f5", "l5"));
}
public IEnumerable<Person> Get()
{
foreach (Person p in l1)
{
yield return p;
}
//return l1.AsReadOnly();
}
}
class Program
{
static void Main(string[] args)
{
List1 list1Instance = new List1();
List<Person> p = new List<Person>(list1Instance.Get());
UpdatePersons(p);
bool sameFirstName = (list1Instance.l1[0].FirstName == p[0].FirstName);
}
private static void UpdatePersons(List<Person> list)
{
list[0].FirstName = "uf1";
}
}
</code></pre>
<p>Can we change this behavior with out changing the return type of <code>List1.Get()</code>? </p>
<p>Thanks</p>
|
<p>In fact, <code>IEnumerable<T></code> <b>is already readonly</b>. It means you cannot replace any items in the underlying collection with different items. That is, you cannot alter the <em>references</em> to the <code>Person</code> objects that are held in the collection. The type <code>Person</code> is not read only, however, and since it's a reference type (i.e. a <code>class</code>), you can alter its members through the reference.</p>
<p>There are two solutions:</p>
<ul>
<li>Use a <code>struct</code> as the return type (that makes a copy of the value each time it's returned, so the original value will not be altered — which can be costly, by the way)</li>
<li>Use read only properties on the <code>Person</code> type to accomplish this task.</li>
</ul>
|
<p><code>IEnumerable<T></code> <em>is</em> readonly</p>
<p><code>p</code> is a new collection which doesn't depend on <code>list1instance</code>.
The mistake you made, is that you thought that this line
<code>list[0].FirstName = "uf1";</code><br>
would only modify one of the lists, when on fact you're modifying the <code>Person</code> object.<br>
The two collections are distinct, they just happen to have the same items.<br>
To prove that they are different, try adding and removing items from one of the lists, and you'll see that the other one isn't affected.</p>
| 46,895
|
<p>When working on developing new software i normally get stuck with the redundancy vs dependencies problem. That is, to either accept a 3rd party library that i have a huge dependencies to or code it myself duplicate all the effect but reduce the dependencies.</p>
<p>Though I've recently been trying to come up with a metric way of weighing up either redundancy in the code and dependencies in the code. For the most part, I've concluded reducing redundancy increases you dependencies in your code. Reducing the dependencies in your code increases redundancy. So its very much counter each other out. </p>
<p>So my question is:
Whats a good metric you've used in the past and do use to weigh up dependencies or redundancy in your code?</p>
<p>One thing I think is soo important is if you choose the dependencies route is you need the tool sets in place so you can quickly examine all the routines and functions that use a specified function. Without those tools set, it seems like redundancy wins.</p>
<p>P.S Following on from an article<br>
<a href="http://www.yosefk.com/blog/redundancy-vs-dependencies-which-is-worse.html" rel="noreferrer">Article</a></p>
|
<p>I would definitely recommend reading Joels essay on this:</p>
<p><a href="http://www.joelonsoftware.com/articles/fog0000000007.html" rel="nofollow noreferrer">"In Defense of Not-Invented-Here Syndrome"</a></p>
<p>For a dependency, the best metric I can think of would be "would the world grind to a halt if this disappeared". For example if the STL of C++ magically went away, tons of programs would stop working. If .Net or Java disappeared, our economy would probably take a beating due to the number of products that stopped working... </p>
<p>I would think in those terms. Of course many things are a shade of gray between "end of world" and "meh" if they disappeared. The closer the dependency is to potentially causing the end-of-the-world if it dissapeared, the more likely it is to be stable, have an active user base, have its issues well-knows, etc. The more users the better. </p>
<p>Its analogous to being a small consumer of some hardware component. Sometimes hardware goes obsolete. Why? Because no one uses it. If you're a small company and need to get a component for your product, you will pick what is commonly available--what the "big players" order in large quantities, hoping this means that (a) the component won't disappear, (b) the problems with the component are well known, (c) there's a large, informed user base and (d) it might cost less and be more readily available. </p>
<p>Sometimes though, you need that special flux-capacitor part and you take the risk that the company selling it to you might not care to keep producing flux-capacitors if you are only ordering 20 a year, and no one seems to care :). In this case, it <em>might</em> be worth developing your own flux capacitor instead of relying on that unreliable Doc Brown Inc. Just don't buy Plutonium from the Libyans.</p>
<p>If you've dealt in manufacturing something (especially when you're making far fewer than millions of them per year), you've had to deal with with this problem. Software dependencies, I believe, need to be understood in very similar terms.</p>
<p>How to quantify this into a real metric? Roughly count how many people depend on something. If its high, the risk of the dependency hurting you is much lower, and you can decide at what point the risk is too much.</p>
|
<p>A possible alternative is to use the external software if it provides a lot of value to your project, but hide this behind a simplified (and more consistent to your project) interface.</p>
<p>This allows you to leverage the power of a third party library, but with much reduced complexity (and as such redundancy) in calling the library. The interface ensures that you don't let the specific style of the third party library bleed into your project and allows you to easily replace it with an internal implementation as and when you think that might be necessary.</p>
<p>A sign of when this is happening might be that the interface you want to support is hampered by the third party library.</p>
<p>The significant downside to this is that it does require extra development and add a certain maintenance impact (this increases with the amount of functionality you need from the library), but allows you to leverage the third party library without too much coupling and without all of your developers needing to understand it.</p>
<p>A good example of this would be the use of an object relation mapper (Hibernate\NHibernate) behind a set of repositories or data access objects, or factories being implemented with an dependency injection framework.</p>
| 19,947
|
<p>Newer ARM processors include the PLD and PLI instructions.</p>
<p>I'm writing tight inner loops (in C++) which have a non-sequential memory access pattern, but a pattern that naturally my code fully understands. I would anticipate a substantial speedup if I could prefetch the next location whilst processing the current memory location, and I would expect this to be quick-enough to try out to be worth the experiment!</p>
<p>I'm using new expensive compilers from ARM, and it doesn't seem to be including PLD instructions anywhere, let alone in this particular loop that I care about.</p>
<p>How can I include explicit prefetch instructions in my C++ code?</p>
|
<p>There should be some Compiler-specific Features. There is no standard way to do it for C/C++. Check out you compiler Compiler Reference Guide. For RealView Compiler see <a href="http://www.keil.com/support/man/docs/armccref/armccref_cjagadac.htm" rel="noreferrer">this</a> or <a href="http://www.keil.com/support/man/docs/armccref/armccref_cjacagfi.htm" rel="noreferrer">this</a>.</p>
|
<p>At the risk of asking the obvious: have you verified the compiler's target architecture? For example (humor me), if by default the compiler is targeted to ARM7, you're <em>never</em> going to see the PLD instruction.</p>
| 10,814
|
<p>Suppose I want to to print several copies of a large, flat object, such as a hollow frame. If I make an STL file consisting of several copies floating just above each other then my 3D printer's software happily generates supports for the upper objects to sit on, as shown below:</p>
<p><a href="https://i.stack.imgur.com/XbxbGm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XbxbGm.png" alt="enter image description here"></a></p>
<p>My question is, is this a crazy idea? If it will work it seems it has several advantages. I can print more copies at once than if I tried to fit them next to each other on the platform, and if one of the prints fails the ones below it will still be OK. It doesn't take that much more filament than printing them all separately.</p>
<p>I'll probably try it at some point just to see what happens, but it's not something I've heard of people doing before, so I'm wondering if there's a good reason why it won't work or would otherwise not be a good strategy.</p>
|
<p>According to the RepRap.org <a href="http://reprap.org/wiki/G-code" rel="nofollow noreferrer">list of G-Code commands</a>, see <strong><a href="http://reprap.org/wiki/G-code#G0_.26_G1:_Move" rel="nofollow noreferrer">G0 & G1: Move</a></strong>:</p>
<blockquote>
<p>The <code>Ennn</code> command is <em>The amount to extrude between the starting point and ending point</em>. </p>
</blockquote>
<p>However, according to <strike><a href="https://github.com/daid/Cura/issues/385" rel="nofollow noreferrer">this</a></strike> a discussion, that is now deleted from GitHub, about the Cura slicing engine:</p>
<p>The <strong>E</strong> values are in <em>absolute mode</em>, so perhaps the firmware is attempting to move the stepper motor to the absolute position (which is almost 50% through your print). This may lead to clogging or skipping depending on how hot your extruder is at that point.</p>
<p>As a last resort, you can perform a Boolean subtract on your model of the section that's already printed and re-slice the model to print the remaining bit. Then glue, or ABS weld, the remaining piece to the main print. I've done this in the past, it's not super glamorous, but it gets the job done if the part doesn't require a lot of structural integrity.</p>
<p><strong>I was incorrect with the following statements with regard to the Cura slicing engine:</strong> </p>
<p><s>It's been a while since I've looked at 3D printer G-Code, but from what I remember, <strong>E</strong> values can be the bane of any manually written G-Code. Usually the slicing engine generates the <strong>E</strong> value as an incremental step value throughout the G-Code (at least this was true for Skeinforge and early MakerWare, please verify this). So, if the value is incremental and depending on the controller, this value could be lost or corrupt if a new print is initialized.</p>
<p>I would hope, that if you're using a slicing engine's <em>custom G-Code</em> input, that the software would be able to compensate situations like this and reformat your provided G-Code to match the value of <strong>E</strong> or any similar command.</s></p>
|
<p>Is the hotend temperature set correctly? If you only preheat the hotend but then turn it off, it will behave exactly as you described (while you're above <code>EXTRUDE_MINTEMP</code> it will behave normally, but once the temperature drops too low it will continue doing the XYZ-moves, but stop extruding). Perhaps you need to add a <code>M109</code> command to set the temperature properly.</p>
<p><a href="https://3dprinting.stackexchange.com/questions/850/no-extrusion-when-trying-to-resume-failed-print-with-manually-edited-gcode/851#851">In his answer</a>, tbm0115 mentions absolute and relative coordinates. Whether absolute or relative coordinates are used is set using the <code>G90</code>/<code>G91</code> commands and will always be the same for all axes (XYZ and E). He also mentions that:</p>
<blockquote>
<p>so perhaps the firmware is attempting to move the stepper motor to the absolute position (which is almost 50% thru your print). This may lead to clogging or skipping depending on how hot your extruder is at that point.</p>
</blockquote>
<p>This shouldn't happen, as extremely long extrude moves are ignored by Marlin. When the printer encounters</p>
<pre><code>G1 F3600 X210.390 Y105.771 E4104.65185
</code></pre>
<p>it performs only the XYZ-part of the move, but doesn't move the extruder (assuming the printer was reset and the current extruder position is 0). However, it does update the internal value for the extruder position, so the next move happens normally. Perhaps missing the initial extrude segment isn't a big deal, but if you want the print to resume perfectly where you left off, you should add a <code>G92</code> command to the beginning to initialize the extruder position correctly, for example:</p>
<pre><code>G92 E4104.4
</code></pre>
<p>(but the exact value depends on the last extruder position in the previous layer).</p>
| 232
|
<p>I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down.</p>
<p>Problems: </p>
<p>The MouseDown and MouseEnter event handlers do not work together very well.</p>
<p>For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cursor moves over the PictureBox the MouseEnter event does not fire, until the mouse button is realeased.</p>
|
<p>When the mouse is pressed down most controls will then <em>Control.Capture</em> the mouse input. This means that all <em>MouseMove</em> events are sent to the original control that captured rather than the control the mouse happens to be over. This continues until the mouse loses capture which typically happens on the mouse up. </p>
<p>If you really need to know when the mouse is over your control even when another control has captured mouse input then you only really have one way. You need to snoop the windows messages destined for other controls inside your application. To do that you need add a message filter ...</p>
<pre><code>Application.AddMessageFilter(myFilterClassInstance);
</code></pre>
<p>Then you need to implement the IMessageFilter on a suitable class...</p>
<pre><code>public class MyFilterClass : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_MOUSEMOVE)
// Check if mouse is over my picture box!
return false;
}
}
</code></pre>
<p>Then you watch for mouse move events and check if they are over your picture box and do whatever it is you want to do.</p>
|
<p>set a flag or a state on mouse down. release it on mouse up.
When on mouse over fires for the picture box check your state.
Now you can detect when a person is dragging something.</p>
| 20,473
|
<p>I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?</p>
|
<p>Probably using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.onpaste" rel="nofollow noreferrer"><code>onpaste</code></a> event, and either <code>return false</code> from it or use <code>e.preventDefault()</code> on the Event object.</p>
<p>Note that <code>onpaste</code> is <em>non standard</em>, don't rely on it for production sites, because it will not be there forever.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on("paste",function(e){
console.log("paste")
e.preventDefault()
return false;
})</code></pre>
</div>
</div>
</p>
|
<p>Even if it is somewhat possible to intercept the paste event in many browsers (but not all as shown at the link on the previous answer), that is quite unreliable and posible not complete (depending on the browser / OS it may be possible to do the paste operation in different ways that may not be trappable by javascript code).</p>
<p><a href="http://discerning.com/topics/software/ttw.html#copy_and_paste" rel="nofollow noreferrer" title="Here">Here</a> is a collection of notes regarding paste (and copy) in the context of rich text editors that may be applied also elsewhere.</p>
| 5,309
|
<p>I have trouble using Perl grep() with a string that <em>may</em> contain chars that are interpreted as regular expressions quantifiers. </p>
<p>I got the following error when the grep pattern is "g++" because the '+' symbols
are interpreted as quantifiers. Here is the output of for program that follows:</p>
<pre><code>1..3
ok 1 - grep, pattern not found
ok 2 - grep, pattern found
Nested quantifiers in regex; marked by <-- HERE
in m/g++ <-- HERE / at escape_regexp_quantifier.pl line 8.
</code></pre>
<p>Is there a modifier I could use to indicate to grep that the quantifiers shall be ignored,
or is there a function that would escape the quantifiers ?</p>
<pre><code>#! /usr/bin/perl
sub test_grep($)
{
my $filter = shift;
my @output = ("-r-xr-xr-x 3 root bin 122260 Jan 23 2005 gcc",
"-r-xr-xr-x 4 root bin 124844 Jan 23 2005 g++");
return grep (!/$filter/, @output);
}
use Test::Simple tests => 2;
ok(test_grep("foo"), "grep, pattern not found");
ok(test_grep("gcc"), "grep, pattern found");
ok(test_grep("g++"), "grep, pattern found");
</code></pre>
<p>PS: in addition to the answer question above, I welcome any feedback on Perl usage in the above as I'm still learning. Thanks</p>
|
<p>The standard way is to use the <code>\Q</code> escape indicator before your variable, to tell Perl not to parse the contents as a regular expression:</p>
<pre><code>return grep (!/\Q$filter/, @output);
</code></pre>
<p>Altering that line in your code yields:</p>
<pre>
1..3
ok 1 - grep, pattern not found
ok 2 - grep, pattern found
ok 3 - grep, pattern found
</pre>
|
<blockquote>
<p>PS: in addition to the answer question
above, I welcome any feedback on Perl
usage in the above as I'm still
learning.</p>
</blockquote>
<p>The best advice I can give for Perl coding advice in general is to install <a href="http://search.cpan.org/perldoc?Perl::Critic" rel="nofollow noreferrer">Perl::Critic</a> and use the <a href="http://search.cpan.org/perldoc?perlcritic" rel="nofollow noreferrer">perlcritic</a> command on your code. If you can't do that, you can use the <a href="http://perlcritic.com/" rel="nofollow noreferrer">on-line perl critic tool</a>. It will help if you have a copy of <a href="http://oreilly.com/catalog/9780596001735/" rel="nofollow noreferrer">Perl Best Practices</a> handy, since <code>Perl::Critic</code> has already read the book and will give you references to page numbers, however even if you don't have the book around you can still find extended feedback in the <a href="http://search.cpan.org/dist/Perl-Critic/" rel="nofollow noreferrer">Perl::Critic documentation</a> sections starting with <code>Perl::Critic::Policy::</code>.</p>
| 25,026
|
<p>I need to spawn a process in Java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this? </p>
<p>Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again.</p>
<p>I'm interested in a hack & slash method to just get it working as well as a better design proposal if you have one :)</p>
|
<p>If you're spawning the process using <a href="http://java.sun.com/javase/6/docs/api/java/lang/Process.html" rel="noreferrer"><code>java.lang.Process</code></a> it should "just work" - I don't believe the spawned process will die when the JVM exits. You might find that the Ant libraries make it easier for you to control the spawning though.</p>
|
<p>If you're looking at making an updater on Linux, you're probably barking up the wrong tree. I believe all major linux distros have a package manager built in. You should use the package manager to do your updating. Nothing frustrates me more than programs that try to self-update... (I'm looking at you, Eclipse)</p>
| 37,807
|
<p>In one of my VB6 forms, I create several other Form objects and store them in member variables.</p>
<pre><code>Private m_frm1 as MyForm
Private m_frm2 as MyForm
// Later...
Set m_frm1 = New MyForm
Set m_frm2 = New MyForm
</code></pre>
<p>I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to <code>Nothing</code> in <code>Form_Unload()</code>?</p>
<p>In general, when is that required?</p>
<p>SOLVED: This particular memory leak was fixed when I did an <code>Unload</code> on the forms in question, not when I set the form to <code>Nothing</code>. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to <code>Nothing</code>, as well.</p>
|
<p>@Matt Dillard - Did setting these to nothing fix your memory leak?</p>
<p>VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said.</p>
<p>Actually calling unload on your forms seems to me to be the best way to ensure that the main form is cleaned up and that each subform cleans up their actions.</p>
<p>I tested this with a blank project and two blank forms.</p>
<pre><code>Private Sub Form_Load()
Dim frm As Form2
Set frm = New Form2
frm.Show
Set frm = Nothing
End Sub
</code></pre>
<p>After running both forms are left visible. setting frm to nothing did well... nothing.</p>
<p>After settign frm to nothing, the only handle open to this form is via the reference.</p>
<pre><code>Unload Forms(1)
</code></pre>
<p>Am I seeing the problem correctly?</p>
<ul>
<li>Josh</li>
</ul>
|
<p>Strictly speaking never, but it gives the garbage collector a strong hint to clean things up.</p>
<p>As a rule: <strong>do it every time you're done with an object that you've created</strong>.</p>
| 5,028
|
<p>I need to add multiple empty divs to a container element using jQuery.</p>
<p>At the moment I am generating a string containing the empty html using a loop</p>
<pre><code>divstr = '<div></div><div></div>...<div></div>';
</code></pre>
<p>and then injecting that into my container:</p>
<pre><code>$('#container').html(divstr);
</code></pre>
<p>Is there a more elegant way to insert multiple, identical elements?</p>
<p>I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable <code>.repeat()</code> plugin?</p>
|
<p>If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.</p>
<p>John Resig explains the technique and includes a performance benchmark:</p>
<p><a href="http://ejohn.org/blog/dom-documentfragments/" rel="noreferrer">http://ejohn.org/blog/dom-documentfragments/</a></p>
<pre><code>var i = 10,
fragment = document.createDocumentFragment(),
div = document.createElement('div');
while (i--) {
fragment.appendChild(div.cloneNode(true));
}
$('#container').append(fragment);
</code></pre>
<p>I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.</p>
|
<p>You can use a regular loop with the Jquery <a href="http://docs.jquery.com/Manipulation/append#content" rel="nofollow noreferrer">append</a> function.</p>
<pre><code>for(i=0;i<10; i++){
$('#container').append("<div></div>");
}
</code></pre>
| 24,612
|
<p>I'm looking for the .NET/C# way of performing <a href="http://msdn.microsoft.com/en-us/library/aa363801(VS.85).aspx" rel="nofollow noreferrer">Change Journal Operations</a> (without importing unmanaged code).</p>
<p>Any hints or RTM-links?</p>
|
<p>This looks promising (and in C#):</p>
<p><a href="http://mchangejournal.codeplex.com/" rel="nofollow">http://mchangejournal.codeplex.com/</a></p>
<p>You have to download the Source code as there are no official Releases. I was able to run the demo (on Windows 7), but not able to see which Files were changed. This library may still be in its infancy.</p>
|
<p>This might be useful</p>
<p><a href="http://www.codeproject.com/KB/files/Eyes_on_NTFS.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/files/Eyes_on_NTFS.aspx</a></p>
| 32,090
|
<p>I know Java well. Which caveats and resources will help me cross to the other side (C#) as painlessly as possible.</p>
|
<p>Biggest tip: go with the <a href="http://msdn.microsoft.com/en-us/library/ms229045.aspx" rel="noreferrer">.NET naming conventions</a> from the word go. That way you'll constantly be reminded about which language you're in. (Sounds silly, but it really is helpful.) Embrace the idioms of the language as far as possible.</p>
<p>There are various books specifically for folks in your situation - search for "C# for Java" in Amazon and you'll get plenty of hits. It's worth reading <em>carefully</em> to make sure you don't assume that things will work the same in C# as in Java. (For instance, in C# instance variable initializers are executed before the base class constructor body; in Java they happen after. Subtle things like this can take a while to learn, and are easy to miss if you're skimming.)</p>
<p>If you're going to be using C# 3, I'd get a book which definitely covers that - everything in C# 3 will be new to you. Gratuitous plug: my own book (<a href="http://manning.com/skeet" rel="noreferrer">C# in Depth</a>) covers C# 2 and 3, but assumes you already know C# 1. (In other words, it won't be enough on its own, but you may want it as a "second" book.)</p>
|
<p>The language syntax is vary similar, so I should only read a small reference of the C# syntax. Like a simple book (for experienced programmers) or maybe wikipedia (<a href="http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp</a>) will tell enough.</p>
<p>The biggest difference is the library: Asp.Net websites are totally different from java servlets. </p>
<p>Don't read much, just start programming!</p>
| 26,091
|
<p>I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this </p>
|
<p>First of all, go get <a href="http://www.mztools.com/v3/mztools3.aspx" rel="noreferrer">MZTools for Visual Basic 6</a>, its free and invaluable. Second add a custom error handler on every function (yes, every function). The error handler we use looks something like this:</p>
<pre><code>On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
LogError "Error " & Err.Number & " (" & Err.Description & ") in line " & Erl & _
", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}"
</code></pre>
<p>Then create a LogError function that logs the error to disc. Next, before you release code add Line Numbers to every function (this is also built into MZTools). From now on you will know from the Error Logs everything that happens. If possible, also, upload the error logs and actually examine them live from the field. </p>
<p>This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors. If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it. If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an "unknown state" and that "bad things" are probably going happen. Obviously use friendly terms to keep the user informed, but not frightened.</p>
|
<p>Use the On Error statement and the Err object.</p>
| 14,168
|
<p>I am trying to print a <a href="https://www.thingiverse.com/thing:2755765" rel="nofollow noreferrer">12 hole Ocarina</a> I found on thingiverse. When printing I have to stop it around 25-30 layers because the edge of the shell is higher then the infill. </p>
<p><a href="https://i.stack.imgur.com/kMrn5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMrn5.jpg" alt="Example 1"></a></p>
<p><a href="https://i.stack.imgur.com/PVHAO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PVHAO.jpg" alt="Example 2"></a></p>
<p><a href="https://www.codepile.net/pile/Z0Y3v986" rel="nofollow noreferrer">G-Code of first 30 layers</a></p>
<p>I tried changing the infill, wall size, speed and retraction settings to no avail. The settings of the example print were:</p>
<ul>
<li>100% infill</li>
<li>0.2mm layer height</li>
<li>40mm printing speed (average)</li>
<li>1mm shell thickness (results in 2 layers)</li>
<li>Automatic infill patern</li>
<li>Printed at 210C with 3mm PLA (<a href="https://www.conrad.nl/p/renkforce-pla300h1-filament-pla-kunststof-3-mm-grijs-1-kg-1093147" rel="nofollow noreferrer">like this one</a>)</li>
<li>Printed on a RF1000</li>
<li>Sliced with CuraEngine in Repetier-host V2.1.6.</li>
</ul>
<p>Does anyone know what might cause this and how I can prevent it from happening?</p>
<p>Any help is greatly appreciated! :)</p>
|
<p>Did you verify the Cura z-offset actually changed the corresponding G-Codes? </p>
<p>I had the opposite problem on my RF1000. To fix the problem I added the following 2 lines to my start G-Codes:</p>
<pre><code>M3001 ; Activate Z-Compensation
M206 Z-0.3 ; Set z offset 0.3mm closer to the nozzle
</code></pre>
<p>The first line was default in some example prints and is (as far as I know) only used by Renkforce printers. The second line moves the nozzle closer to the bed. In your case you'd have to move it further away and would need a positive Z value.</p>
|
<p>Did you verify the Cura z-offset actually changed the corresponding G-Codes? </p>
<p>I had the opposite problem on my RF1000. To fix the problem I added the following 2 lines to my start G-Codes:</p>
<pre><code>M3001 ; Activate Z-Compensation
M206 Z-0.3 ; Set z offset 0.3mm closer to the nozzle
</code></pre>
<p>The first line was default in some example prints and is (as far as I know) only used by Renkforce printers. The second line moves the nozzle closer to the bed. In your case you'd have to move it further away and would need a positive Z value.</p>
| 1,438
|
<p>Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard?</p>
|
<p>Maybe this is a solution for your problem:
<a href="http://sourceforge.net/projects/javaoutlookdd/" rel="nofollow">http://sourceforge.net/projects/javaoutlookdd/</a>
It allows to handle outlook items like File objects during drag&drop.</p>
|
<p>I assume that you've already ruled out the tools in "org.eclipse.swt.dnd" for some reason? There are some examples <a href="http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Clipboard.htm" rel="nofollow noreferrer">here</a> on how to go about using them, in case you haven't. If what you really want to do is drag&drop, you're going to have to do some work with those tools. At that point, really the question becomes, what format is it in on the clipboard, vs in a file, and which is easier to integrate into your app. </p>
| 4,281
|
<p>There are too many method for embedding flash in html, which way is the best?
Requirements are:</p>
<ul>
<li>Cross-browser support</li>
<li>Support for alternative content (if flash is not supported by the browser)</li>
<li>Possibility to require a specific version of the flash player</li>
</ul>
<p>I have been reading about <a href="http://code.google.com/p/swfobject/wiki/documentation" rel="nofollow noreferrer">SWFobject</a>, has anyone used it/tested? </p>
|
<p>In a project I work on we use SWFobject which works like a charm, it allows you to check for a specific version and also display alternative content if flash is not supported.</p>
<pre><code>var fn = function() {
if(swfobject.hasFlashPlayerVersion("9.0.115"))
{
var att = { data:"flash.swf", width:"y", height:"x" };
var par = { menu: "false", flashvars: "" };
signUp = swfobject.createSWF(att, par);
}
}
swfobject.addDomLoadEvent(fn);
</code></pre>
|
<p>I use SWFObject myself, in combination with the <embed> and <object> tags. The reason I include the HTML embeds, is that SWFObject and flashembed rely on Javascript to update the DOM. Not every user who has Flash installed also has Javascript enabled.</p>
| 40,907
|
<p>How could I setup a nice indice on <code>cap:deploy</code>?</p>
<p>I want the remote server to nice the <code>cp</code> commands like so: </p>
<pre><code>nice -n 19 cp ...
</code></pre>
|
<p>This seems to be doing exactly what you want. It's just your code with some typos fixed.</p>
<pre><code> var reportXML:XML =
<Report>
<prop1>4</prop1>
<prop2>2255</prop2>
<prop3>true</prop3>
<prop4>false</prop4>
<prop5>true</prop5>
</Report>;
var myArray:Array = [{xmlNodeName: "prop5", value: false}];
for each (var item:Object in myArray)
{
reportXML[item.xmlNodeName] = item.value.toString();
}
trace(reportXML);
</code></pre>
|
<p>Using E4X syntax in ActionScript 3 I guess that would be something like:</p>
<pre><code>report.prop5[0] = false;
</code></pre>
| 37,839
|
<p>I want to read and write from serial using events/interrupts.
Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?</p>
<p>This is my current code:</p>
<pre>
while(true)
{
//read
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//write
if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//print what you are reading
printf("%s\n", szBuff);
}
</pre>
|
<p>Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:</p>
<pre><code>public interface IValidatableControl
{
bool IsValidControl();
}
</code></pre>
<p>then implement this on your Control1</p>
<pre><code>public class Control1 : IValidatableControl
{
... Other methods
public bool IsValidControl()
{
foreach(object c in this.Controls)
{
if(c.GetType() == "Control2")
return true;
}
return false;
}
}
</code></pre>
<p>There are probably better ways to write this but it should give you enough of an idea to get started.</p>
|
<p>One method you could try is creating and maintaining a simple xml structure that represents your custom control hierarchy. Insert or delete from this structure any time you create or destroy a custom user control. Upon save, validate that the control hierarchy represented in the xml structure is correct. You could save the xml in the Session object to persist it across postbacks.</p>
| 31,857
|
<p>i get a Keyword not supported: '192.168.1.1;initial catalog'. error when trying to do this </p>
<p><code>Dim cn As New SqlConnection(str)</code> </p>
<p>where str is the connection string starts with '192.168.1.1;initial catalog' ...
I have not specified the provider in the connection string</p>
|
<p>you need to provide a properly formatted connectionstring such as:</p>
<pre><code>Dim str As String
str = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
Dim cn As New SqlConnection(str)
</code></pre>
|
<p>You have to specify the database with the keyword "Data Source" or "Server". Here's an example:</p>
<pre><code>Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
</code></pre>
| 39,521
|
<p>I'm well aware of Java tools for manipulating, generating, decompiling JVM bytecode (ASM, cglib, jad, etc). What similar tools exist for the CLR bytecode? Do people do bytecode manipulation for the CLR? </p>
|
<p>Reflector is always good, but Mono.Cecil is the best tool you can possibly ask for overall. It's invaluable for manipulating CIL in any way.</p>
|
<p><a href="http://ndepend.com/" rel="nofollow noreferrer">NDepend</a> allows you to do .NET assemblies static analysis (code metrics, dependency analysis, etc.). NDepend is very useful to get an overview of the structure of your .NET assemblies using dependency matrix, dependency graphs and treemap metrics <a href="http://ndepend.com/Screenshots.aspx" rel="nofollow noreferrer">visualizations</a>.</p>
<p>It is also integrated with Reflector: for example you can detect the important types and methods in your assemblies using respectively a Type/Method <a href="http://ndepend.com/Metrics.aspx#TypeRank" rel="nofollow noreferrer">Rank metric</a> (a code metric similar to Google Page Rank), and jump directly from NDepend to Reflector to get the disassembled code in C#, VB.NET, etc.</p>
| 15,047
|
<p>I would like to write all meta data (including advanced summary properties) for my files in a windows folder to a csv file. Is there a way to collect all the attributes? I see mp3 files have a different set of attributes compared to jpg files. (c#)</p>
<p>This can also be a script (vb, perl)</p>
<p>Update: by looking at libextractor (thank you) I can see this can be achieved by writing different plugins for different type of files. I gather this meta data is not a simple collection...</p>
|
<p>If you can cope w/ VB.Net: <a href="http://www.codeproject.com/KB/vb/mp3id3v1.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/vb/mp3id3v1.aspx</a></p>
<p>If you can cope w/ C++/.Net: <a href="http://www.codeproject.com/KB/audio-video/mp3fileinfo.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/audio-video/mp3fileinfo.aspx</a></p>
<p>For either (assuming the C++) is compiled to .Net, you can use Reflector to disassemble the binary and convert it to C#. Check w/ the respective authors about their licenses first (usually Code Project articles are under an open license like CPOL).</p>
|
<p>It may not be worth it to add all of the data from a jpeg file (exif data). I would hand pick what attributes I wanted from those files.</p>
| 11,376
|
<p>I'm not that familiar with WCF, but I thought I'll learn while trying to consume an existing service.</p>
<p>One of the REST APIs I thought of was the <a href="http://apiwiki.twitter.com/REST+API+Documentation" rel="noreferrer">Twitter API</a>. I thought of developing a WPF client that will just output to the screen the last 5 tweets by a certain Twitter user.</p>
<p>I was wondering if someone could please briefly outline the steps I need to take in Visual Studio to consume these services, using WCF (classes, wizards, proxies etc.).I already know how to just call them using a web request and parse the XML that returns - I really want to see the WCF part at work.</p>
<p>Thanks in advance to anyoine who helps further my education :)</p>
|
<p>Check out Kirk Evans <a href="http://blogs.msdn.com/kaevans/archive/2008/07/26/creating-a-rest-twitter-client-with-wcf.aspx" rel="nofollow noreferrer">Creating a REST Twitter Client With WCF</a>. The latest improvements to WCF in .NET 3.5 SP1 make many RESTful interfaces easier.</p>
<p>Also check out the <a href="http://code.msdn.microsoft.com/dparys/Release/ProjectReleases.aspx?ReleaseId=1128" rel="nofollow noreferrer">Twitter WCF 3.5 API Declaration Library</a> from the MSDN site.</p>
<p>Here's <a href="http://www.amptools.net/2008/07/amplify-twittern-yet-another-c-twitter.aspx" rel="nofollow noreferrer">yet another example</a> - WARNING as of 2/3/10 link is "borked"</p>
|
<p>There is no benefit to using WCF to consume an Http based API like the Twitter API. System.Net.HttpWebRequest is more than sufficient. In fact I suspect that you will have some difficulty. WCF is much easier to get working when you have WCF at both ends of the wire.</p>
<p>However, if the REST API is returning Atom content then you could using the System.ServiceModel.Syndication classes to help parse the response.</p>
<p>EDIT:
Since I wrote this post Microsoft released a preview of a new HTTP client library that does an even better job of consuming RESTful services.<br>
Here is how you would use it to POST to twitter:</p>
<pre><code>var client = new HttpClient();
client.DefaultHeaders.Authorization = Credential.CreateBasic("username","password");
var form = new HttpUrlEncodedForm();
form.Add("status","Test tweet using Microsoft.Http.HttpClient");
var content = HttpContent.Create(form);
var resp = client.Post("http://www.twitter.com/statuses/update.xml", content);
</code></pre>
<p>If you want more more details on this client library, I am in the process of writing some blog posts about it <a href="http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/" rel="noreferrer">here</a>. </p>
| 34,350
|
<p>We have an InnoDB database that is about 70 GB and we expect it to grow to several hundred GB in the next 2 to 3 years. About 60 % of the data belong to a single table. Currently the database is working quite well as we have a server with 64 GB of RAM, so almost the whole database fits into memory, but we’re concerned about the future when the amount of data will be considerably larger. Right now we’re considering some way of splitting up the tables (especially the one that accounts for the biggest part of the data) and I’m now wondering, what would be the best way to do it.</p>
<p>The options I’m currently aware of are</p>
<ul>
<li>Using MySQL Partitioning that comes with version 5.1 </li>
<li>Using some kind of third party library that encapsulates the partitioning of the data (like hibernate shards)</li>
<li>Implementing it ourselves inside our application</li>
</ul>
<p>Our application is built on J2EE and EJB 2.1 (hopefully we’re switching to EJB 3 some day).</p>
<p>What would you suggest?</p>
<p>EDIT (2011-02-11):<br>
Just an update: Currently the size of the database is 380 GB, the data size of our "big" table is 220 GB and the size of its index is 36 GB. So while the whole table does not fit in memory any more, the index does.<br>
The system is still performing fine (still on the same hardware) and we're still thinking about partitioning the data.</p>
<p>EDIT (2014-06-04):
One more update: The size of the whole database is 1.5 TB, the size of our "big" table is 1.1 TB. We upgraded our server to a 4 processor machine (Intel Xeon E7450) with 128 GB RAM.
The system is still performing fine.
What we're planning to do next is putting our big table on a separate database server (we've already done the necessary changes in our software) while simultaneously upgrading to new hardware with 256 GB RAM.</p>
<p>This setup is supposed to last for two years. Then we will either have to finally start implementing a sharding solution or just buy servers with 1 TB of RAM which should keep us going for some time. </p>
<p>EDIT (2016-01-18):</p>
<p>We have since put our big table in it's own database on a separate server. Currently the size ot this database is about 1.9 TB, the size of the other database (with all tables except for the "big" one) is 1.1 TB.</p>
<p>Current Hardware setup:</p>
<ul>
<li>HP ProLiant DL 580</li>
<li>4 x Intel(R) Xeon(R) CPU E7- 4830</li>
<li>256 GB RAM</li>
</ul>
<p>Performance is fine with this setup.</p>
|
<p>You will definitely start to run into issues on that 42 GB table once it no longer fits in memory. In fact, as soon as it does not fit in memory anymore, performance will degrade extremely quickly. One way to test is to put that table on another machine with less RAM and see how poor it performs.</p>
<blockquote>
<p>First of all, it doesn't matter as much splitting out tables unless you also move some of the tables to a separate physical volume.</p>
</blockquote>
<p>This is incorrect. Partioning (either through the feature in MySQL 5.1, or the same thing using MERGE tables) can provide significant performance benefits even if the tables are on the same drive. </p>
<p>As an example, let's say that you are running SELECT queries on your big table using a date range. If the table is whole, the query will be forced to scan through the entire table (and at that size, even using indexes can be slow). The advantage of partitioning is that your queries will only run on the partitions where it is absolutely necessary. If each partition is 1 GB in size and your query only needs to access 5 partitions in order to fulfill itself, the combined 5 GB table is a lot easier for MySQL to deal with than a monster 42 GB version.</p>
<p>One thing you need to ask yourself is how you are querying the data. If there is a chance that your queries will only need to access certain chunks of data (i.e. a date range or ID range), partitioning of some kind will prove beneficial.</p>
<p>I've heard that there is still some buggyness with MySQL 5.1 partitioning, particularly related to MySQL choosing the correct key. MERGE tables can provide the same functionality, although they require slightly more overhead.</p>
<p>Hope that helps...good luck!</p>
|
<p>First of all, it doesn't matter as much splitting out tables unless you also move some of the tables to a separate physical volume. </p>
<p>Secondly, it's not necessarily the table with the largest physical size that you want to move. You may have a much smaller table that gets more activity, while your big table remains fairly constant or only appends data.</p>
<p>Whatever you do, don't implement it yourselves. Let the database system handle it.</p>
| 6,788
|
<p>What is the best way to create a DataTable with the same structure as a table in my SqlServer database? At present, I am using SqlDataAdapter.Fill() with a query that brings back the columns but no rows. That's works fine, but it seems klutzy. </p>
<p>Is there a better way?</p>
|
<p>Well, if you use Linq2Sql, you can reflect over the entity class, and create the datatable based on the properties name and datatype.</p>
<pre><code> Type type = typeof(Product); //or whatever the type is
DataTable table = new DataTable();
foreach(var prop in type.GetProperties())
{
table.Columns.Add(prop.Name, prop.PropertyType);
}
</code></pre>
|
<p>Well, don't you already know the structure?</p>
<p>The "SET FMT_ONLY ON", or "WHERE 1 = 0" tricks are both very tested (with different results).</p>
<p>Is the query here dynamic? I can't help thinking you should know the schema already...</p>
| 48,288
|
<p>I have a Hash like this</p>
<pre><code>{ 55 => {:value=>61, :rating=>-147},
89 => {:value=>72, :rating=>-175},
78 => {:value=>64, :rating=>-155},
84 => {:value=>90, :rating=>-220},
95 => {:value=>39, :rating=>-92},
46 => {:value=>97, :rating=>-237},
52 => {:value=>73, :rating=>-177},
64 => {:value=>69, :rating=>-167},
86 => {:value=>68, :rating=>-165},
53 => {:value=>20, :rating=>-45}
}
</code></pre>
<p>How can i sort it by <strong><em>:rating</em></strong>? Or maybe i should use some different structure?</p>
|
<p>I would change the data structure to an array of hashes:</p>
<pre><code>my_array =
[
{:id => 78, :value=>64, :rating=>-155},
{:id => 84, :value=>90, :rating=>-220},
{:id => 95, :value=>39, :rating=>-92}
]
</code></pre>
<p>You can sort this kind of structure easily with</p>
<pre><code>my_array.sort_by { |record| record[:rating] }
</code></pre>
<p>To get the hash-like functionality of fetching a record by id you can define a new method on my_array:</p>
<pre><code>def my_array.find_by_id(id)
self.find { |hash| hash[:id] == id }
end
</code></pre>
<p>so after that you can do </p>
<pre><code>my_array.find_by_id(id)
</code></pre>
<p>instead of</p>
<pre><code>my_hash[id]
</code></pre>
|
<p>Simple</p>
<pre class="lang-rb prettyprint-override"><code>Hash[result_hash.sort_by {|key, value| value[:rating] }]
</code></pre>
<p>NB: <code>result_hash</code> is your hash</p>
| 47,259
|
<p>For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:</p>
<pre><code>int a = 2, b = 3;
float c = (float)a / (float)b;
</code></pre>
<p>If I do not cast <code>a</code> and <code>b</code> to floats, it'll do integer division and return an int.</p>
<p>Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:</p>
<pre><code>u8 a = 255;
s8 b = -127;
s16 = (s16)a * (s16)b;
</code></pre>
<p>How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?</p>
|
<h3>Question 1: Float division</h3>
<pre><code>int a = 2, b = 3;
float c = static_cast<float>(a) / b; // need to convert 1 operand to a float
</code></pre>
<h3>Question 2: How the compiler works</h3>
<p>Five rules of thumb to remember:</p>
<ul>
<li>Arithmetic operations are always performed on values of the same type.</li>
<li>The result type is the same as the operands (after promotion)</li>
<li>The smallest type arithmetic operations are performed on is int.</li>
<li>ANSCI C (and thus C++) use value preserving integer promotion.</li>
<li><b>Each operation is done in isolation</b>.</li>
</ul>
<p>The ANSI C rules are as follows:<br>
Most of these rules also apply to C++ though not all types are officially supported (yet).</p>
<ul>
<li>If either operand is a <b>long double</b> the other is converted to a <b>long double</b>.</li>
<li>If either operand is a <b>double</b> the other is converted to a <b>double</b>.</li>
<li>If either operand is a <b>float</b> the other is converted to a <b>float</b>.</li>
<li>If either operand is a <b>unsigned long long</b> the other is converted to <b>unsigned long long</b>.</li>
<li>If either operand is a <b>long long</b> the other is converted to <b>long long</b>.</li>
<li>If either operand is a <b>unsigned long</b> the other is converted to <b>unsigned long</b>.</li>
<li>If either operand is a <b>long</b> the other is converted to <b>long</b>.</li>
<li>If either operand is a <b>unsigned int</b> the other is converted to <b>unsigned int</b>.</li>
<li><b>Otherwise both</b> operands are converted to <b>int</b>.</li>
</ul>
<h3>Overflow</h3>
<p>Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening.</p>
<p>As a side note:<br>
Unsigned division can not overflow but signed division can.<br></p>
<pre><code>std::numeric_limits<int>::max() / -1 // No Overflow
std::numeric_limits<int>::min() / -1 // Will Overflow
</code></pre>
|
<p>Do you need to cast one or two sides? The answer isn't dictated by the compiler. It has to know the exact, precse rules. Instead, the answer should be dictated by the person who will read the code later. For that reason alone, cast both sides to the same type. Implicit truncation might be visible enough, so that cast could be redundant.</p>
<p>e.g. this cast float->int is obvious.</p>
<pre><code>int a = float(foo()) * float(c);
</code></pre>
| 30,484
|
<p>While working on an existing project I suddenly got the following error when trying to compile the solution:</p>
<p><em>error MSB3105: The item "[filename]" was specified more than once in the "Resources" parameter. Duplicate items are not supported by the "Resources" parameter.</em></p>
<p>Now, as far as I'm aware, I did not make any change to the project that affects the resources. Also I have checked each and every file within the project, but there is no duplicate reference anywhere to this file.
Now I already found some forum entries regarding this error:</p>
<p>1) Open the .csproj file and remove the duplicate reference. [Tried this, but I cannot find any duplicates in it]</p>
<p>2) In a 'partial class' project, move everything to a single class. [ Could try this, but the project has been split up into partial classes since the start, and I do not want to change this just because of the error ]</p>
<p>So what else could cause this ?</p>
|
<p>Did you try showing all files in the Solution Explorer? You could have a duplicate .rsx file somewhere in there.</p>
|
<p>In my case, this problem happened because a file had the same name but not the same case in the GIT repository.
For example <code>MyFile.cs</code> and <code>myFile.cs</code>.</p>
<p>If you do a checkout on windows, one of the files is overwritten by the other (no message, no warning). So, it is compiling, and we don't notice anything. But if you try to compile on Linux (with .NET Core) both files are present, and there is this error at compile time. </p>
| 40,446
|
<p>I need a member of my class to be a Control, and for it to implement an interface we define.</p>
<p>If I declare it like this...</p>
<pre><code>public class MyClass
{
public Control MyMember;
}
</code></pre>
<p>... then I don't get the interface methods, but if I declare it like this...</p>
<pre><code>public class MyClass
{
public IMyInterface MyMember;
}
</code></pre>
<p>...then I don't get the Control methods. Is there a way to specify that MyMember must be initialised to a type that inherits from both? I can't find one on MSDN. Something like...</p>
<pre><code>public class MyClass
{
public Control : IMyInterface MyMember;
}
</code></pre>
<p>... or ...</p>
<pre><code>public class MyClass
{
public Control MyMember : IMyInterface;
}
</code></pre>
<p>... except that neither of those work. Can I specify interfaces when I declare a member, and if so, how?</p>
|
<p>You can use generics with constraints:</p>
<pre><code>public interface MyClass {
public T GetMyControl() where T : Control, IMyInterface { /* ........ */ }
}
</code></pre>
|
<p>Use the power of inheritance on the interface </p>
<pre><code>public interface IMyInterface : Control
{
..
}
</code></pre>
<p>Now you say you want a control with some special methods.</p>
<hr>
<p><strong>EDIT:</strong> TcKs is of course right.. you can't inherit an interface from a concrete class. </p>
<p>One way of solving this problem could be to extend the interface with a property or method that returns a control.</p>
<p>Sample:</p>
<pre><code>public interface IMyInterface
{
Control Control { get; }
[..rest of the definition..]
}
</code></pre>
<p>and implement it like that:</p>
<pre><code>class MyControl : Control, IMyInterface
{
public Control Control { get { return this; } }
[..rest of the implementation..]
}
</code></pre>
| 36,425
|
<p>I really want to be able to have a way to take an app that currently gets its settings using <strong>ConfigurationManager.AppSettings["mysettingkey"]</strong> to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database.</p>
<p>Any ideas?</p>
|
<p>If you don't mind hacking around the framework and you can reasonably assume the .net framework version the application is running on (i.e. it's a web application or an intranet application) then you could try something like this:</p>
<pre><code>using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;
static class ConfigOverrideTest
{
sealed class ConfigProxy:IInternalConfigSystem
{
readonly IInternalConfigSystem baseconf;
public ConfigProxy(IInternalConfigSystem baseconf)
{
this.baseconf = baseconf;
}
object appsettings;
public object GetSection(string configKey)
{
if(configKey == "appSettings" && this.appsettings != null) return this.appsettings;
object o = baseconf.GetSection(configKey);
if(configKey == "appSettings" && o is NameValueCollection)
{
// create a new collection because the underlying collection is read-only
var cfg = new NameValueCollection((NameValueCollection)o);
// add or replace your settings
cfg["test"] = "Hello world";
o = this.appsettings = cfg;
}
return o;
}
public void RefreshConfig(string sectionName)
{
if(sectionName == "appSettings") appsettings = null;
baseconf.RefreshConfig(sectionName);
}
public bool SupportsUserConfig
{
get { return baseconf.SupportsUserConfig; }
}
}
static void Main()
{
// initialize the ConfigurationManager
object o = ConfigurationManager.AppSettings;
// hack your proxy IInternalConfigSystem into the ConfigurationManager
FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic);
s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));
// test it
Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!");
}
}
</code></pre>
|
<p>It appears there is a way to do this in .NET 3.5 by setting the allowOverride attribute in the appSettings definition section of machine.config. This allows you to override the entire section in your own app.config file and specify a new type to handle it.</p>
| 19,209
|
<p>I've been using Window Home Server for my backups here at home for most of a year now, and I'm really pleased with it. It's far better than the software I was using previously (Acronis). I'm thinking about a backup strategy for my work machine and I'd like to know how WHS compares with Vista's built-in backup and restore features. The plan is to do a full backup to a local external hard drive and backup the documents folder to a network drive on the server. Anyone have experience using the Vista backup feature like this?</p>
|
<p>Chris, </p>
<p>They're different beasts. WHS backup is pretty much automatic and uses deltas - Vista's is manual and I don't believe offers incremental updates.</p>
<p>While your solution (Vista + network copy) would preserve your data it has two problems I an see;</p>
<ol>
<li>Your documents will only have the latest revision. If you find something was corrupted a month ago it could be very awkward to recover it. Vista's shadow copies may help though.</li>
<li>As soon as you install a program/patch/config your Vista backup is out of date and needs remade, or these repeated if you reinstall.</li>
</ol>
<p>These might not be dealbreakers and indeed Vista's backup is pretty decent, it's just nowhere near as good as WHS. In my opinion WHS leaves almost everything else standing, you can be sure this tech will be in the "big brother" server versions shortly.</p>
|
<p>WHS is such a quick, simple, robust way to get your stuff backed up. Plug it in to the network; install the client software; done. I'd hate to live without it.</p>
<p>However, as a programmer, I also set up scripts to run each night and back up my pending changes to another machine. For example, when using TFS, I run 'tf workspaces' then 'tf shelve' on each workspace to make a copy. Shelveset names begin with 'z' to make them sort to the end of the list.</p>
| 5,620
|
<p>So I am writing a registration form and I need the display name to be only numbers, letters and underscores. </p>
<p>Have a look at my code and tell me what I'm doing wrong.</p>
<pre><code><form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
</code></pre>
<p>It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.</p>
|
<p>Your regex</p>
<pre><code>/^([a-zA-Z0-9_])+/
</code></pre>
<p>Looks for </p>
<ol>
<li>Start of string(check), followed by</li>
<li>1 or more letters, numbers, or underscore (check)</li>
</ol>
<p>And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore</p>
<p>If you put a <code>$</code> at the end, then it will work - <code>$</code> matches 'end of string', so the only way it can match is if there are <em>only</em> numbers, letters, and underscores between the start and end of the string.</p>
<pre><code>/^([a-zA-Z0-9_])+$/
</code></pre>
<p>Secondly, I'd suggest using <code>document.getElementById('display-name').value</code> instead of <code>document.forms</code> as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'</p>
|
<p>By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).</p>
<p>As @Annan has said, this would probably be due to the lack of the <code>$</code> character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.</p>
| 3,938
|
<p>When I goto view the property page for my CSharp test application I get the following error.</p>
<p>"An error occurred trying to load the page. COM object that has been seperated from its underlying RCW cannot be used."</p>
<p>The only thing that seems to fix it is rebooting my PC!</p>
|
<p>This is usually caused by a 'rogue' add-in.</p>
<p>Try disabling them all, and then re-enabling them checking for the error - so that you can narrow down the culprit.</p>
|
<p>It seems Microsoft Style Cop was causing the issue.</p>
<p>It was not registered as an Add-in, but was integrated into VS2005 on some deeper level.</p>
| 3,749
|
<p>I am looking for a good menu to use in an ASP.NET. I am currently using the asp menu. I need
it to work in IE 6,7,8, Firefox and Safari. I also need it to not add a lot of overhead to the page client-side. I need to be able to load it from the database.</p>
|
<p>Write your own Server Control which implements the asp.net menu control but go one step further and implement the CSS friendly adapters which will give you standards compliant code instead of the usual garbage html tables that asp:menu creates.</p>
<p>You can read more here: <a href="http://www.asp.net/cssadapters/Whitepaper.aspx" rel="nofollow noreferrer">http://www.asp.net/cssadapters/Whitepaper.aspx</a> </p>
|
<p>You can use this code as inspiration: <a href="http://trac2.assembla.com/GiusCms/browser/trunk/Controls/Controls/Menu.cs" rel="nofollow noreferrer">http://trac2.assembla.com/GiusCms/browser/trunk/Controls/Controls/Menu.cs</a></p>
<p>This control is able to use any SiteMapDataSource. Or you can simply customize it as you want. Use CSS to hide and show inner submenus.</p>
| 39,894
|
<p>I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005?</p>
<p>The insert I'm doing is:</p>
<pre><code>INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems]
</code></pre>
<p>Here is what the trigger looks like:</p>
<pre><code>CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems]
FOR INSERT
AS
Declare @iRoleID int
Declare @iMenuItemID int
Select @iMenuItemID = [ID] from Inserted
DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles
OPEN tblUserRoles
FETCH NEXT FROM tblUserRoles INTO @iRoleID
WHILE (@@FetchStatus = 0)
BEGIN
INSERT INTO tblRestrictedMenuItems(
[RoleID],
[MenuItemID],
[RestrictLevel])
VALUES(
@iRoleID,
@iMenuItemID,
1)
FETCH NEXT FROM tblUserRoles INTO @iRoleID
END
CLOSE tblUserRoles
Deallocate tblUserRoles
</code></pre>
|
<p>Your trigger is only using the first row from 'Inserted'. This is a common misunderstanding when dealing with SQL triggers for the first time. The trigger fires per update not per row.</p>
<p>For example if you do the following:-</p>
<p>update products
set title = 'geoff de geoff'</p>
<p>this would update all the products, but a trigger on the product table would only fire once.</p>
<p>The Inserted 'table' you get in trigger would contain all the rows. You must either loop through Inserted with a cursor, or better join Inserted to the table you are updating.</p>
|
<p>I just want to second @Gordon Bell on his answer...</p>
<p>"Catch" the values the very moment they are being inserted. You do not really need the cursor in this situation (or maybe you have a reason?).</p>
<p>A simple TRIGGER might be all you need:</p>
<p><a href="http://dbalink.wordpress.com/2008/06/20/how-to-sql-server-trigger-101/" rel="nofollow noreferrer">http://dbalink.wordpress.com/2008/06/20/how-to-sql-server-trigger-101/</a> </p>
| 3,882
|
<p>I have just installed Windows Server 2003 Standard Edition and therefore IIS6 (comes as standard). I have also install the windows component that enable the administration of IIS from the browser (<a href="https://server:8098/" rel="nofollow noreferrer">https://server:8098/</a>). The problem I have is that I have to log-in to this tool but the Server Administrator u/name and p/word does not let me in.</p>
<p>The Windows documentation on this tool (<a href="http://support.microsoft.com/kb/324282" rel="nofollow noreferrer">http://support.microsoft.com/kb/324282</a>) says "You are prompted for a user name and password that exist on the Web Server" but none of the standard user acounts on the server let me in.</p>
<p>Thanks,</p>
|
<p>Here are a couple ideas:</p>
<ul>
<li><p>Take a look at the security log on the server for clues.</p></li>
<li><p>Look at the "Directory Security" tab on the properties of the admin site and ensure "Enable anonymous access" is unchecked. You will need to use "Integrated Windows authentication" or "Basic authentication". If you use Basic auth then the password is sent across then network base64 encoded - you will want to use SSL to encrypt it.</p></li>
<li><p>Is there a specific requirement to use the web tools? You can download <a href="http://www.microsoft.com/DOWNLOADS/details.aspx?familyid=F9C1FB79-C903-4842-9F6C-9DB93643FDB7&displaylang=en" rel="nofollow noreferrer">Internet Information Services (IIS) 6.0 Manager for Windows XP</a> from Microsoft and run it from a client.</p></li>
</ul>
|
<p>I'm not so sure now, haven't set up a Win 2003 box in a while but as far as I remember you have to activate remote desktop first and then you can use a RDP client to access the server. I recommend that over the ActiveX RDP client.</p>
| 14,623
|
<p>Sparked by <a href="https://3dprinting.stackexchange.com/questions/1245/running-12v-on-a-24v-heater-cartridge">this question</a>, I wanted to discuss the most efficient and also the easiest ways of thermally insulating the heat block of the hotend.</p>
<p>I have seen <a href="http://numbersixreprap.blogspot.fr/2013/10/does-insulating-heater-block-make.html" rel="noreferrer">Kapton tape insulations as done here</a> with a very conclusive resumee about its usefulness.</p>
<p>In the links of the named article, <a href="http://bukobot.com/hot-end-thermal-management" rel="noreferrer">a method with insulating material from a heatbed is described</a>, however without giving quantitative results.</p>
<p>Additionally, I know that in the guys over in the german reprap forum produce their own <a href="http://forums.reprap.org/read.php?252,584458" rel="noreferrer">silicon covers for the heater block</a>. As I understand there is a large spread between people's reports, from 'almost negligible' as insulator (but helpful for other things) to very useful. No quantification, though. Also, these seem to come with a certain amount of effort to produce.</p>
<p>Are there additional solutions and/or comparisons between solutions?</p>
|
<p>The "quick and dirty" approach is to just slap a bunch of Kapton tape on there. The more the better! (Until you need to dismantle for maintenance, anyway.)</p>
<p>I find pre-cut ceramic tape + kapton tape "blankets" to be easy and effective. E3Dv6 and Replicator 1/2 style hot blocks should be compatible. Or you can cut your own using a sharp hobby knife. </p>
<p><a href="https://i.stack.imgur.com/DFZDq.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DFZDq.jpg" alt="enter image description here"></a>
<a href="http://www.fargo3dprinting.com/products/makerbot-replicator-2-ceramic-insulation-tape/" rel="noreferrer">http://www.fargo3dprinting.com/products/makerbot-replicator-2-ceramic-insulation-tape/</a></p>
<p>The main downside is that they don't insulate two sides of the hot block. But covering the top and bottom provides much of the practical benefit, and you can always add a few more wraps of Kapton tape to cover up the rest of the surfaces. </p>
<p>Another good option that has recently started to become popular is fiberglass heat shield tape. It has a silicone adhesive, woven fiberglass mat, and shiny aluminum surface. (The reflective surface reduces heat radiation.) It's often used in automotive applications around mufflers and the like. You can cut it up into little rectangles for each side of the hot block, or wrap the block similar to Kapton. </p>
<p><a href="https://i.stack.imgur.com/DEiZE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DEiZE.jpg" alt="enter image description here"></a>
<a href="https://shop.raffle.ch/shop/insulation_material/" rel="noreferrer">https://shop.raffle.ch/shop/insulation_material/</a></p>
<p>Main issue is quality -- not all brands have adhesive that will hold up to high temp printing. It may smell when initially "burned in" due to the adhesive cooking a bit. I also find that you need a couple layers to get as much insulation as the ceramic+kapton blanket when there's a lot of airflow around the hot block. </p>
|
<p>After having seen <a href="https://3dprinting.stackexchange.com/questions/4026/how-can-i-insulate-my-thermistor/4035#4035">this answer</a> to this question, <a href="https://3dprinting.stackexchange.com/questions/4026/how-can-i-insulate-my-thermistor">How can I insulate my thermistor?</a>, I ordered these, from eBay, <a href="http://www.ebay.co.uk/itm/5PCS-3mm-Thick-3D-Printer-Heating-Block-Cotton-Hotend-Nozzle-Heat-Insulation-EW-/282484985258" rel="nofollow noreferrer">5PCS 3mm Thick 3D Printer Heating Block Cotton Hotend Nozzle Heat Insulation EW</a>, for around £0.40</p>
<p><a href="https://i.stack.imgur.com/6f1tY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6f1tY.png" alt="enter image description here"></a></p>
<p>Blurb from the item's description</p>
<blockquote>
<ul>
<li>Thickness: 3mm </li>
<li><p>Dimension : 75mm*21*3mm +/-0.2mm </p></li>
<li><p>The heat insulation cotton is used for 3D printer nozzle keeping warm;</p></li>
<li>The heating insulation cotton is made from heat-resistant ceramic fiber;</li>
<li>The product sizes can be customized according to customer needs;</li>
<li>The benefit for keeping the key parts of the 3D printer heating aluminum block warm;</li>
<li>Is making the internal temperature flat, saving power,and energy;</li>
<li>This High temperature resistant cotton can work for a long time in high temperature of 900 degree.</li>
</ul>
</blockquote>
<p>Other images:</p>
<p><a href="https://i.stack.imgur.com/8Y9KA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Y9KA.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/VLyKX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VLyKX.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/nkRUR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nkRUR.png" alt="enter image description here"></a></p>
<p>Granted, these look suspiciously like the strips in <a href="https://3dprinting.stackexchange.com/questions/1247/efficient-and-easy-way-to-thermally-insulate-the-heat-block-of-the-hotend#answer-1249">Ryan's answer</a>, but use cotton, en lieu of ceramic tape.</p>
| 301
|
<p>I'm using the <a href="http://docs.python.org/library/subprocess.html" rel="noreferrer">subprocess module</a> to start a subprocess and connect to its output stream (standard output). I want to be able to execute non-blocking reads on its standard output. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke <code>.readline</code>? I'd like this to be portable or at least work under Windows and Linux.</p>
<p>Here is how I do it for now (it's blocking on the <code>.readline</code> if no data is available):</p>
<pre><code>p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/4025909#4025909"><code>fcntl</code></a>, <a href="https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/375511#375511"><code>select</code></a>, <a href="https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/437888#437888"><code>asyncproc</code></a> won't help in this case.</p>
<p>A reliable way to read a stream without blocking regardless of operating system is to use <a href="https://docs.python.org/3/library/queue.html#queue.Queue.get_nowait" rel="noreferrer"><code>Queue.get_nowait()</code></a>:</p>
<pre><code>import sys
from subprocess import PIPE, Popen
from threading import Thread
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty # python 2.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
# ... do other things here
# read line without blocking
try: line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
print('no output yet')
else: # got line
# ... do something with line
</code></pre>
|
<p>Here is a module that supports non-blocking reads and background writes in python:</p>
<p><a href="https://pypi.python.org/pypi/python-nonblock" rel="nofollow">https://pypi.python.org/pypi/python-nonblock</a></p>
<p>Provides a function,</p>
<p>nonblock_read which will read data from the stream, if available, otherwise return an empty string (or None if the stream is closed on the other side and all possible data has been read)</p>
<p>You may also consider the python-subprocess2 module,</p>
<p><a href="https://pypi.python.org/pypi/python-subprocess2" rel="nofollow">https://pypi.python.org/pypi/python-subprocess2</a></p>
<p>which adds to the subprocess module. So on the object returned from "subprocess.Popen" is added an additional method, runInBackground. This starts a thread and returns an object which will automatically be populated as stuff is written to stdout/stderr, without blocking your main thread.</p>
<p>Enjoy!</p>
| 49,131
|
<p>I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.</p>
<p>Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers. </p>
<p><a href="http://www.schillmania.com/projects/soundmanager2/" rel="noreferrer">Soundmanager2</a> comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well. </p>
<p>Does anyone have any other libraries that might help?</p>
|
<p>You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work...</p>
<pre><code>//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which)
{
if (!soundEmbed)
{
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", "/snd/"+which+".wav");
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
else
{
document.body.removeChild(soundEmbed);
soundEmbed.removed = true;
soundEmbed = null;
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", "/snd/"+which+".wav");
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
soundEmbed.removed = false;
document.body.appendChild(soundEmbed);
}
//======================================================================
</code></pre>
|
<p>For a cross browser solution with wav files I would suggest to make an <code><audio></code> tag default and then go for the <code><embed></code> solution that @dacracot suggested before <a href="https://stackoverflow.com/a/187415/3214497">here</a> if the user is in IE, you can check it easily with a little search here in SO.</p>
| 22,653
|
<p>I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.</p>
<p>Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that most material I could find either targets people who are new to the language or those with a lot of experience.</p>
<p>Which C++ libraries are popular these days? I guess I will need to read on the STL because I didn't use it much. What else? Boost? ATL? WTL?</p>
|
<p>I personally find that syntax is where i mostly need to catch up when i wander back to a language i havent used in a long time. But the concepts and what the language is about stays the same in memory. </p>
<p>Assuming its the same with you, i would say its a good idea to relook at the texts you remember to have been useful to you while learning C++. I would recommned Thinking in C++ for getting up fast on the syntax. </p>
<p>STL would be really useful yes. Thats one thing i have found commonly appreciated by all mature C++ programmers. It would be useful to know the libraries that Boost provides. </p>
<p>The changes to C++ world, depends on the changes your favourite compiler has decided to implement. Since you mentioned ATl/COM i assume it would be VC++. The changes to MFC would be support for Windows Forms (2005 vc++) and Vista compliant uI's and ribbon support(?) (2008 Vc++)</p>
<p>VC++ now supports managed C++ -i'm sure you know what that is coming from the C# world - 2008 adds supports for managed STL too. </p>
<p>VC++ is trying to be more standards compliant and are making some progress in that area. </p>
<p>They have introduced lots of secure functions that depreciate the old stds like strcpy and the compilers will also give warnings if you use the old fns. </p>
<p>VC++2005 also has something called function attributes, which it uses to describe the parameters so that it can do more checking on the inputs you pass in and statically flag a warning if it sees soething amiss. Usefuli would say though our shop has not progressed to using the 2005 compiler. </p>
<p>MSDN has the list of breaking changes for each releases. Oh & Support for Windows 95, Windows 98, Windows Millennium Edition, and Windows NT 4.0 has been removed from 2005 version of VC++. Additionally the core libraries you required till now (CRT, ATL, MFC etc) now support a new deployment model which makes them shared side sy side assemblies and requires a manifest. </p>
<p>This link should get you going - <a href="http://msdn.microsoft.com/en-us/library/y8bt6w34.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/y8bt6w34.aspx</a></p>
<p>2008 adds even more like Tr1 recommendations, more optimizning compiler, parallel compilation(/mp), support for new processor architectures etc. Open Mp support has also been enhanced in one of these versions is what i remember. </p>
<p>Again refer MSDN - thats the suthentic source for all the answers. </p>
<p>Good luck. </p>
|
<p>To sharpen your C++ skills I'd suggest going over some of your old C++ code if you still have access to it. Revisiting it will hopefully trigger those parts of your brain that have laid dormant after switching to C# :)</p>
<p>For libraries STL is good, then boost. I don't think there is too much new stuff going on with ATL/WTL from what you would have known back in 2001.</p>
| 17,232
|
<p>In my just-completed project, I was working getting distributed transactions working.</p>
<p>We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries.</p>
<p>Our request sequence looked like:</p>
<pre><code>browser -> secured servlet -> 'wafer-thin' SLSB -> spring TX-aware proxy -> request-handler POJO
</code></pre>
<p>What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB.</p>
<p>Our SLSB had a static initialiser block to bootstrap our Spring application context.</p>
<p>I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations.</p>
<p>I would be interested to know what others propose to separate tiers when using Spring?</p>
|
<p>Jeremiah Morrill has recently released a <a href="http://www.codeplex.com/WPFMediaKit" rel="nofollow noreferrer">specialized WPF library</a> that supports displaying HD Media (among other features)</p>
|
<p>It sure doesn't seem to work correctly. It may be that testing for the opacity of other layers slows it down too much. Have you tried running the test with Aero turned off?</p>
<p>It has been suggested that hosting Windows Media Player may be the way to go.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms748870.aspx" rel="nofollow noreferrer">Walkthrough: Hosting an ActiveX Control in Windows Presentation Foundation by Using XAML</a></p>
| 18,092
|
<p>I accidentally coded <code>SELECT $FOO..</code> and got the error "Invalid pseudocolumn "$FOO".</p>
<p>I can't find any documentation for them. Is it something I should know?</p>
<p>Edit: this is a MS SQL Server specific question.</p>
|
<p>Pseudocolumns are symbolic aliases for actual columns, that have special properties, for example, $IDENTITY is an alias for the column that has the IDENTITY assigned, $ROWGUID for the column with ROWGUIDCOL assigned. It's used for the internal plumbing scripts.</p>
|
<p>A simple Google search brings up <a href="http://www.lorentzcenter.nl/awcourse/oracle/server.920/a96540/sql_elements6a.htm" rel="nofollow noreferrer">this</a> from Oracle's reference:</p>
<blockquote>
<p>A pseudocolumn behaves like a table
column, but is not actually stored in
the table. You can select from
pseudocolumns, but you cannot insert,
update, or delete their values.</p>
</blockquote>
<p>I think that the error you got is simply because there is no column $FOO, so the query parser tests to see if there's a psuedocolumn named $FOO as a fallback. And since there is no pseudocolumn named "$FOO" (and there are no other fallback) you get the error "Invalid pseudocolumn $FOO". This is a guess, though. I'm no expert when it comes to databases.</p>
| 23,754
|
<p>What I want to do is set the focus to a specific control (specifically a <code>TextBox</code>) on a tab page when that tab page is selected.</p>
<p>I've tried to call <code>Focus</code> during the Selected event of the containing tab control, but that isn't working. After that I tried to call focus during the <code>VisibleChanged</code> event of the control itself (with a check so that I'm not focusing on an invisible control), but that isn't working either.</p>
<p>Searching this site, I've come across this <a href="https://stackoverflow.com/questions/48680/winforms-c-set-focus-to-first-child-control-of-tab-page">question</a> but that isn't working either. Although after that, I did notice that calling the <code>Focus</code> of the control does make it the <code>ActiveControl</code>.</p>
|
<p>I did this and it seems to work:</p>
<p>Handle the <code>SelectedIndexChanged</code> for the <code>tabControl</code>.
Check if <code>tabControl1.SelectedIndex</code> == the one I want and
call <code>textBox.Focus();</code></p>
<p>I'm using VS 2008, BTW.</p>
<hr>
<p>Something like this worked:</p>
<pre><code>private void tabControl1_selectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 1)
{
textBox1.Focus();
}
}
</code></pre>
|
<p>Try the TabPage.Enter something like</p>
<pre>
private void tabPage1_Enter(object sender, EventArgs e)
{
TabPage page = (TabPage)sender;
switch (page.TabIndex)
{
case 0:
textBox1.Text = "Page 1";
if (!textBox1.Focus())
textBox1.Focus();
break;
case 1:
textBox2.Text = "Page 2";
if (!textBox2.Focus())
textBox2.Focus();
break;
default:
throw new InvalidOperationException();
}
}
</pre>
| 21,643
|
<p>I'm trying to call the OpenThemeData (see msdn <a href="http://msdn.microsoft.com/en-us/library/bb759821%28v=VS.85%29.aspx" rel="noreferrer">OpenThemeData</a>) function but I couldn't determine what are the acceptable Class names to be passed in by the <code>pszClassList</code> parameter.</p>
<pre><code>HTHEME OpenThemeData(
HWND hwnd,
LPCWSTR pszClassList
);
</code></pre>
<p>Could anybody tell me what are the acceptable class names that I can pass into that parameter?
Thanks!</p>
|
<p>You can look in "AeroStyle.xml" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name "Button", the edit control "Edit", etc. I generally pick the class name of the control that's closest to whatever custom element I'm working on is, and use the theme data for that. That way you'll get code that works with XP, Vista and (hopefully) Windows 7, regardless of what the user's selected theme actually is.</p>
<p>However, unless you use raw Win32 a lot, you probably don't do much control creation directly using the class name. The class names are rather liberally sprinkled throughout MSDN. A good place to start is usually the "CommCtrl.h" file from the Platform SDK, which has a lot of them, and they're always described in the MSDN help on the individual common controls. You can also often learn them by looking at how dialogs are defined in .rc files by opening them in a text editor: these contain the class name for the controls.</p>
|
<p>It has nothing to do with Aero, which even doesn't exits on XP !
See the source code of OpenThemeData()..</p>
| 26,733
|
<p>I'm trying to add a new node to an jQuery <a href="http://news.kg/wp-content/uploads/tree/" rel="nofollow noreferrer">SimpleTree</a>, but all I seem to be able to get is "sTC.addNode is not a function"... </p>
<pre><code>var simpleTreeCollection = $('.simpleTree').simpleTree({
animate:true,
drag:false,
autoclose: false,
afterClick:function(node){},
afterDblClick:function(node){},
beforeMove:function (destination, source, pos){},
afterMove:function(destination, source, pos){},
afterAjax:function() {},
afterContextMenu:function(node){}
});
simpleTreeCollection.addNode('test', 'test');
</code></pre>
<p>Any suggestions what I might be doing wrong? Is there even the possibility to add a node?</p>
|
<p>Maybe take a look at <a href="http://www.jstree.com/jsTree/examples/" rel="nofollow noreferrer">jsTree</a> </p>
|
<p>FYI the above code works in the firebug console on their demo page. On your tree ake sure you use a correct selector to highlight the node</p>
| 36,003
|
<p>I' trying to use a Linq query to find and set the selected value in a drop down list control.</p>
<pre><code> Dim qry = From i In ddlOutcome.Items _
Where i.Text.Contains(value)
Dim selectedItem As ListItem = qry.First
ddlOutcome.SelectedValue = selectedItem.Value
</code></pre>
<p>Even though the documentation says that the DropDownList.Items collection implements IEnumerable I get an error in the Where clause that Option Strict ON disallows late binding!</p>
|
<p>I can give you an answer in C#, and i hope it helps you.</p>
<p>The easiest way it to use the methods of DropDownlist, better than linq query:</p>
<pre><code>DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("2"));
</code></pre>
<p>If you want the linq query it would be like this:</p>
<pre><code>var selected=from i in DropDownList1.Items.Cast<ListItem>()
where ((ListItem)i).Text.Contains("2") select i;
DropDownList1.SelectedValue = selected.ToList()[0].Text;
</code></pre>
|
<p>simple way to select using following code</p>
<pre><code>foreach (ListItem i in DropDownList1.Items)
{
DropDownList1.SelectedValue = i.Value;
if (DropDownList1.SelectedItem.Text=="text of your DropDownList")
{
break;
}
}
</code></pre>
| 40,773
|
<p>I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of .NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.</p>
|
<p>One reason is compatibility - anyone who has done 'check for existence' knows to exclude directories; changing that behaviour may confuse those who rely on that behaviour.</p>
<p>Secondly, the underlying code often does a check on the operating system for existence in a catlog of filesystem entries - to the OS, a directory is the same as a file. In other words, it's looking for an entry of 'xyz' in the catalog not a file with name 'xyz' in the catalog.</p>
<p>Backwards compatability is the main reason, I suspect.</p>
|
<p>Part of the Unix philosophy is that "<a href="http://www.cs.bgu.ac.il/~arik/usail/concepts/filesystems/everything-is-a-file.html" rel="nofollow">everything is a file</a>". This has influenced other environments as well to some degree.</p>
| 7,282
|
<p>I was wondering what I could do to improve the performance of Excel automation, as it can be quite slow if you have a lot going on in the worksheet...</p>
<p>Here's a few I found myself:</p>
<ul>
<li><p><code>ExcelApp.ScreenUpdating = false</code> -- turn off the redrawing of the screen</p></li>
<li><p><code>ExcelApp.Calculation = Excel.XlCalculation.xlCalculationManual</code> -- turning off the calculation engine so Excel doesn't automatically recalculate when a cell value changes (turn it back on after you're done)</p></li>
<li><p>Reduce calls to <code>Worksheet.Cells.Item(row, col)</code> and <code>Worksheet.Range</code> -- I had to poll hundreds of cells to find the cell I needed. Implementing some caching of cell locations, reduced the execution time from ~40 to ~5 seconds.</p></li>
</ul>
<p>What kind of interop calls take a heavy toll on performance and should be avoided? What else can you do to avoid unnecessary processing being done?</p>
|
<p>When using C# or VB.Net to either get or set a range, figure out what the total size of the range is, and then get one large 2 dimensional object array...</p>
<pre><code>//get values
object[,] objectArray = shtName.get_Range("A1:Z100").Value2;
iFace = Convert.ToInt32(objectArray[1,1]);
//set values
object[,] objectArray = new object[3,1] {{"A"}{"B"}{"C"}};
rngName.Value2 = objectArray;
</code></pre>
<p>Note that its important you know what datatype Excel is storing (text or numbers) as it won't automatically do this for you when you are converting the type back from the object array. Add tests if necessary to validate the data if you can't be sure beforehand of the type of data.</p>
|
<p>Another big thing you can do in VBA is to use Option Explicit and avoid Variants wherever possible. Variants are not 100% avoidable in VBA, but they make the interpreter do more work at runtime and waste memory.</p>
<p>I found this article very helpful when I was starting with VBA in Excel.<br>
<a href="http://www.ozgrid.com/VBA/SpeedingUpVBACode.htm" rel="nofollow noreferrer">http://www.ozgrid.com/VBA/SpeedingUpVBACode.htm</a></p>
<p>And this book</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/1565923588" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/VB-VBA-Nutshell-Language-OReilly/dp/1565923588</a></p>
<p>Similar to </p>
<pre><code> app.ScreenUpdates = false //and
app.Calculation = xlCalculationManual
</code></pre>
<p>you can also set </p>
<pre><code> app.EnableEvents = false //Prevent Excel events
app.Interactive = false //Prevent user clicks and keystrokes
</code></pre>
<p>although they don't seem to make as big a difference as the first two.</p>
<p>Similar to setting Range values to arrays, if you are working with data that is mostly tables with the same formula in every row of a column, you can use R1C1 formula notation for your formula and set an entire column equal to the formula string to set the whole thing in one call.</p>
<pre><code>app.ReferenceStyle = xlR1C1
app.ActiveSheet.Columns(2) = "=SUBSTITUTE(C[-1],"foo","bar")"
</code></pre>
<p>Also, creating XLL add-ins using ExcelDNA & .NET (or the hard way in C) is also the only way you can get UDFs to run on multiple threads. (See Excel DNA's ExcelFunction attribute's IsThreadSafe property.)</p>
<p>Before I transitioned to Excel DNA completely, I also experimented with creating COM visible libraries in .NET to reference in VBA projects. Heavy text processing is a bit faster than VBA that way, as are using wrapped .NET List classes instead of VBA's Collection, but Excel DNA is better.</p>
| 46,463
|
<p>I've explored python for several years, but now I'm slowly learning how to work with c. Using the <a href="http://www.python.org/doc/2.5.2/ext/intro.html" rel="nofollow noreferrer">python documentation</a>, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it. My question now is how to distribute a program like this.</p>
<p>I suppose the heart of my question is how to compile things. I can do this easily on my own machine (gentoo), but a binary distribution like Ubuntu probably doesn't have a compiler available by default. Plus, I have a few friends who are mac users. My instinct says that I can't just compile with my own machine and then run it on another. Anyone know what I can do, or some online resources for learning things like this?</p>
|
<p>Please read up on distutils. Specifically, the section on <a href="http://www.python.org/doc/2.5.2/dist/describing-extensions.html" rel="nofollow noreferrer">Extension Modules</a>.</p>
<p>Making assumptions about compilers is bad policy; your instinct may not have all the facts. You could do some marketplace survey -- ask what they can handle regarding source distribution of extension modules.</p>
<p>It's relatively easy to create the proper distutils <code>setup.py</code> and see who can run it and who can't.</p>
<p>Built binary distributions are pretty common. Perhaps you can sign up some users will help create binary distributions -- with OS-native installers -- for some considerations. </p>
|
<p>S. Lott is right. You should first look at distutils. After you've learned what you need from distutils, look at <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow noreferrer">setuptools</a>. Setuptools is built on top of distutils and makes installation easy for your users. Have you ever used easy_install or Python Eggs? That's what's next.</p>
| 37,628
|
<p>The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.</p>
<p>For instance, how would I find out that there are 10 week days in between <code>31/08/2008</code> and <code>13/09/2008</code>?</p>
|
<pre><code> $datefrom = strtotime($datefrom, 0);
$dateto = strtotime($dateto, 0);
$difference = $dateto - $datefrom;
$days_difference = floor($difference / 86400);
$weeks_difference = floor($days_difference / 7); // Complete weeks
$first_day = date("w", $datefrom);
$days_remainder = floor($days_difference % 7);
$odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
if ($odd_days > 7) { // Sunday
$days_remainder--;
}
if ($odd_days > 6) { // Saturday
$days_remainder--;
}
$datediff = ($weeks_difference * 5) + $days_remainder;
</code></pre>
<p>From here: <a href="http://www.addedbytes.com/php/php-datediff-function/" rel="nofollow noreferrer">http://www.addedbytes.com/php/php-datediff-function/</a></p>
|
<p>One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):</p>
<pre><code>$dif_in_seconds = abs(strtotime($a) - strtotime($b));
$daysbetween = $dif_in_seconds / 86400;
</code></pre>
<p>ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..</p>
| 10,599
|
<p>I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention. </p>
<p>How can I tell the difference? </p>
|
<p>You can use a <code>-d</code> file test operator to check if something is a directory. Here's some of the commonly useful file test operators</p>
<pre>
-e File exists.
-z File has zero size (is empty).
-s File has nonzero size (returns size in bytes).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
</pre>
<p>See <a href="http://perldoc.perl.org/perlfunc.html#-X-FILEHANDLE" rel="nofollow noreferrer">perlfunc manual page for more</a></p>
<p>Also, try using <a href="https://metacpan.org/pod/File::Find" rel="nofollow noreferrer">File::Find</a> which can recurse directories for you. Here's a sample which looks for directories....</p>
<pre><code>sub wanted {
if (-d) {
print $File::Find::name." is a directory\n";
}
}
find(\&wanted, $mydir);
</code></pre>
|
<p>It would be easier to use <code>File::Find</code>.</p>
| 25,277
|
<p>i'm trying to use the GeoKit plugin to calculate the distance between 2 points. So the idea is, i do a search for an article, and the results i want to order by distance. So i have a form where I enter the article (that im looking for) and my address. Then rails must find all articles that match with my query and order by address.</p>
<p>So now, i have two models: Article and User. Articles belongs_to User and User has_many Articles. At the User model i have the info related with my latitude and longitude.</p>
<p>So my Article object has three fields:</p>
<ul>
<li>id</li>
<li>name</li>
<li>user_id (FK to User model)</li>
</ul>
<p>And my user model has four fields</p>
<ul>
<li>id</li>
<li>name</li>
<li>lat (latitude)</li>
<li>lng (longitude)</li>
</ul>
<p>OK, to have access to the user info thru articles i do the query:</p>
<pre><code>@articles = Article.find(:all,:conditions=>"vectors @@ to_tsquery('büch')",:joins=>" INNER JOIN users ON users.id = articles.user_id",:include=>:user,:origin=>"Augustusplatz,8,leipzig,germany")
</code></pre>
<p>it works. But when i wanna add an :order=>'distance ASC' it fails because the order by query is using a Article.lat, and Article.lng fields to calculate the distance, but these fields lat and lng, are User object's members and not Article member.</p>
<p>BTW if I get the query generated by rails and i change the order by clause where uses articles.lat/lng to users.lat/lng it works.</p>
|
<p>I'm not really an SQL expert, and I find joins very hard to wrap my head around (even more than figuring out multiple NOT's like <code>if(!(foo != !bar & (!baz)))</code> ) but I do feel that either the <code>:joins</code> line or the <code>:include</code> line is redundant, or even wrong.</p>
<p>(I cleaned up your query so I could understand it, please do the same with the question):</p>
<pre><code>@articles = Article.find(:all,
:conditions=>"vectors @@ to_tsquery('büch')",
:joins=>" INNER JOIN users ON users.id = articles.user_id",
:include=>:user,
:origin=>"Augustusplatz,8,leipzig,germany")
</code></pre>
<p>I guess either the model of the user and article should define their relation, so you don't need a manual join or that you remove the include. </p>
<p>But I don't see from this code where the distance is actually calculated (probably some automagic in GeoKit?). The distance should be "named" with the SQL someting like:</p>
<pre><code>SELECT (some_heavy_calculation(user.lat, user.long)) AS distance, ... ;
</code></pre>
<p>So you can refer to the distance in the order by clause, I don't think the database cares if the <em>ruby</em> object doesn't contain the value.</p>
<p>Perhaps if you showed us the generated SQL, wich causes errors, and you'r manipulated SQL we could understand better...</p>
|
<p>I didnt want to put the sql generated in the first post otherwise it would be too much thing :-)</p>
<p>I was using just include, that works, but i dont know why, include makes a left join, and i need a inner join. If i remove the include i cannot access the user information thru the article object (like for example articles[0].user.name)</p>
<p>here it is my sql. if i change in the order by the fields articles.lat and articles.lng to users.lat and user.lng it works:</p>
<pre><code>SELECT "articles"."id" AS t0_r0, "articles"."name" AS t0_r1, "articles"."price" AS t0_r2, "articles"."user_id" AS t0_r3, "articles"."created_at" AS t0_r4, "articles"."updated_at" AS t0_r5, "articles"."vectors" AS t0_r6, "users_articles"."id" AS t1_r0, "users_articles"."name" AS t1_r1, "users_articles"."address" AS t1_r2, "users_articles"."created_at" AS t1_r3, "users_articles"."updated_at" AS t1_r4, "users_articles"."lat" AS t1_r5, "users_articles"."lng" AS t1_r6, "users_articles"."zipcode" AS t1_r7 FROM "articles" LEFT OUTER JOIN "users" users_articles ON "users_articles".id = "articles".user_id INNER JOIN users ON users.id = articles.user_id WHERE (vectors @@ to_tsquery('büch')) ORDER BY (ACOS(least(1,COS(0.896021391737553)*COS(0.216084610510851)*COS(RADIANS(articles.lat))*COS(RADIANS(articles.lng))+
COS(0.896021391737553)*SIN(0.216084610510851)*COS(RADIANS(articles.lat))*SIN(RADIANS(articles.lng))+
SIN(0.896021391737553)*SIN(RADIANS(articles.lat))))*3963.19)
</code></pre>
<p>Regards,</p>
<p>Victor</p>
| 41,945
|
<p>I wrote a raw TCP client for HTTP/HTTPS requests, however I'm having problems with chunked encoding responses. HTTP/1.1 is requirement therefore I should support it.</p>
<p><em>Raw TCP is a business requirement that I need to keep, therefore I can't switch to .NET HTTPWebRequest/HTTPWebResponse</em> However if there is way to convert a RAW HTTP Request/Response into HTTPWebRequest/HTTPWebResponse that'd work.</p>
|
<p>The best place to start is the <a href="ftp://ftp.isi.edu/in-notes/rfc2616.txt" rel="nofollow noreferrer">http 1.1 specification</a>, which lays out how chunking works. Specifically section 3.6.1.</p>
<blockquote>
<p>3.6.1 Chunked Transfer Coding</p>
<p>The chunked encoding modifies the
body of a message in order to<br>
transfer it as a series of chunks,
each with its own size indicator,<br>
followed by an OPTIONAL trailer
containing entity-header fields. This
allows dynamically produced content to
be transferred along with the<br>
information necessary for the
recipient to verify that it has<br>
received the full message.</p>
<pre><code> Chunked-Body = *chunk
last-chunk
trailer
CRLF
chunk = chunk-size [ chunk-extension ] CRLF
chunk-data CRLF
chunk-size = 1*HEX
last-chunk = 1*("0") [ chunk-extension ] CRLF
chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
chunk-ext-name = token
chunk-ext-val = token | quoted-string
chunk-data = chunk-size(OCTET)
trailer = *(entity-header CRLF)
</code></pre>
<p>The chunk-size field is a string of
hex digits indicating the size of<br>
the chunk. The chunked encoding is
ended by any chunk whose size is<br>
zero, followed by the trailer, which
is terminated by an empty line.</p>
<p>The trailer allows the sender to
include additional HTTP header<br>
fields at the end of the message. The
Trailer header field can be used to
indicate which header fields are
included in a trailer (see section
14.40).</p>
</blockquote>
<p>Assuming that you have already read the header from the response and are pointing to the next byte in the stream your pseudo code would look something like this:</p>
<pre><code>done = false;
uint8 bytes[];
while (!done)
{
chunksizeString = readuntilCRLF(); // read in the chunksize as a string
chunksizeString.strip(); // strip off the CRLF
chunksize = chunksizeString.convertHexString2Int(); // convert the hex string to an integer.
bytes.append(readXBytes(chunksize)); // read in the x bytes and append them to your buffer.
readCRLF(); // read the trailing CRLF and throw it away.
if (chunksize == 0)
done = true; //
}
// now read the trailer if any
// trailer is optional, so it may be just the empty string
trailer = readuntilCRLF()
trailer = trailer.strip()
if (trailer != "")
readCRLF(); // read out the last CRLF and we are done.
</code></pre>
<p>This is ignoring the chunk-extension portion, but since it is delimited with a ";" it should be easy to split it out. This should be enough to get you started. Keep in mind that the chunksize string <strong>does not</strong> have a leading "0x".</p>
|
<p>For the future reference also I found this :</p>
<pre><code> length := 0
read chunk-size, chunk-extension (if any) and CRLF
while (chunk-size > 0) {
read chunk-data and CRLF
append chunk-data to entity-body
length := length + chunk-size
read chunk-size and CRLF
}
read entity-header
while (entity-header not empty) {
append entity-header to existing header fields
read entity-header
}
Content-Length := length
Remove "chunked" from Transfer-Encoding
</code></pre>
| 41,159
|
<p>I have a page generated by php which includes two drop-down lists (SELECTs) which contain a lot of items (about 2,000 each). The page is fine, but when it loads in Firefox, there's a delay during the load, and then it seems to refresh the entire page. If a user tries to click on anything before the "reload" occurs, it has no effect.</p>
<p>In Explorer, each drop-down just takes a while (a second or two) to appear, which is fine.</p>
<p>Anyone know what this is? And aside from using AJAX to dynamically fill the drop-down list, is there an easy way to avoid it?</p>
<p>EDIT: Additional information. I have got my PHP script to output to a log file whenever it is called, so I can now see that what seems to be happening is this:</p>
<p>A call is made to the PHP script, and the page starts to load. After a few seconds, another identical call is made to the PHP script, at which point the page starts to load again. This time it completes loading. So I guess it seems like the browser refreshes the page automatically for some reason before the page finishes loading.</p>
|
<p>Can you explain what you mean when you say it gets a bit "messy"? Any particular symptoms?</p>
<p>Anyway looking at this from a clean sheet I'd say you want to throttle the number of concurrent uploads you're performing at one time otherwise you're likely to hit some kind of limit in terms of the number of connections the FTP server will allow a single client, or the number of connections the client operating system will allow. Your application is likely to be bound more by bandwidth than by CPU so running too many threads may be counter-productive. You'll essentially be uploading more items at once but with less throughput.</p>
<p>I presume you application has a set of tasks which cron4j off, these tasks then take a directory and upload it via FTP, does this sound about right?</p>
<p>If so I'd suggest splitting this into a couple of stages, first cron4j kicks off tasks which constructs a runnable object which when executed will perform the FTP upload instead of the task performing the upload itself. Place this runnable in in a queue (a blocking queue from java.util.concurrent would be a good idea). You then have a few instances of another task running in a thread pool, these tasks will take jobs off the queue and execute them (experiment with the number of threads in the pool to see what gives you good throughput). This will give you a set of competing consumers which you can limit to the effective number of concurrent uploads (e.g. 4 at a time).</p>
<hr>
<p>As is noted in the comments the SEDA pattern sounds quite interesting. If your going to do any concurrent programming in Java I'd recommend getting a copy of "Concurrent Programming in Java: Design Principles and Patterns" by Doug Lea, it doesn't include the Java 5 stuff but most of that is based on what's in the book anyway. He clearly explains a lot of issues about thread safety and how to write good Java Code.</p>
|
<p>ipworks FTP class is thread safe. And you <strong>must</strong> read Java Concurrency in Practice by Brian Goetz ... </p>
<pre><code>public class ServerConnection extends Thread {
// the connection to the ftp server
private final Ftp connection;
</code></pre>
<p>or you can implement Runnable and use an <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" rel="nofollow noreferrer" title="executorService"">executorService</a> if you don't like to manage the thread yourself ...</p>
| 49,081
|
<p>I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files.</p>
<p>Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?</p>
|
<p>The problem (for you) with <code>$0</code> is that it is set to whatever command line was use to invoke the script, not the location of the script itself. This can make it difficult to get the full path of the directory containing the script which is what you get from <code>%~dp0</code> in a Windows batch file.</p>
<p>For example, consider the following script, <code>dollar.sh</code>:</p>
<pre><code>#!/bin/bash
echo $0
</code></pre>
<p>If you'd run it you'll get the following output:</p>
<pre><code># ./dollar.sh
./dollar.sh
# /tmp/dollar.sh
/tmp/dollar.sh
</code></pre>
<p>So to get the fully qualified directory name of a script I do the following:</p>
<pre><code>cd `dirname $0`
SCRIPTDIR=`pwd`
cd -
</code></pre>
<p>This works as follows:</p>
<ol>
<li><code>cd</code> to the directory of the script, using either the relative or absolute path from the command line.</li>
<li>Gets the absolute path of this directory and stores it in <code>SCRIPTDIR</code>.</li>
<li>Goes back to the previous working directory using "<code>cd -</code>".</li>
</ol>
|
<p>I have tried $0 before, namely:</p>
<blockquote>
<p>dirname $0</p>
</blockquote>
<p>and it just returns "." even when the script is being sourced by another script: </p>
<blockquote>
<p>. ../somedir/somescript.sh</p>
</blockquote>
| 25,497
|
<p>Not too practical maybe, but still interesting.</p>
<p>Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.</p>
<p>And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I <em>could</em> try just to cast all to double, but that's not convenient way.</p>
<p>Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?</p>
<p>So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.</p>
<p>And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.</p>
<p>What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.</p>
<p>Thanks.</p>
|
<p>For this you need generic maths. Luckily <a href="http://www.yoda.arachsys.com/csharp/genericoperators.html" rel="nofollow noreferrer">I have done this</a>. Usage would be similar to this "complex" (i.e. x+iy) <a href="http://csharpindepth.com/ViewNote.aspx?NoteID=50" rel="nofollow noreferrer">example</a>.
The Operator class is now part of <a href="http://www.yoda.arachsys.com/csharp/miscutil/" rel="nofollow noreferrer">MiscUtil</a>.</p>
|
<p>Well, there is a less tech-heavy way to do just that. You cannot add a new interface for "int" or "double". But you can declare an interface for an object that can multiply and add values of some generic type. And then you can implement the interface for all the types you need:</p>
<pre><code>public interface ICalculator<T>
{
T Add(T x, T y);
T Multiply(T x, T y);
}
public class MatrixMultiplier<T>
{
public MatrixMultiplier(ICalculator<T> calculator) { ... }
}
public class IntCalculator : ICalculator<int>
{
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
}
</code></pre>
| 20,094
|
<p>I wanting to show prices for my products in my online store.
I'm currently doing:</p>
<pre><code><span class="ourprice">
<%=GetPrice().ToString("C")%>
</span>
</code></pre>
<p>Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"</p>
<p>I think the correct HTML for an output of "£12.00" is "<code>&pound;12.00</code>", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. </p>
<p>(The server is in the UK, with localisation is set appropriately in web.config).</p>
<p>Is the below an improvement, or is there a better way?</p>
<pre><code><span class="ourprice">
<%=GetPrice().ToString("C").Replace("£","&pound;")%>
</span>
</code></pre>
|
<p>The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser. </p>
<p>If the browser doesn't recognise £, it probably won't recognise the entity versions.
It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can).</p>
<p>If you see a $ sign, it's likely you have two things:
1. The browser default language is en-us
2. Asp.net is doing automatic locale switching. The default web.config setting is something like</p>
<pre><code><globalization culture="auto:en-us" uiCulture="auto:en-US" />
</code></pre>
<p>As you (almost certainly) want UK-only prices, simply specify the locale in web.config:</p>
<pre><code> <globalization culture="us" uiCulture="en-gb" />
</code></pre>
<p>(or on page level:)</p>
<pre><code> <%@Page Culture="en-gb" UICulture="en-gb" ..etc... %>
</code></pre>
<p>Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you</p>
<p>(although you can specify the en-gb culture in the overloads if you're paranoid).</p>
|
<p>If you need to explicity state the localisation you can use the CultureInfo and pass that to the string formatter.</p>
| 11,417
|
<p>After many years of using make, I've just started using jam (actually ftjam) for my projects. </p>
<p>In my project workspaces, I have two directories:</p>
<ul>
<li><code>src</code> where I build executables and libraries</li>
<li><code>test</code> where my test programs are</li>
</ul>
<p>I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to).</p>
<p>Any suggestion on how to do it? </p>
|
<p>Ok this seems to be not an as easy question as I thought so I worked out a solution on my own. It uses a script to achieve the end result so I still hope that a Jam guru will have a jam-only solution.</p>
<ul>
<li><p>Create a Jamrules in the root directory of the project with the common definitions.</p></li>
<li><p>Create a Jamfile in the root directory of the project with the following content:</p></li>
</ul>
<pre>
SubDir . ;
SubInclude . src ;
SubInclude . test ;
</pre>
<ul>
<li>Create a Jamfile in the src directory</li>
</ul>
<pre>
SubDir .. src ;
Library mylib : mylib.c ;
</pre>
<ul>
<li>Create a Jamfile in the test directory</li>
</ul>
<pre>
SubDir .. test ;
Main mytest : mytest.c ;
Depends mytest : mylib$(SUFLIB) ;
</pre>
<p>With this setting, as long as I am in the root directory, whenever I try to build mytest the library will also be recompiled (if needed). I found an old message on the jammer mailing list describing it.</p>
<p>Alas this doesn't work if I'm in the test subdirectory since jam can only look <em>down</em> into subdirectories.</p>
<p>So, I created a simple script called <code>jmk</code> and put it together with the <code>jam</code> executable (so that both are in the path):</p>
<pre><code>if [ "$JMKROOT" = "" ] ; then
JMKROOT=`pwd`
export JMKROOT
fi
cd $JMKROOT
jam $*
</code></pre>
<p>and I set the JMKROOT environment variable to the root of my project.</p>
<p>For when I compile in a Windows shell (that's why I want to use Jam) I simply use this small <code>jmk.bat</code> batch file:</p>
<pre><code>@echo off
if "%JMKROOT%" EQU "" set JMKROOT=%CD%
set OLDCD=%CD%
cd %JMKROOT%
jam %1 %2 %3 %4 %5 %6 %7 %8 %9
cd %OLDCD%
</code></pre>
|
<p>I'm using Jam in <a href="http://github.com/Andromeda-OS/LLVM" rel="nofollow">one of my projects</a>, and I am encountering your very situation. I have my executable programs in the <code>bin</code> subdirectory, and my static libraries are kept in the <code>lib</code> subdirectory.</p>
<p>In my top-level Jamfile, I type in <code>SubDir TOP ;</code>. This initializes the <code>$(TOP)</code> variable to point to the directory containing this Jamfile. I then add lines such as <code>SubInclude TOP bin llvm-tblgen</code> and <code>SubInclude TOP lib Support</code>, which adds the contents of the Jamfiles in <code>bin/llvm-tblgen</code> and <code>lib/Support</code> to the build.</p>
<p>In the Jamfile in <code>bin/llvm-tblgen</code>, I type in <code>SubDir TOP bin llvm-tblgen ;</code>. I do the same in the Jamfile in <code>lib/Support</code>, but I use <code>SubDir TOP lib Support ;</code> instead. The key when entering <code>SubDir</code> rules is to type in the names of each subdirectory from the <code>TOP</code> to the directory containing this Jamfile.</p>
<p>Then, when it is time to set the linkline of my executable target, I reference the support library like this: <code>$(TOP)/lib/Support/libLLVMSupport.a</code>. Jam expands this path into the location of <code>libLLVMSupport.a</code>, relative to where I run Jam, even if I cd into the <code>bin/llvm-tblgen</code> directory and run Jam manually from there.</p>
<p>This makes it very easy to manage large projects that contain cross-directory dependencies. This solution, unlike your earlier one, lets you run Jam directly. Hope it helps you!</p>
| 24,222
|
<p>How do you disable autocomplete in the major browsers for a specific input (or form field)?</p>
|
<p>Firefox 30 ignores <code>autocomplete="off"</code> for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100" rel="noreferrer">commentary</a> from May 5, 2014:</p>
<blockquote>
<ul>
<li>The password manager <em>always</em> prompts if it wants to save a password. Passwords are not saved without permission from the user.</li>
<li>We are the third browser to implement this change, after IE and Chrome.</li>
</ul>
</blockquote>
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion" rel="noreferrer">Mozilla Developer Network</a> documentation, the Boolean form element attribute <code>autocomplete</code> prevents form data from being cached in older browsers.</p>
<pre><code><input type="text" name="foo" autocomplete="off" />
</code></pre>
|
<p>I was having trouble on a form which included input fields for username and email with email being right after username. Chrome would autofill my current username for the site into the email field and put focus on that field. This wasn't ideal as it was a form for adding new users to the web application.</p>
<p>It seems that if you have two inputs one after the other where the first one has the term 'user name' or username in it's label or ID and the next one has the word email in it's label or ID chrome will autofill the email field.</p>
<p>What solved the issue for me was to change the ID's of the inputs to not include those words. I also had to set the text of the labels
to an empty string and use a javascript settimeout function to change the label back to what it should be after 0.01s.</p>
<pre><code>setTimeout(function () { document.getElementById('id_of_email_input_label').innerHTML = 'Email:'; }, 10);
</code></pre>
<p>If you are having this problem with any other input field being wrongly autofilled I'd try this method.</p>
| 2,466
|
<p>What is the most efficient way to create a <strong>constant</strong> (never changes at runtime) mapping of <code>string</code>s to <code>int</code>s? </p>
<p>I've tried using a <a href="https://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke">const Dictionary</a>, but that didn't work out. </p>
<p>I could implement a <a href="https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary">immutable wrapper</a> with appropriate semantics, but that still doesn't seem totally right.</p>
<hr>
<p>For those who have asked, I'm implementing <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.110).aspx" rel="noreferrer">IDataErrorInfo</a> in a generated class and am looking for a way to make the columnName lookup into my array of descriptors. </p>
<p>I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!</p>
|
<p>Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.</p>
<p>There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:</p>
<pre><code>switch (myString)
{
case "cat": return 0;
case "dog": return 1;
case "elephant": return 3;
}
</code></pre>
<p>This is exactly what you want. And yes, I know, it's ugly.</p>
|
<p>Why not:</p>
<pre><code>public class MyClass
{
private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } };
public IEnumerable<KeyValuePair<string,int>> MyCollection
{
get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }
}
}</code></pre>
| 33,636
|
<p>I am working on an application, implemented in VC++ 2008 that needs to use sftp through libCurl. In order for this to happen, libCurl needs to be built with ssh support. The problem is that, unlike the mingw makefile, the makefile for vc8 does not have target configurations to build with SSH support. Does anyone know what needs to be done to make this work?</p>
|
<p>Solve the realm problem that you mentioned is easy. Just set the realm to *.mysite.com instead of just mysite.com. If you're using one of the ASP.NET controls included in the library, you just set a property on the control to set the realm. If you're doing it programmatically, you set the property on the IAuthenticationRequest object before calling RedirectToProvider().</p>
<p>As far as the session/cookie problem goes with hopping between the www and non-www host name, you have two options:</p>
<ol>
<li>Rather than storing the original identifier in the session, which is a bad idea anyway for a few reasons, use the IAuthenticationRequest.AddCallbackArguments(name, value) method to store the user's entered data and then use IAuthenticationResponse.GetCallbackArgument(name) to recall the data when the user has authenticated.</li>
<li>Forget it. There's a reason the dotnetopenid library doesn't automatically store this information for you. Directed identity is just one scenario: If the user types 'yahoo.com', you probably don't want to say to them 'Welcome, yahoo.com!' but rather 'Welcome, id.yahoo.com/andrewarnott'! The only way you're going to get the right behavior consistently is to use the IAuthenticationResponse.FriendlyIdentifierForDisplay property to decide what to display to the user as his logged in identifier. It gives more accurate information, and is easier than storing a value in the callback and getting it back. :)</li>
</ol>
|
<p>I dunno how OpenID works, but LiveID gives you a token based on the combination of user and domain. I just would have forwarded www to mysite.com.</p>
| 34,453
|
<p>I have the following scenario:</p>
<pre>
public class CarManager
{
..
public long AddCar(Car car)
{
try
{
string username = _authorizationManager.GetUsername();
...
long id = _carAccessor.AddCar(username, car.Id, car.Name, ....);
if(id == 0)
{
throw new Exception("Car was not added");
}
return id;
} catch (Exception ex) {
throw new AddCarException(ex);
}
}
public List AddCars(List cars)
{
List ids = new List();
foreach(Car car in cars)
{
ids.Add(AddCar(car));
}
return ids;
}
}
</pre>
<p>I am mocking out _reportAccessor, _authorizationManager etc.</p>
<p>Now I want to unittest the CarManager class.
Should I have multiple tests for AddCar() such as </p>
<pre>
AddCarTest()
AddCarTestAuthorizationManagerException()
AddCarTestCarAccessorNoId()
AddCarTestCarAccessorException()
</pre>
<p>For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()? < p/></p>
<p>Please help.</p>
|
<p>There are two issues here:</p>
<ul>
<li>Unit tests should do more than test methods one at a time. They should be designed to prove that your class can do the job it was designed for when integrated with the rest of the system. So you should mock out the dependencies and then write a test for each way in which you class will actually be used. For each (non-trivial) class you write there will be scenarios that involve the client code calling methods in a particular pattern.</li>
<li>There is nothing wrong with AddCars calling AddCar. You should repeat tests for error handling but only when it serves a purpose. One of the unofficial rules of unit testing is 'test to the point of boredom' or (as I like to think of it) 'test till the fear goes away'. Otherwise you would be writing tests forever. So if you are confident a test will add no value them don't write it. You may be wrong of course, in which case you can come back later and add it in. You don't have to produce a perfect test first time round, just a firm basis on which you can build as you better understand what your class needs to do.</li>
</ul>
|
<p>Unit Test should focus only to its corresponding class under testing. All attributes of class that are not of same type should be mocked.</p>
<p>Suppose you have a class (CarRegistry) that uses some kind of data access object (for example CarPlatesDAO) which loads/stores car plate numbers from Relational database.</p>
<p>When you are testing the CarRegistry you should not care about if CarPlateDAO performs correctly; Since our DAO has it's own unit test.</p>
<p>You just create mock that behaves like DAO and returns correct or wrong values according to expected behavior. You plug this mock DAO to your CarRegistry and test only the target class without caring if all aggregated classes are "green".</p>
<p>Mocking allows separation of testable classes and better focus on specific functionality.</p>
| 12,652
|
<p>I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been started?
Here is a sample bit of code:</p>
<pre><code> try {
Zend_Registry::get('database')->beginTransaction();
$totals = self::calculateTotals($Cart);
$PaymentInstrument = new PaymentInstrument;
$PaymentInstrument->create();
$PaymentInstrument->validate();
$PaymentInstrument->save();
Zend_Registry::get('database')->commit();
return true;
} catch(Zend_Exception $e) {
Bootstrap::$Log->err($e->getMessage());
Zend_Registry::get('database')->rollBack();
return false;
}
</code></pre>
<p>Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started. </p>
|
<p>The framework has no way of knowing if you started a transaction. You can even use <code>$db->query('START TRANSACTION')</code> which the framework would not know about because it doesn't parse SQL statements you execute.</p>
<p>The point is that it's an application responsibility to track whether you've started a transaction or not. It's not something the framework can do.</p>
<p>I know some frameworks try to do it, and do cockamamie things like count how many times you've begun a transaction, only resolving it when you've done commit or rollback a matching number of times. But this is totally bogus because none of your functions can know if commit or rollback will actually do it, or if they're in another layer of nesting.</p>
<p>(Can you tell I've had this discussion a few times? :-)</p>
<p><em>Update 1:</em> <a href="http://propel.phpdb.org/" rel="nofollow noreferrer">Propel</a> is a PHP database access library that supports the concept of the "inner transaction" that doesn't commit when you tell it to. Beginning a transaction only increments a counter, and commit/rollback decrements the counter. Below is an excerpt from a mailing list thread where I describe a few scenarios where it fails.</p>
<p><em>Update 2:</em> <a href="https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/transactions.html#transaction-nesting" rel="nofollow noreferrer">Doctrine DBAL</a> also has this feature. They call it Transaction Nesting.</p>
<hr />
<p>Like it or not, transactions are "global" and they do not obey object-oriented encapsulation.</p>
<p><strong>Problem scenario #1</strong></p>
<p>I call <code>commit()</code>, are my changes committed? If I'm running inside an "inner transaction" they are not. The code that manages the outer transaction could choose to roll back, and my changes would be discarded without my knowledge or control.</p>
<p>For example:</p>
<ol>
<li>Model A: begin transaction</li>
<li>Model A: execute some changes</li>
<li>Model B: begin transaction (silent no-op)</li>
<li>Model B: execute some changes</li>
<li>Model B: commit (silent no-op)</li>
<li>Model A: rollback (discards both model A changes and model B changes)</li>
<li>Model B: WTF!? What happened to my changes?</li>
</ol>
<p><strong>Problem scenario #2</strong></p>
<p>An inner transaction rolls back, it could discard legitimate changes made by an outer transaction. When control is returned to the outer code, it believes its transaction is still active and available to be committed. With your patch, they could call <code>commit()</code>, and since the transDepth is now 0, it would silently set <code>$transDepth</code> to -1 and return true, after not committing anything.</p>
<p><strong>Problem scenario #3</strong></p>
<p>If I call <code>commit()</code> or <code>rollback()</code> when there is no transaction active, it sets the <code>$transDepth</code> to -1. The next <code>beginTransaction()</code> increments the level to 0, which means the transaction can neither be rolled back nor committed. Subsequent calls to <code>commit()</code> will just decrement the transaction to -1 or further, and you'll never be able to commit until you do another superfluous <code>beginTransaction()</code> to increment the level again.</p>
<p>Basically, trying to manage transactions in application logic without allowing the database to do the bookkeeping is a doomed idea. If you have a requirement for two models to use explicit transaction control in one application request, then you must open two DB connections, one for each model. Then each model can have its own active transaction, which can be committed or rolled back independently from one another.</p>
|
<p>In web-facing PHP, scripts are almost always invoked during a single web request. What you would really like to do in that case is start a transaction and commit it right before the script ends. If anything goes wrong, throw an exception and roll back the entire thing. Like this:</p>
<pre><code>wrapper.php:
try {
// start transaction
include("your_script.php");
// commit transaction
} catch (RollbackException $e) {
// roll back transaction
}
</code></pre>
<p>The situation gets a little more complex with sharding, where you may be opening several connections. You have to add them to a list of connections where the transactions should be committed or rolled back at the end of the script. However, realize that in the case of sharding, unless you have a global mutex on transactions, you will not be easily able to achieve true isolation or atomicity of concurrent transactions because another script might be committing their transactions to the shards while you're committing yours. However, you might want to check out MySQL's <a href="http://dev.mysql.com/doc/refman/5.5/en/xa.html" rel="nofollow">distributed transactions</a>.</p>
| 41,354
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.