instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I tried to make the title as clear as possible... here is my scenario:</p> <p>I have 2 tables (let's call them table A and table B) that have a similar schema. I would like write a stored procedure that would select specific columns of data out of table A, and insert this data as a new record in table B.</p> <p>Can someone point me in the write direction to make such a query? I am unsure how to "Hold" the values from the first query, so that I may then perform the insert.</p> <p>I am trying to avoid making a query, processing it with C# and then making another query...</p> <p>Thanks.</p>
<pre><code>INSERT INTO B (Col1, Col2) SELECT Col1, Col2 FROM A </code></pre> <p>Is this what you mean?</p>
<p>use a SELECT INTO</p> <pre><code>SELECT [Col1], [COl2] INTO TableA FROM TableB </code></pre>
44,359
<p>I am looking for instructions on how to setup a PEAR channel for our project so that we can deploy it with the pear installer. I have searched the web for a while and cannot find any straightforward information. I followed <a href="http://greg.chiaraquartet.net/archives/123-Setting-up-your-own-PEAR-channel-with-Chiara_PEAR_Server-the-official-way.html" rel="nofollow noreferrer">this tutorial</a> for a while, but I am having a hell of a time getting this to work. Does anyone know how to do this? Is there a simpler way?</p>
<p>It looks like you are one of the few people who want to do this. That tutorial you linked to appears to be the latest (!) but the package is still <a href="http://pear.chiaraquartet.net/index.php?package=Chiara_PEAR_Server" rel="nofollow noreferrer">somewhat in development</a>. The documentation in that package is also non-existent. It looks like it's up to you to write the docs. Or maybe contact <a href="http://greg.chiaraquartet.net/" rel="nofollow noreferrer">Greg Beaver</a>; the author of the package and blog post you linked to. He also <a href="https://rads.stackoverflow.com/amzn/click/com/1904811191" rel="nofollow noreferrer" rel="nofollow noreferrer">wrote a book about PEAR</a> (albeit in 2006.) The amazon writeup mentions this:</p> <blockquote> <p>Next, you will learn how to set up your own PEAR Channel for distributing PHP applications, both open-source and proprietary closed-source PHP applications that can be secured using technology already built into the PEAR Installer</p> </blockquote> <p>.</p>
<p>What problems are you encountering on following the tutorial that you linked to?</p> <p>You could set up your own channel with pirum or the chiara server ( <a href="http://pear.chiaraquartet.net/" rel="nofollow noreferrer">http://pear.chiaraquartet.net/</a> ) but you could also look into getting an account on <a href="http://pearfarm.org" rel="nofollow noreferrer">http://pearfarm.org</a> and hosting your packages there (or on <a href="http://pearhub.org" rel="nofollow noreferrer">http://pearhub.org</a>).</p>
20,305
<p>I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are:</p> <ol> <li><p>Changing permissions to allow PowerShell to run scripts</p> </li> <li><p>The speed of PowerShell starting</p> </li> <li><p>Using PowerShell for logon/logoff scripts with GPO</p> </li> </ol> <p>Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do). Has anyone had any experience with using PowerShell in this way?</p>
<p>To speed up the start of PowerShell, Jeffrey Snover (the partner/architect responsible for PowerShell) provides an "Update-GAC" script <a href="http://blogs.msdn.com/powershell/archive/2008/09/02/speeding-up-powershell-startup-updating-update-gac-ps1.aspx" rel="nofollow noreferrer">here</a>.</p> <p>Basically, it is just running through the assemblies that are loaded for PowerShell and NGen'ing (pre-compiling the IL to machine code) them. This does speed up the start of PowerShell.</p> <p>Another trick is to run PowerShell with the -nologo and -noprofile switches.</p> <p>This will skip the profile scripts and splash logo.</p> <p>There is a <a href="http://www.specopssoft.com/powershell/" rel="nofollow noreferrer">product for using PowerShell for logon/logoff scripts</a> from Special Operations Software. There are other ways to do it also.</p> <pre><code>%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -nologo -noprofile </code></pre>
<p>Changing permissions to allow Powershell scripts is possible to do via group policy. </p> <p>Microsoft provide ADM templates <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2917a564-dbbc-4da7-82c8-fe08b3ef4e6d&amp;DisplayLang=en" rel="nofollow noreferrer">here</a>, there is only one option "Turn on Script Execution" and can be assigned at a user or computer level.</p>
13,878
<p>Can anyone recommend a library/SDK/etc. that is free or for purchase that I can integrate into my C++ application that enables the application to perform automatic error reporting? I have something now that I am using but it does not catch all exceptions. I'm looking for something more sophisticated and more robust than I have now.</p> <p>Any suggestions?</p>
<p>You don't mention your platform, but if it's Windows, you could take a look at Microsoft's <a href="http://www.microsoft.com/whdc/maintain/StartWER.mspx" rel="nofollow noreferrer">Windows Error Reporting</a>.</p> <p>This is the "Application XYZ has crashed. Do you want to send an error report to Microsoft?" stuff. If you sign up for WER, you get access to the error reports (dump files, basically) for your apps.</p>
<p>You can use <em>SetUnhandledExceptionFilter</em> and <em>MiniDumpWriteDump</em> functions to make error reporting by yourself.</p>
44,620
<p>Upcasting is allowed in Java, however downcasting gives a compile error. </p> <p>The compile error can be removed by adding a cast but would anyway break at the runtime. </p> <p>In this case why Java allows downcasting if it cannot be executed at the runtime?<br> Is there any practical use for this concept? </p> <pre><code>public class demo { public static void main(String a[]) { B b = (B) new A(); // compiles with the cast, // but runtime exception - java.lang.ClassCastException } } class A { public void draw() { System.out.println("1"); } public void draw1() { System.out.println("2"); } } class B extends A { public void draw() { System.out.println("3"); } public void draw2() { System.out.println("4"); } } </code></pre>
<p>Downcasting is allowed when there is a possibility that it succeeds at run time:</p> <pre><code>Object o = getSomeObject(), String s = (String) o; // this is allowed because o could reference a String </code></pre> <p>In some cases this will not succeed:</p> <pre><code>Object o = new Object(); String s = (String) o; // this will fail at runtime, because o doesn't reference a String </code></pre> <p>When a cast (such as this last one) fails at runtime a <a href="https://docs.oracle.com/javase/10/docs/api/java/lang/ClassCastException.html" rel="noreferrer"><code>ClassCastException</code></a> will be thrown.</p> <p>In other cases it will work:</p> <pre><code>Object o = "a String"; String s = (String) o; // this will work, since o references a String </code></pre> <p>Note that some casts will be disallowed at compile time, because they will never succeed at all:</p> <pre><code>Integer i = getSomeInteger(); String s = (String) i; // the compiler will not allow this, since i can never reference a String. </code></pre>
<p>Downcasting is very useful in the following code snippet I use this all the time. Thus proving that downcasting is useful. </p> <pre><code>private static String printAll(LinkedList c) { Object arr[]=c.toArray(); String list_string=""; for(int i=0;i&lt;c.size();i++) { String mn=(String)arr[i]; list_string+=(mn); } return list_string; } </code></pre> <p>I store String in the Linked List. When I retrieve the elements of Linked List, Objects are returned. To access the elements as Strings(or any other Class Objects), downcasting helps me. </p> <p>Java allows us to compile downcast code trusting us that we are doing the wrong thing. Still if humans make a mistake, it is caught at runtime.</p>
49,904
<p>I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes.</p> <p>Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint".</p> <p>What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process.</p> <p>Here's some pseudocode</p> <pre><code>FILE *p1read, *p1write; FILE *p2read, *p2write; FILE *p3read, *p3write; //start each command, attach to stdin and stdout popen2("process1",&amp;p1read,&amp;p1write); popen2("process2",&amp;p2read,&amp;p2write); popen2("process3",&amp;p3read,&amp;p3write); while (1) { //read status from each process char status1[1024]; char status2[1024]; char status3[1024]; fread(status1,1024,p1read); fread(status2,1024,p2read); fread(status3,1024,p3read); char command1[1024]; char command2[1024]; char command3[1024]; //do some logic here //write command back to each process fwrite(command1,p1write); fwrite(command2,p2write); fwrite(command3,p3write); } </code></pre> <p>The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea.</p> <p>Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively. </p> <p>The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way.</p> <p>Any Ideas?</p> <p>Thanks!</p>
<p>On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process.</p> <p>Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file numbers. In the Microsoft CRT, file numbers are different from OS file handles. So to return the other end of CreatePipe to the caller, you first need _open_osfhandle to get a CRT file number, and then fdopen on that.</p> <p>If you want to see working code, check out _PyPopen in</p> <p><a href="http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup" rel="noreferrer">http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup</a></p>
<p>I think you've made a very good start to your problem by using the popen2() function to abstract away the cross-platform issues. I was expecting to come and suggest 'sockets', but I'm sure that's not relevant after reading the question. You could use sockets instead of pipes - it would be hidden in the popen2() function.</p> <p>I am 99% sure you can implement the required functionality on Windows, using Windows APIs. What I cannot do is point you to the right functions reliably. However, you should be aware the Microsoft has most of the POSIX-like API calls available, but the name is prefixed with '_'. There are also native API calls that achieve the effects of <code>fork</code> and <code>exec</code>.</p> <p>Your comments suggest that you are aware of issues with availability of data and possible deadlocks - be cautious.</p>
31,706
<p>I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.</p> <p>I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?</p>
<p>Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:</p> <pre><code>class Base { public Base() { InitializeComponent(); } protected virtual void InitializeComponent() { ... } } class Derived : Base { private Button button1; public Derived() : base() { button1 = new Button(); } protected override void InitializeComponent() { button1.Text = "I'm gonna throw a null reference exception" } } </code></pre> <p>The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.</p>
<ul> <li>If you have users that override your virtual methods you can't seal them again without breaking code.</li> <li>Any virtual methods you call from the constructor may fall down to derived implementations and if they don't call the base method and the constructor depends on it, the object may be in an invalid state</li> </ul>
16,604
<p>As I recall <code>BOOST_MPL_ASSERT</code> was once preferred. Is this still true? Anyone know why?</p>
<p><em>[Answering my own question]</em></p> <p>It depends. This is an apples to oranges comparison. Although similar, these macros are NOT interchangeable. Here's a summary of how each works:</p> <p><code>BOOST_STATIC_ASSERT( P )</code> generates a compilation error if <code>P != true</code>.</p> <p><code>BOOST_MPL_ASSERT(( P ))</code> generates a compilation error if <code>P::type::value != true</code>.</p> <p>The latter form, despite <em>requiring double parentheses</em>, is especially useful because it can generate more informative error messages <em>if</em> one uses <em>Boolean nullary Metafunctions</em> from Boost.MPL or TR1's <code>&lt;type_traits&gt;</code> as predicates.</p> <p>Here is an example program that demonstrates how to use (and misuse) these macros:</p> <pre><code>#include &lt;boost/static_assert.hpp&gt; #include &lt;boost/mpl/assert.hpp&gt; #include &lt;type_traits&gt; using namespace ::boost::mpl; using namespace ::std::tr1; struct A {}; struct Z {}; int main() { // boolean predicates BOOST_STATIC_ASSERT( true ); // OK BOOST_STATIC_ASSERT( false ); // assert // BOOST_MPL_ASSERT( false ); // syntax error! // BOOST_MPL_ASSERT(( false )); // syntax error! BOOST_MPL_ASSERT(( bool_&lt; true &gt; )); // OK BOOST_MPL_ASSERT(( bool_&lt; false &gt; )); // assert // metafunction predicates BOOST_STATIC_ASSERT(( is_same&lt; A, A &gt;::type::value ));// OK BOOST_STATIC_ASSERT(( is_same&lt; A, Z &gt;::type::value ));// assert, line 19 BOOST_MPL_ASSERT(( is_same&lt; A, A &gt; )); // OK BOOST_MPL_ASSERT(( is_same&lt; A, Z &gt; )); // assert, line 21 return 0; } </code></pre> <p>For comparison, here are the error messages my compiler (Microsoft Visual C++ 2008) generated for lines 19 and 21 above:</p> <pre><code>1&gt;static_assert.cpp(19) : error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE&lt;x&gt;' 1&gt; with 1&gt; [ 1&gt; x=false 1&gt; ] 1&gt;static_assert.cpp(21) : error C2664: 'boost::mpl::assertion_failed' : cannot convert parameter 1 from 'boost::mpl::failed ************std::tr1::is_same&lt;_Ty1,_Ty2&gt;::* ***********' to 'boost::mpl::assert&lt;false&gt;::type' 1&gt; with 1&gt; [ 1&gt; _Ty1=A, 1&gt; _Ty2=Z 1&gt; ] 1&gt; No constructor could take the source type, or constructor overload resolution was ambiguous </code></pre> <p>So if you're using metafunctions (as defined <a href="http://www.boost.org/doc/libs/1_38_0/libs/mpl/doc/refmanual/metafunction.html" rel="noreferrer">here</a>) as predicates then <code>BOOST_MPL_ASSERT</code> is both less verbose to code and more informative when it asserts.</p> <p>For simple boolean predicates, <code>BOOST_STATIC_ASSERT</code> is less verbose to code although its error messages may be less clear (depending on your compiler.)</p>
<p><code>BOOST_MPL_ASSERT</code> is (still) generally considered better. The messages from it are somewhat easier to see (and understand, if you use <code>BOOST_MPL_ASSERT_MSG</code>). There was some talk a few months ago about deprecating <code>BOOST_STATIC_ASSERT</code>, though I think everyone eventually agreed that there's still room for it in the world.</p>
23,515
<p>I'm considering using <a href="https://en.wikipedia.org/wiki/Category_6_cable" rel="noreferrer">CAT6</a> cables to connect my printer's extruder assembly to the control board. They seem like an elegant solution, but I've read conflicting opinions online on whether or not this would be feasible.</p> <p>I would like to know if CAT6 cables can handle the required current, whether I should be worried about electromagnetic interference or other problems, and how I should pair up the wires. Cable length would be 30cm max.</p> <p>Here are the relevant parts:</p> <ol> <li><a href="http://e3d-online.com/Heater-Cartridge-12v-40w" rel="noreferrer">E3D heater cartridge</a> (2 wires)</li> <li><a href="http://e3d-online.com/E3D-v6/Spares/Thermistor-Cartridge" rel="noreferrer">E3D thermistor cartridge</a> (2 wires)</li> <li><a href="http://e3d-online.com/E3D-v6/Spares/30x30x10mm-12v-DC-Fan" rel="noreferrer">30mm hotend fan</a> (2 wires)</li> <li><a href="https://printrbot.com/shop/auto-leveling-probe-2" rel="noreferrer">Z-axis auto-leveling probe</a> (3 wires)</li> <li><a href="https://docs.google.com/spreadsheets/d/1Q6nW_lToPZe6Kou6VbDMoQ3sFleCJ02XV0y4piXL_Fg/pubhtml" rel="noreferrer">NEMA 17 extruder motor</a> (4 wires)</li> <li><a href="https://www.amazon.co.uk/gp/product/B00MJUD1DW" rel="noreferrer">50mm part cooling fan</a> (2 wires)</li> </ol> <p><strong>[cable A]</strong> I imagine I would use one CAT6 cable for parts 1-4, which form a logical unit (and in the future I might combine them into a removable module). I've been given to understand that power for the fan can be spliced from the z-probe or heater cartridge, so 8 wires should be enough.</p> <p><strong>[cable B]</strong> I would use a second CAT6 cable for parts 5 and 6. There will be two spare wires, so I could potentially double the bandwidth for the motor.</p>
<p>The ampacity question is not completely answerable because CAT6 does not specify wire gauge, so the current limit will depend on the specific gauge you get. CAT6 can be anywhere from 22 AWG to 24 AWG, and depending on who you ask this can be good for as much as 7A or as little as 0.5A. Given that you will have a bunch of wires in a bundle, this may cause them to heat up more than if they were in free air. For the steppers (1-2A) a single wire should suffice, but for the heater (around 3-4A) you might want to double up.</p> <p>EMI will likely not cause any problems regardless of how you wire things up. CAT6 cables have the wires twisted in pairs of 2. Some people recommend to take advantage of these pairs: the +12V and GND of the heater should use a pair, each of the two coils of the steppers should have their own separate pairs. The reasoning behind this is that with equal current flowing in opposite directions in each wire of the pair, the generated electromagnetic fields will cancel out.</p> <p>Twisted pairs are usually used when dealing with multiple pairs of wires that are carrying high frequency signals that might affect each other. The main concern for crosstalk in this application is if the stepper motor might cause the endstop to be erroneously triggered, but this is only a concern during homing when the feedrate (and thus frequency of the signal) is low anyways.</p>
<p>CAT6 cable by itself is not a problem, it is typically 23 AWG solid core wire which can take you to 4A just fine. The real problem comes from the connectors you use. CAT6 usually goes hand in hand with 8p8c ethernet connectors which only have contacts rated to 500mA.</p> <p>Also typically CAT6 cable is meant to be stationary (hence the solid core wires), so I'd go for something stranded. <a href="https://www.mcmaster.com/#standard-electrical-wire/=15d9c3w" rel="nofollow noreferrer">McMaster sells some nice cheap cabling</a> that fits your needs, and it's actually meant for moving platforms like a CNC machine.</p>
441
<p>Is there a simple out of the box way to impersonate a user in .NET?</p> <p>So far I've been using <a href="http://www.codeproject.com/KB/cs/zetaimpersonator.aspx" rel="noreferrer">this class from code project</a> for all my impersonation requirements.</p> <p>Is there a better way to do it by using .NET Framework?</p> <p>I have a user credential set, (username, password, domain name) which represents the identity I need to impersonate.</p>
<p>&quot;Impersonation&quot; in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently.</p> <h2>Impersonation</h2> <p>The APIs for impersonation are provided in .NET via the <code>System.Security.Principal</code> namespace:</p> <ul> <li><p>Newer code should generally use <a href="https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.runimpersonated" rel="noreferrer"><code>WindowsIdentity.RunImpersonated</code></a>, which accepts a handle to the token of the user account, and then either an <code>Action</code> or <code>Func&lt;T&gt;</code> for the code to execute.</p> <pre><code>WindowsIdentity.RunImpersonated(userHandle, () =&gt; { // do whatever you want as this user. }); </code></pre> <p>or</p> <pre><code>var result = WindowsIdentity.RunImpersonated(userHandle, () =&gt; { // do whatever you want as this user. return result; }); </code></pre> <p>There's also <a href="https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.runimpersonatedasync" rel="noreferrer"><code>WindowsIdentity.RunImpersonatedAsync</code></a> for async tasks, available on .NET 5+, or older versions if you pull in the <a href="https://www.nuget.org/packages/System.Security.Principal.Windows" rel="noreferrer">System.Security.Principal.Windows</a> Nuget package.</p> <pre><code>await WindowsIdentity.RunImpersonatedAsync(userHandle, async () =&gt; { // do whatever you want as this user. }); </code></pre> <p>or</p> <pre><code>var result = await WindowsIdentity.RunImpersonated(userHandle, async () =&gt; { // do whatever you want as this user. return result; }); </code></pre> </li> <li><p>Older code used the <a href="https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.impersonate" rel="noreferrer"><code>WindowsIdentity.Impersonate</code></a> method to retrieve a <code>WindowsImpersonationContext</code> object. This object implements <code>IDisposable</code>, so generally should be called from a <code>using</code> block.</p> <pre><code>using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userHandle)) { // do whatever you want as this user. } </code></pre> <p>While this API still exists in .NET Framework, it should generally be avoided.</p> </li> </ul> <h2>Accessing the User Account</h2> <p>The API for using a username and password to gain access to a user account in Windows is <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184.aspx" rel="noreferrer"><code>LogonUser</code></a> - which is a Win32 native API. There is not currently a built-in managed .NET API for calling it.</p> <pre><code>[DllImport(&quot;advapi32.dll&quot;, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); </code></pre> <p>This is the basic call definition, however there is a lot more to consider to actually using it in production:</p> <ul> <li>Obtaining a handle with the &quot;safe&quot; access pattern.</li> <li>Closing the native handles appropriately</li> <li>Code access security (CAS) trust levels (in .NET Framework only)</li> <li>Passing <code>SecureString</code> when you can collect one safely via user keystrokes.</li> </ul> <p>Instead of writing that code yourself, consider using my <a href="https://github.com/mattjohnsonpint/SimpleImpersonation" rel="noreferrer">SimpleImpersonation</a> library, which provides a managed wrapper around the <code>LogonUser</code> API to get a user handle:</p> <pre><code>using System.Security.Principal; using Microsoft.Win32.SafeHandles; using SimpleImpersonation; var credentials = new UserCredentials(domain, username, password); using SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.Interactive); // or another LogonType </code></pre> <p>You can now use that <code>userHandle</code> with any of the methods mentioned in the first section above. This is the preferred API as of version 4.0.0 of the SimpleImpersonation library. See the project readme for more details.</p> <h2>Remote Computer Access</h2> <p>It's important to recognize that impersonation is a <em>local machine</em> concept. One cannot impersonate using a user that is only known to a remote machine. If you want to access resources on a remote computer, the local machine and the remote machine must be attached to the same domain, or there needs to be a trust relationship between the domains of the two machines. If either computer is domainless, you cannot use <code>LogonUser</code> or SimpleImpersonation to connect to that machine.</p>
<p>You can use this solution. (Use nuget package) The source code is available on : Github: <a href="https://github.com/michelcedric/UserImpersonation" rel="nofollow">https://github.com/michelcedric/UserImpersonation</a></p> <p>More detail <a href="https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/" rel="nofollow">https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/</a></p>
15,234
<p>Say we have a TestClass with the 2 methods, <code>-getSomeString</code> and <code>-getAnotherString</code>, and we are editing the following code and the cursor is in the location shown:</p> <pre><code>NSString *aString = [TestClass get&lt;cursorIsHere&gt;SomeString]; </code></pre> <p>Say I want to change it to use <code>-getAnotherString</code>. If I bring up the auto-completion popup and select the other method via hitting enter or tab, I'm left with:</p> <pre><code>NSString *aString = [TestClass getAnotherStringSomeString]; </code></pre> <p>i.e., it doesn't replace the existing text but rather just inserts.</p> <p>Is there a special keystroke to make it replace the remaining text?</p> <p>See IntelliJ for reference.</p>
<p>I don't think that there is a one step operation to achieve this. My suggestion would be similar to Thomas Templemann, but rather than two steps of forward word select and then Delete, I would expand to the desired autocomplete, by bouncing on <strong>Control + .</strong> and then hit <strong>Option + forward delete</strong>, which kills to the end of the word.</p>
<p>I don't think so. I have always used the following</p> <ul> <li>double click on getSomeString</li> <li>press Escape (or your autocomplete key)</li> <li>find replacement method</li> </ul> <p>that double click step has never really bothered me, but I would be interested if anyone knows better!</p>
42,410
<p>I have a device that supports 4-color graphics (much like CGA in the old days).</p> <p>I wanted to use <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p> <p>A simple python example would be much appreciated!</p> <p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
<p>First: your four colour palette (black, green, red, yellow) has <em>no</em> blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.</p> <p>Try this code:</p> <pre><code>import Image def estimate_color(c, bit, c_error): c_new= c - c_error if c_new &gt; 127: c_bit= bit c_error= 255 - c_new else: c_bit= 0 c_error= -c_new return c_bit, c_error def image2cga(im): "Produce a sequence of CGA pixels from image im" im_width= im.size[0] for index, (r, g, b) in enumerate(im.getdata()): if index % im_width == 0: # start of a line r_error= g_error= 0 r_bit, r_error= estimate_color(r, 1, r_error) g_bit, g_error= estimate_color(g, 2, g_error) yield r_bit|g_bit def cvt2cga(imgfn): "Convert an RGB image to (K, R, G, Y) CGA image" inp_im= Image.open(imgfn) # assume it's RGB out_im= Image.new("P", inp_im.size, None) out_im.putpalette( ( 0, 0, 0, 255, 0, 0, 0, 255, 0, 255, 255, 0, ) ) out_im.putdata(list(image2cga(inp_im))) return out_im if __name__ == "__main__": import sys, os for imgfn in sys.argv[1:]: im= cvt2cga(imgfn) dirname, filename= os.path.split(imgfn) name, ext= os.path.splitext(filename) newpathname= os.path.join(dirname, "cga-%s.png" % name) im.save(newpathname) </code></pre> <p>This creates a PNG palette image with only the first four palette entries set to your colours. This sample image:</p> <p><a href="https://i.stack.imgur.com/BBxf1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBxf1.jpg" width="320"></a></p> <p>becomes</p> <p><a href="https://i.stack.imgur.com/QxtCD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QxtCD.png" width="320"></a></p> <p>It's trivial to take the output of <code>image2cga</code> (yields a sequence of 0-3 values) and pack every four values to a byte.</p> <p>If you need help about what the code does, please ask and I will explain.</p> <h3>EDIT1: Do not reinvent the wheel</h3> <p>Of course, turns out I was too enthusiastic and —as Thomas discovered— the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above:</p> <pre><code>def cga_quantize(image): pal_image= Image.new("P", (1,1)) pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252) return image.convert("RGB").quantize(palette=pal_image) </code></pre> <h3>EDIT1, cont: Pack the pixels into bytes</h3> <p>For "added value", here follows code to produce the packed string (4 pixels per byte):</p> <pre><code>import itertools as it # setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys # and values [chr(0)‥chr(255)], because PIL does not yet support # 4 colour palette images TUPLE2CHAR= {} # Assume (b7, b6) are pixel0, (b5, b4) are pixel1… # Call it "big endian" KEY_BUILDER= [ (0, 64, 128, 192), # pixel0 value used as index (0, 16, 32, 48), # pixel1 (0, 4, 8, 12), # pixel2 (0, 1, 2, 3), # pixel3 ] # For "little endian", uncomment the following line ## KEY_BUILDER.reverse() # python2.6 has itertools.product, but for compatibility purposes # let's do it verbosely: for ix0, px0 in enumerate(KEY_BUILDER[0]): for ix1, px1 in enumerate(KEY_BUILDER[1]): for ix2, px2 in enumerate(KEY_BUILDER[2]): for ix3, px3 in enumerate(KEY_BUILDER[3]): TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3) # Another helper function, copied almost verbatim from itertools docs def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --&gt; ('a','b','c'), ('d','e','f'), ('g','x','x')" return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n) # now the functions def seq2str(seq): """Takes a sequence of [0..3] values and packs them into bytes using two bits per value""" return ''.join( TUPLE2CHAR[four_pixel] for four_pixel in grouper(4, seq, 0)) # and the image related function # Note that the following function is correct, # but is not useful for Windows 16 colour bitmaps, # which start at the *bottom* row… def image2str(img): return seq2str(img.getdata()) </code></pre>
<pre><code>import sys import PIL from PIL import Image def quantizetopalette(silf, palette, dither=False): """Convert an RGB or L mode image to use a given P image's palette.""" silf.load() # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if silf.mode != "RGB" and silf.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = silf.im.convert("P", 1 if dither else 0, palette.im) # the 0 above means turn OFF dithering return silf._makeself(im) if __name__ == "__main__": import sys, os for imgfn in sys.argv[1:]: palettedata = [ 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 0,] palimage = Image.new('P', (16, 16)) palimage.putpalette(palettedata + [0, ] * 252 * 3) oldimage = Image.open(sys.argv[1]) newimage = quantizetopalette(oldimage, palimage, dither=False) dirname, filename= os.path.split(imgfn) name, ext= os.path.splitext(filename) newpathname= os.path.join(dirname, "cga-%s.png" % name) newimage.save(newpathname) </code></pre> <p>For those that wanted NO dithering to get solid colors. i modded: <a href="https://stackoverflow.com/questions/29433243/convert-image-to-specific-palette-using-pil-without-dithering">Convert image to specific palette using PIL without dithering</a> with the two solutions in this thread. Even though this thread is old, some of us want that information. Kudios</p>
29,290
<p>From using a number of programming languages and libraries I have noticed various terms used for the total number of elements in a collection.</p> <p>The most common seem to be <code>length</code>, <code>count</code>, and <code>size</code>.</p> <p>eg.</p> <pre><code>array.length vector.size() collection.count </code></pre> <p>Is there any preferred term to be used? Does it depend on what type of collection it is? ie. mutable/immutable</p> <p>Is there a preference for it being a property instead of a method?</p>
<p><code>Length()</code> tends to refer to contiguous elements - a string has a length for example. </p> <p><code>Count()</code> tends to refer to the number of elements in a looser collection. </p> <p><code>Size()</code> tends to refer to the size of the collection, often this can be different from the length in cases like vectors (or strings), there may be 10 characters in a string, but storage is reserved for 20. It also may refer to number of elements - check source/documentation.</p> <p><code>Capacity()</code> - used to specifically refer to allocated space in collection and not number of valid elements in it. If type has both "capacity" and "size" defined then "size" usually refers to number of actual elements.</p> <p>I think the main point is down to human language and idioms, the size of a string doesn't seem very obvious, whilst the length of a set is equally confusing even though they might be used to refer to the same thing (number of elements) in a collection of data.</p>
<p>To me, this is a little like asking whether "foreach" is better than "for each". It just depends on the language/framework.</p>
38,528
<p>Is it recommended to set member variables of a base class to protected, so that subclasses can access these variables? Or is it more recommended to set the member variables to private and let the subclasses get or set the varible by getters and setters?</p> <p>And if it is recommended to use the getters and setters method, when are protected variables used?</p>
<p>This is very <em>similar</em> to <a href="https://stackoverflow.com/questions/355787">this question</a>, about whether to access information within the same class via properties or direct access. It's probably worth reading all those answers too.</p> <p>Personally, I don't like any fields to be non-private with the occasional exception of static readonly fields with immutable values (whether const or not). To me, properties just give a better degree of encapsulation. How data is stored is an <em>implementation</em> decision, not an <em>API</em> decision (unlike properties). Why should class Foo deriving from class Bar care about the <em>implementation</em> of class Bar?</p> <p>In short, I'd always go for properties, and I don't use protected variables for anything other than throwaway test code.</p> <p>With automatically implemented properties in C# 3.0, it's easier than ever before to turn fields into properties. There's precious little reason <em>not</em> to do it.</p>
<p>This is a trade-off here. Setters and getters are somewhat slower than accessing fields directly, so if you are doing heavy maths and read/write these fields a lot in your subclasses, you should go for accessing the fields directly. But this is more like an exception.</p> <p>Normally, you should mark them as private and go for getters/setters.</p> <p>So my answer is: direct access for heavily used fields, getters/setters otherwise. Use common sense.</p> <p><strong>EDIT: I did some profiling and apparently even in Release mode, there can be up the 20% speed difference between fields and properties.</strong> See my test case here: <a href="http://pastebin.com/m5a4d1597" rel="nofollow noreferrer">http://pastebin.com/m5a4d1597</a></p>
47,340
<p>I am trying to extract a gif image embedded as a resource within my ISAPI dll using WebBroker technology. The resource has been added to the DLL using the following RC code:</p> <pre><code>LOGO_GIF RCDATA logo.gif </code></pre> <p>Using resource explorer I verified it is in the DLL properly.</p> <p>using the following code always throws an exception, "resource not found" (using Delphi 2009)</p> <pre><code>var rc : tResourceStream; begin rc := tResourceStream.Create(hInstance,'LOGO_GIF','RCDATA'); end; </code></pre>
<p>RCDATA is a <a href="http://msdn.microsoft.com/en-us/library/aa381039(VS.85).aspx" rel="nofollow noreferrer">pre-defined</a> resource type with an integer ID of RT_RCDATA (declared in Types unit).</p> <p>Try accessing it this way:</p> <pre><code>rc := tResourceStream.Create(hInstance,'LOGO_GIF', MakeIntResource(RT_RCDATA)); </code></pre>
<p>If I remember correctly you are actually dealing with an instance of the web server, not the dll. I don't remember the work around though, but that is the explanation for why that doesn't work. Hopefully someone else can build off of this.</p>
11,519
<p>The array has lots of data and I need to delete two elements. </p> <p>Below is the code snippet I am using,</p> <pre><code>my @array = (1,2,3,4,5,5,6,5,4,9); my $element_omitted = 5; @array = grep { $_ != $element_omitted } @array; </code></pre>
<p>Use splice if you already know the index of the element you want to delete.</p> <p>Grep works if you are searching.</p> <p>If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.</p> <p>If it makes sense in your context, you may want to consider using a "magic value" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of "live" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.</p> <p><strong>Edit</strong> Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)</p> <pre><code>my $index = 0; $index++ until $arr[$index] eq 'foo'; splice(@arr, $index, 1); </code></pre> <p>That will delete the first occurrence. Deleting all occurrences is very similar, except you will want to get all indexes in one pass:</p> <pre><code>my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr; </code></pre> <p>The rest is left as an excercise for the reader -- remember that the array changes as you splice it!</p> <p><strong>Edit2</strong> John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.</p>
<p>If you know the array index, you can <a href="http://perldoc.perl.org/functions/delete.html" rel="nofollow noreferrer">delete()</a> it. The difference between splice() and delete() is that delete() does not renumber the remaining elements of the array.</p>
20,999
<p>I am trying to display a pie chart that shows sales by company. However there are a lot of companies that only have a tiny sales which makes the pie chart look rubbish. </p> <p>Is there a way to group companies like this into a single "Other" category?</p>
<p>Chart Expert -> Data then select your "on change of" field then click the TopN button. From here you can specify what to do with the smaller amounts. I usually group together the bottom 5% into an "other" group.</p>
<p>You could always make two pie charts from your data - one showing the main players and the other showing a blow-up of your smaller company data.</p>
45,884
<p>What considerations do I need to make if I want my code to run correctly on both 32bit and 64bit platforms ?</p> <p>EDIT: What kind of areas do I need to take care in, e.g. printing strings/characters or using structures ?</p>
<p>Options:</p> <p>Code it in some language with a <a href="http://en.wikipedia.org/wiki/Virtual_machine" rel="nofollow noreferrer">Virtual Machine</a> (such as Java)</p> <p>Code it in .NET and don't target any specific architecture. The <a href="http://www.dotnet-guide.com/jit.html" rel="nofollow noreferrer">.NET JIT compiler</a> will compile it for you to the right architecture before running it.</p>
<p>I assume you are still talking about <em>compiling</em> them separately for each individual platform? As running them on both is completely doable by just creating a 32bit binary.</p>
5,247
<p>When you login to Stackoverflow you see a button with the openID logo between the text input field and the submit button.</p> <p>When you click this button you get a dropdown with the main openID providers. This is an integrated 3rd party service called 'ID selector' which has been deprecated in favour of it's successor RPX (<a href="http://rpxnow.com" rel="nofollow noreferrer">rpxnow.com</a>). RPX even gives the user the possibility to login with existing Facebook, AOL, Google, etc. accounts.</p> <p>This is an <strong>excellent service</strong> but I need it in <em>German</em> and it seems it's only available in <em>English</em>.</p> <p>Has anyone encountered this problem and can share thoughts? Or has anyone even solved it? It would be a pitty if I couldn't use this great service just because there is no way to translate (@PhiLho: see*) these few strings in the js popup...</p> <p><strong>EDIT</strong>: *as a programming term: fetch, translate, return... like translate();</p> <p>The question is, can I get the strings out and inject my translations?</p>
<p>Thanks for the kind word on RPX. Translations are on the shortterm roadmap.</p> <p>UPDATE: Translations have been implemented.</p>
<p>You might want to check out DotNetOpenID which I started incorporating in <a href="http://stacked-ra.ajax.org" rel="nofollow noreferrer">Stacked</a> yesterday in fact. I haven't gotten to play much around with it, and obviously I don't care about anything else then English (yet at least) but it seems promising... :)</p>
42,120
<p>What are the benefits of doing static code analysis on your source code? I was playing around with FxCop and I was wondering if there any benefits beyond making sure you are following the coding standards. </p>
<p>There are all kinds of benefits:</p> <ol> <li>If there are anti-patterns in your code, you can be warned about it.</li> <li>There are certain metrics (such as McCabe's Cyclomatic Complexity) that tell useful things about source code.</li> <li>You can also get great stuff like call-graphs, and class diagrams from static analysis. Those are wonderful if you are attacking a new code base.</li> </ol> <p>Take a look at <a href="http://www.campwoodsw.com/sourcemonitor.html" rel="noreferrer">SourceMonitor</a></p>
<p>actually, fxcop doesn't particularly help you follow a coding standard. What it does help you with is designing a well-thought out framework/API. It's true that parts of the coding standard (such as casing of public members) will be caught by FxCop, but coding standards isn't the focus.</p> <p>coding standards can be checked with <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="nofollow noreferrer">stylecop</a>, which checks the source code instead of the MSIL like fxcop does.</p>
12,975
<p>I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process.</p> <p>I've looked into the various <code>exec()</code>, <code>shell_exec()</code>, <code>pcntl_fork()</code>, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?</p>
<p>If it "doesn't care about the output", couldn't the exec to the script be called with the <code>&amp;</code> to background the process?</p> <p><strong>EDIT</strong> - incorporating what @<a href="https://stackoverflow.com/users/1103/adamthehutt">AdamTheHut</a> commented to this post, you can add this to a call to <code>exec</code>:</p> <pre><code>" &gt; /dev/null 2&gt;/dev/null &amp;" </code></pre> <p>That will redirect both <code>stdio</code> (first <code>&gt;</code>) and <code>stderr</code> (<code>2&gt;</code>) to <code>/dev/null</code> and run in the background.</p> <p>There are other ways to do the same thing, but this is the simplest to read.</p> <hr> <p>An alternative to the above double-redirect:</p> <pre><code>" &amp;&gt; /dev/null &amp;" </code></pre>
<p>I can not use <code> &gt; /dev/null 2&gt;/dev/null &amp;</code> on Windows, so I use <code>proc_open</code> instead. I run PHP 7.4.23 on Windows 11.</p> <p>This is my code.</p> <pre class="lang-php prettyprint-override"><code> function run_php_async($value, $is_windows) { if($is_windows) { $command = 'php -q '.$value.&quot; &quot;; echo 'COMMAND '.$command.&quot;\r\n&quot;; proc_open($command, [], $pipe); } else { $command = 'php -q '.$value.&quot; &gt; /dev/null 2&gt;/dev/null &amp;&quot;; echo 'COMMAND '.$command.&quot;\r\n&quot;; shell_exec($command); } } $tasks = array(); $tasks[] = 'f1.php'; $tasks[] = 'f2.php'; $tasks[] = 'f3.php'; $tasks[] = 'f4.php'; $tasks[] = 'f5.php'; $tasks[] = 'f6.php'; $is_windows = true; foreach($tasks as $key=&gt;$value) { run_php_async($value, $is_windows); echo 'STARTED AT '.date('H:i:s').&quot;\r\n&quot;; } </code></pre> <p>In each files to be execute, I put delay this:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php sleep(mt_rand(1, 10)); file_put_contents(__FILE__.&quot;.txt&quot;, time()); </code></pre> <p>All files are executed asynchronously.</p>
27,439
<p>I have two tables. Club and Coach. Between them is 0,1 - 0,1 relationship (coach can have zero or one club. club can have zero or one coach). When I want to change the coach of the given club, i have to update the club table. So i have to change idCoach of that club. Lets consider a new coach (the newly assigned coach of the given club) is already a coach of some other club. I have to set to Null field idCoach of that club, because his coach will be assigned to another club. Also if the club for which I want to change the coach, already has a coach, then I have to set idClub of that coach (in Coach table) to Null.</p> <p>All the given above, also applies to when I want to change the club of the certain coach. (have to set to Null idCoach field of the previous club of a given coach and have to set to null idCoach of the new club) .</p> <p>The same problems could occur when I insert new record in Club or Coach table, or if I delete the existing (in insert, update and delete I have to watch out for the corresponding references and unlink them).</p> <p>I want to solve this with triggers. I guess I would have to have 3 triggers in Club table (for insert, update and delete) and 3 more in Coach table.</p> <p>In update trigger (for example in Club) I have to update Coach table which will again trigger update in Club (cause in it's body it has to update Club table) and that trigger will update Coach and trigger and so forth. So I'll have a dead lock.</p> <p>How to solve this?</p> <p>This is the first time ever I work with triggers, so sorry in advance, for this big explanation of a simple thing. </p> <p>Cheers!</p>
<p>I suggest this might not be an appropriate use for triggers, which are very difficult to debug, and often surprise people by the way they don't support single-record operations as you would expect. Break it down into simple SQL statements and wrap a transaction around it instead.</p>
<p>I recommend avoiding triggers if you can. If you must try and use Instead of triggers instead of normal triggers. The difference is instead of triggers fire before any data is actually modified. With that said I think your much better off using stored procedures, and looking to see if you </p> <p>Another suggestion is if you could model this instead as an associative entity. I assume that The coach of the club must also be the club's coach. So what you could do is create a CoachAssignment table, now you only have to maintain this one record. If you ever need a coach to belong to multiple clubs the model is there for you.</p> <p>With that said, you can use the If Update(FieldName) syntax to only update the tables you actually need. If you need to stop a recursive trigger you can prevent this by checking TRIGGER_NESTLEVEL()</p>
38,051
<p>Vista SP1 Visual Studio 2008 SP1 .NET 3.5 SP1 C#</p> <p>I have a winforms app I'm playing with that uses a SerialPort object as a private variable. When the application is compiled and executed, it works great. It also works running in debug mode wihtout any breakpoints. 90% of the time when I stop at a breakpoint and try to step through code I get an 'unhandled exception ocurred' dialog with these details:</p> <p>System.ObjectDisposedException was unhandled Message="Safe handle has been closed" Source="mscorlib" ObjectName="" StackTrace: at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle) at System.Threading.EventWaitHandle.Set() at System.IO.Ports.SerialStream.AsyncFSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) InnerException:</p> <p>The frustrating thing is, I do not have to be stepping over serial-related code! I just have to have done <em>something</em> with the port. So I might read a string, manipulate the string, add two numbers together, whatever, and then BANG.</p> <p>Again, this works just fine when NOT debugging, or when debugging wihtout any breakpoints. There seems to be something about stopping at a breakpoint that makes the CLR dispose the SerialStream on a different thread.</p> <p>There is a lot of chatter online about problems with renoving USB devices causing this. But I'm using the build-in motherboard port on COM1.</p> <p>I don't think I had this issue in .NET 2.0 so I may have to go back to that...</p> <p>I need to simplify the application quite a bit before I can post code - but has anyone seen behavior like this in the debugger before?</p> <p>Thanks so much!</p>
<p>I had the same problem just this morning. Surprisingly, it simply has gone away when I DISABLED the following options in VS2008 Tools->Options->Debugging->General:</p> <ul> <li>"Enable the exception assistant"</li> <li>"Enable .NET Framework source stepping"</li> <li>"Step over properties and operators"</li> <li>"Enable property evaluation and other implicit function calls"</li> </ul> <p>I have no idea why, but it worked for me.</p>
<p>Well I'm not so sure this is an answer, but there was definately something about that project. It was originally written in 2.0 and converted to 3.5 by VS2008. I created a new project in C#-Express 2008 adding the original classes one-by-one and it works like a charm now! No idea what is different.</p>
37,043
<p>What is the best way to detect if a user leaves a web page?</p> <p>The <code>onunload</code> JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).</p> <p>Creating one will probably be blocked by current browsers.</p>
<p>Try the <code>onbeforeunload</code> event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo <em><a href="https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm" rel="noreferrer">onbeforeunload Demo</a></em>.</p> <p>Alternatively, you can send out an <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> request when he leaves.</p>
<p>For What its worth, this is what I did and maybe it can help others even though the article is old.</p> <p>PHP:</p> <pre><code>session_start(); $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; if(isset($_SESSION['userID'])){ if(!strpos($_SESSION['activeID'], '-')){ $_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID']; } }elseif(!isset($_SESSION['activeID'])){ $_SESSION['activeID'] = time(); } </code></pre> <p>JS</p> <pre><code>window.setInterval(function(){ var userid = '&lt;?php echo $_SESSION['activeID']; ?&gt;'; var ipaddress = '&lt;?php echo $_SESSION['ipaddress']; ?&gt;'; var action = 'data'; $.ajax({ url:'activeUser.php', method:'POST', data:{action:action,userid:userid,ipaddress:ipaddress}, success:function(response){ //alert(response); } }); }, 5000); </code></pre> <p>Ajax call to activeUser.php</p> <pre><code>if(isset($_POST['action'])){ if(isset($_POST['userid'])){ $stamp = time(); $activeid = $_POST['userid']; $ip = $_POST['ipaddress']; $query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1"; $results = RUNSIMPLEDB($query); if($results-&gt;num_rows &gt; 0){ $query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1"; RUNSIMPLEDB($query); }else{ $query = "INSERT INTO activeusers (activeid,stamp,ip) VALUES ('".$activeid."','$stamp','$ip')"; RUNSIMPLEDB($query); } } } </code></pre> <p>Database:</p> <pre><code>CREATE TABLE `activeusers` ( `id` int(11) NOT NULL, `activeid` varchar(20) NOT NULL, `stamp` int(11) NOT NULL, `ip` text ) ENGINE=MyISAM DEFAULT CHARSET=utf8; </code></pre> <p>Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.</p> <p>Probably not the most efficient solution but it does the job.</p>
17,773
<p>My organization is starting to take SOA seriously but before we jump in one of the components we seem to be missing is a rock solid repository for tracking these services across the enterprise. Can anyone suggest a product that they have worked with? If the product is also an ESB please mention that in your answer.</p>
<p>You might like to take a look at IBM's WebSphere Service Registry and Repository. It does what you describe (with governance abilities as well), and integrates nicely with IBM's ESB products (although it not one itself).</p> <p>Please feel free to get in touch if you want to ask any questions.</p> <p>Disclaimer: I work for IBM as a WebSphere Consultant. However, I am not speaking for them in an official capacity.</p>
<p>I also have worked for IBM and I would stay away from WSRR - it is buggy, immature, expensive and overly complex. I would not recommend it.</p>
26,451
<p>While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of</p> <pre><code>Name : Value Name2 : Value2 </code></pre> <p>etc.</p> <p>The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form <code>2.20011E+17</code>. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?</p>
<p>You hav to convert your input into a number and then round them:</p> <pre><code>function toInteger(number){ return Math.round( // round to nearest integer Number(number) // type cast your input ); }; </code></pre> <p>Or as a one liner:</p> <pre><code>function toInt(n){ return Math.round(Number(n)); }; </code></pre> <p>Testing with different values:</p> <pre><code>toInteger(2.5); // 3 toInteger(1000); // 1000 toInteger("12345.12345"); // 12345 toInteger("2.20011E+17"); // 220011000000000000 </code></pre>
<p>Math.floor(19.5) = 19 should also work.</p>
30,549
<p>From a web developer point of view, what changes are expected in the development arena when Google Chrome is released?</p> <p>Are the developments powerful enough to make another revolution in the web? Will the way we see web programming change?</p> <p>Or is it just another web browser?</p>
<p>I think this is just another web browser. The most impact I expect to be improved Javascript performance, and the usability perspective. The first will benefit developers, especially when using Google Gears. I think the users will benefit the most from an enhanced user experience, the safety features, and ease of use.</p> <p>I can only hope other browser vendors (MS) will follow Mozilla and Google to create a faster Javascript implementation, since this is the only thing that can truly impact web development.</p>
<p>@bpapa</p> <blockquote> <p>It's just another web browser that very few people are going to use because there are already 4 major browsers out there that work just fine for most people. It doesn't have the extensions like Firefox,</p> </blockquote> <p>Actually, it is pretty clear that it has a plugin architecture</p> <blockquote> <p>it doesn't have browser sync with an iPhone like Safari, it doesn't come with your computer like IE, and it doesn't... well I don't know what Opera does that makes it stand out but I don't think Chrome has it.</p> </blockquote> <p>"I don't know what Opera has, but this piece of software that I've never touched clearly doesn't have it"... what??</p> <blockquote> <p>Another reason why I don't see it taking off - since it's not on OS X a lot of tech people aren't going to be using it.</p> </blockquote> <p>Did you miss the part where the Linux and OS X distros are coming right behind Windows?</p>
6,091
<p>I remember looking at D about 2 years ago, and it looked nice, was actually faster than C for some of the typical language benchmarks, and in general seemed ok, but I didn't find any real projects written in D back then, so I just left as a I came. </p> <p>Now that a few years have passed I was wondering if there have been any projects done in D, hopefully open source to look at the code and see how its going, or is D dead?</p>
<p>Check the projects in <a href="http://www.dsource.org/projects/" rel="noreferrer">DSource</a>.</p> <p>Give a look also to the <a href="http://www.digitalmars.com/d/dlinks.html" rel="noreferrer">DLinks</a> page.</p>
<p>look also at <a href="http://code.google.com/hosting/search?q=label:d&amp;btn=Search+Projects" rel="nofollow noreferrer">code.google.com</a> for some more D projects.</p>
48,374
<p>In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:</p> <pre><code>APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) </code></pre> <p>to create a drop down box in your form and force the user to choose one of those options.</p> <p>I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.</p>
<p>In terms of the forms library, you would use the <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield" rel="noreferrer">MultipleChoiceField</a> field with a <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple" rel="noreferrer">CheckboxSelectMultiple</a> widget to do that. You could validate the number of choices which were made by writing a validation method for the field:</p> <pre><code>class MyForm(forms.Form): my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple()) def clean_my_field(self): if len(self.cleaned_data['my_field']) &gt; 3: raise forms.ValidationError('Select no more than 3.') return self.cleaned_data['my_field'] </code></pre> <p>To get this in the admin application, you'd need to customise a ModelForm and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="noreferrer">override the form used in the appropriate ModelAdmin</a>.</p>
<p>@JonnyBuchanan gave the right answer.</p> <p>But if you need this in the django admin for many models, and you're (like me) too lazy to customize a ModelForm and ovverride the right methods inside the ModelAdmin class, you can use this approach:</p> <p><a href="http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/" rel="nofollow">http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/</a></p>
17,793
<p>im trying to kick off a Runnable classes run method however i keep getting a NullPointerException, Im using WebSpheres commonj.workmanager to get an instance of executorService.this is the code im using.</p> <pre><code>executorService.execute(new Runnable() { public void run() { System.out.println("Inside run ()method.."); } }); ANY IDEAS? </code></pre>
<p>Are you checking whether <code>executorService</code> is null before calling <code>execute()</code>? If not, it sounds like you need to check the WebSphere docs.</p>
<p>thanks for the reply, its the <code>executorService</code> that is <code>null</code>. Im using Spring to inject the property.</p>
38,308
<p>I need to deploy a Delphi app in an environment that needs centralized data and file storage system (for document imaging) but has multiple branch offices with relatively poor inter connectivity. I believe a 3 tier database application is the best way to go so I can provide a rich desktop experience with relatively light-weight data transfer needs. So far I have looked briefly at Delphi Datasnap, kbmMW and Remobjects SDK. It seems that kbmMW and Remobjects SDK use the least bandwidth. Does anyone have any experience in deploying any of these technologies in a challenging environments with a significant number of users (I need to support 700+)? Thanks!</p>
<p>Depends if you are tied to remote datasets. If you aren't dataset bound then SOAP would likely be a good choice. Or, what I've done is write my own protocol that is similar to SOAP in nature. This was done before SOAP was standard and I'm glad I did - this gives you the ability to control more of the flow of data. It's given that if you have poor connectivity then you will be spending time supporting it. It's very nice if it's your own code you are supporting versus having to wait on a vendor. (Although KBM and REM are known to be pretty good vendors.)</p> <p>Personal note: 700 users in a document imaging application over poor connectivity sounds like a mess. Spend the money on upgrading connectivity as it'll be cheaper in the long run.</p>
<p>If you really wanna go "low-bandwidth" use BSD Sockets API - that'll give you full control over what's being sent and there you can send as little information as you want. Of course then you'll have to implement all the tiers yourself, but hey - that's still <em>an option</em> :D</p>
47,202
<p>When using MySQL full text search in boolean mode there are certain characters like + and - that are used as operators. If I do a search for something like "C++" it interprets the + as an operator. What is the best practice for dealing with these special characters?</p> <p>The current method I am using is to convert all + characters in the data to _plus. It also converts &amp;,@,/ and # characters to a textual representation.</p>
<p>There's no way to do this in nicely using MySQL's full text search. What you're doing (substituting special characters with a pre-defined string) is the only way to do it.</p> <p>You may wish to consider using <a href="http://www.sphinxsearch.com/" rel="noreferrer">Sphinx Search</a> instead. It apparently supports escaping special characters, and by all reports is significantly faster than the default full text search.</p>
<p>MySQL is fairly brutal in what tokens it ignores when building its full text indexes. I'd say that where it encountered the term "C++" it would probably strip out the plus characters, leaving only C, and then ignore that because it's too short. You could probably configure MySQL to include single-letter words, but it's not optimised for that, and I doubt you could get it to treat the plus characters how you want.</p> <p>If you have a need for a good internal search engine where you can configure things like this, check out <a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a> which has been ported to various languages <a href="http://ifacethoughts.net/2008/02/07/zend-brings-lucene-to-php/" rel="nofollow noreferrer">including PHP (in the Zend framework)</a>.</p> <p>Or if you need this more for 'tagging' than text search then something else may be more appropriate.</p>
37,042
<p>I have a factory that returns an interface <code>FormatService</code>: </p> <pre><code>public class FormatServiceFactory { public FormatService getService() { ... } } </code></pre> <p>Is it possible to mock out this factory so that it will always return a stub implementation of <code>FormatService</code> - <code>FormatServiceStub</code> in our unit tests? </p>
<p>Depends. How is the factory obtained/used by the code under test? </p> <p>If it's instantiated explicitly in the methods you're testing, or if it's a static factory, you won't be able to mock it. </p> <p>If it's injected into the object under test, you can create and inject the mocked factory before executing the test.</p> <p>Mocking the factory should be easy enough with JMock. From your example code, it looks like it's a class, not an interface, so you'll either need to use the cglib version of JMock and the <a href="http://www.jmock.org/jmock1-cglib.html" rel="nofollow noreferrer">MockObjectTestCase</a> class in the cglib package for JMock 1, or the <a href="http://www.jmock.org/mocking-classes.html" rel="nofollow noreferrer">ClassImposteriser</a> for JMock 2. </p> <p>Once mocked, you can make it return your stubbed implementation (or even a mock FormatService) when you define the expectations for the getService() method.</p>
<p>Mockery mockery = new JUnit4Mockery() {{setImposteriser(ClassImposteriser.INSTANCE);}};</p> <p>final FormatServiceFactory factory = mockery.mock(FormatServiceFactory .class);</p> <p>context.checking(new Expectations() {{ oneOf (factory ).getService(); will(returnValue(new FormatServiceMock())); }});</p>
35,327
<p>We are building an application on an embedded platform that needs a reasonably high performance database (very low select speeds on tables with > 500,000 entries).<br> <br> The database needs to be able to : <li> Store atomic commit information in NVRAM so that such information is preserved if power fails before the commit finishes. <li> Be written to NAND Flash in such a way as to level wearing across the memory (could be done using, e.g. jffs2 or yaffs2).<br> <br> Currently our options appear to be a "roll-your own" approach, or possibly SQLite.<br> <br>Any other options, or pointers about the details of "rolling your own" or working with SQLite appreciated! <br> <br> <b> Edit:</b> The target has 32MB of RAM, 1MB of NVRAM and 64MB of NAND Flash. The rest of the code is C, so that is the preferred language. The target processor is an ARM. In general, the queries that need to have the most performance are pretty simple. Complex queries don't need to have the same level of performance.</p>
<p>Apple's iPhone (and iPod Touch) uses the SQLite DB for a lot of its functions, so there's definitely a proven flash-based platform there. However, I doubt the amount of data in any of those tables has > 500k rows.</p>
<p>Codebase provides a solid portable lightweight fast isam with transactions.</p>
47,611
<p>Alan Kay was quoted several years ago to the effect that there had been only three new things in software in the preceding 20 years (effectively the lifespan of PCs). One of them was Spreadsheets.</p> <p>Does anyone remember the other two?</p> <p>Who is Alan Kay? (a few may ask.) His work at Xerox Parc arguably did more to shape our current software paradigm than any other influence.</p>
<p>I will try to remember what I said, but none of the answers so far are correct (every one of them was done in the 60s and 70s before the commercialization of PCs in the 80s).</p> <p>However, we could start all over and try to think of <a href="https://stackoverflow.com/q/432922/1288">new inventions in computing since the 1980s</a>.</p>
<p>Mice and GUI's</p>
46,659
<p>How can I print a message to the error console, preferably including a variable? </p> <p>For example, something like:</p> <pre><code>print('x=%d', x); </code></pre>
<p>Install <a href="http://en.wikipedia.org/wiki/Firebug_(software)" rel="noreferrer">Firebug</a> and then you can use <code>console.log(...)</code> and <code>console.debug(...)</code>, etc. (see <a href="http://getfirebug.com/wiki/index.php/Console_Panel#Message_types" rel="noreferrer">the documentation</a> for more).</p>
<p>This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:</p> <p>just do:</p> <pre><code>alert("message"); </code></pre>
19,877
<p>What are (if any)the implied assumptions or restrictions and the differences of designing like:</p> <p>A) this:</p> <pre><code>class SampleClass1 { IWorker workerA; IWorker workerB; void setWorkerA(IWorker w); void setWorkerB(IWorker w); WorkResult doWork(); } </code></pre> <p>B) versus this:</p> <pre><code>class SampleClass2 { WorkResult doWork(IWorker workerA, IWorker workerB); } </code></pre> <p>I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.</p> <p>Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.</p>
<p>In option (A) you are creating what is known as a Function Object or Functor, this is a design pattern that is <a href="http://en.wikipedia.org/wiki/Function_object" rel="noreferrer">well documented</a>. </p> <p>The two main advantages are:</p> <ul> <li>The workers can be set by in one place and then the object used elsewhere</li> <li>The object can retain state between calls</li> </ul> <p>Also if you are using a dependency injection framework (Spring, Guice etc...) the functor can be automatically initialized and injected wherever required.</p> <p>Function objects are extensively used in libraries e.g. the C++ Standard Template Library</p>
<p>Another Option:</p> <p>IWorker class:</p> <p>static WorkResult doWork(Iworker a, Iworker b);</p>
16,751
<p>I am looking for a taxonomy of embedded processors. Which processors belong to which families? Who decends from whom?</p> <p>Does anyone here know of a simple article that describes it?</p>
<p>The <a href="http://en.wikipedia.org/wiki/List_of_common_microcontrollers" rel="nofollow noreferrer">Common Microcontrollers</a> page on Wikipedia may be a place to start, or <a href="http://en.wikipedia.org/wiki/Microcontroller#Types_of_microcontrollers" rel="nofollow noreferrer">this shorter list</a> in the Microcontrollers article.</p>
<p><a href="http://www.instructables.com/id/ESICJ1VA2EEWIJKVP2/" rel="nofollow noreferrer">Instructables</a> has a nice overview.</p>
48,674
<p>What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?</p>
<p>I would avoid using <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--" rel="noreferrer"><code>System.currentTimeMillis()</code></a> for measuring elapsed time. <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--" rel="noreferrer"><code>currentTimeMillis()</code></a> returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements. </p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--" rel="noreferrer"><code>System.nanoTime()</code></a>, on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.</p>
<p>Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:</p> <pre><code>public class StopWatch { // Constructor public StopWatch() { } // Public API public void start() { if (!_isRunning) { _startTime = System.nanoTime(); _isRunning = true; } } public void stop() { if (_isRunning) { _elapsedTime += System.nanoTime() - _startTime; _isRunning = false; } } public void reset() { _elapsedTime = 0; if (_isRunning) { _startTime = System.nanoTime(); } } public boolean isRunning() { return _isRunning; } public long getElapsedTimeNanos() { if (_isRunning) { return System.nanoTime() - _startTime; } return _elapsedTime; } public long getElapsedTimeMillis() { return getElapsedTimeNanos() / 1000000L; } // Private Members private boolean _isRunning = false; private long _startTime = 0; private long _elapsedTime = 0; } </code></pre>
29,558
<p>My company has a subsidiary with a slow Internet connection. Our developers there suffer to interact with our central <a href="http://en.wikipedia.org/wiki/Subversion_%28software%29" rel="noreferrer">Subversion</a> server. Is it possible to configure a slave/mirror for them? They would interact locally with the server and all the commits would be automatically synchronized to the master server. </p> <p>This should work as transparently as possible for the developers. Usability is a must.</p> <p>Please, no suggestions to change our version control system.</p>
<p>It is possible but not necessarily simple: the problem you are trying to solve is dangerously close to setting up a distributed development environment which is not exactly what SVN is designed for.</p> <p><strong>The SVN-mirror way</strong></p> <p>You can use <code>svn mirror</code> as explained in the SVN book documentation to create a <em>read-only</em> mirror of your master repository. Your developers each interact with the mirror closest to them. However users of the slave repository will have to use </p> <p>svn switch --relocate master_url</p> <p>before they can commit and they will have to remember to relocate back on the slave once they are done. This could be automated using a wrapper script around the repository modifying commands on SVN if you use the command line client. Keep in mind that the relocate operation while fast adds a bit of overhead. (And be careful to duplicate the repository uuid - see <a href="http://svnbook.red-bean.com/en/1.5/svn.reposadmin.maint.html#svn.reposadmin.maint.replication" rel="noreferrer">the SVN documentation</a>.)</p> <p>[Edit - Checking the <a href="http://en.wikipedia.org/wiki/TortoiseSVN" rel="noreferrer">TortoiseSVN</a> documentation it seems that you can have TortoiseSVN <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html#tsvn-dug-settings-hooks" rel="noreferrer">execute hook scripts client side</a>. You may be able to create a pre/post commit script at this point. Either that or try to see if you can use the <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-automation.html" rel="noreferrer">TortoiseSVN automation interface</a> to do it].</p> <p><strong>The SVK way</strong></p> <p><a href="http://svk.bestpractical.com/view/HomePage" rel="noreferrer">svk</a> is a set of Perl scripts which emulate a distributed mirroring service over SVN. You can set it up so that the local branch (the mirror) is shared by multiple developers. Then basic usage for the developers will be completely transparent. You will have to use the svk client for cherry picking, merging and starmerging. It is doable if you can get your head around the distributed concepts. </p> <p><strong>The git-svn way</strong></p> <p>While I never used that myself, you could also have distant developers use git locally and use the <a href="http://git-scm.com/docs/git-svn" rel="noreferrer">git-svn</a> gateway for synchronization. </p> <p><strong>Final words</strong></p> <p>It all depends on your development environment and the level of integration you require. Depending on your IDE (and if you can change <a href="http://en.wikipedia.org/wiki/Source_Code_Management" rel="noreferrer">SCM</a>) you might want to have a look at other fully distributed SCMs (think <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>/<a href="http://en.wikipedia.org/wiki/Bazaar_%28software%29" rel="noreferrer">Bazaar</a>/<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a>/...) which support distributed development out of the box.</p>
<p>VisualSVN Server's <a href="http://www.visualsvn.com/server/features/multisite-replication/" rel="nofollow noreferrer">Multisite Repository Replication</a> was designed for this case.</p> <p>You can keep the master repository in your main office and setup multiple writeable slave repositories at the remote locations.</p> <blockquote> <p>This should work as transparently as possible for the developers. Usability is a must.</p> </blockquote> <ul> <li><p>The replication between the slaves and the master is transparent and automatic,</p></li> <li><p>Each master and slave repository is a writable Subversion repository from the user's standpoint,</p></li> <li><p>Works out-of-the-box and can be configured in a couple of clicks via VisualSVN Server Manager MMC console.</p></li> </ul> <p><img src="https://i.stack.imgur.com/EG7fF.png" alt="VisualSVNServerManagerConsoleMultisite"></p>
17,289
<p>I'm working on a cross platform application in Java which currently works nicely on Windows, Linux and MacOS X. I'm trying to work out a nice way to do detection (and handling) of 'crashes'. Is there an easy, cross-platform way to detect 'crashes' in Java and to do something in response?</p> <p>I guess by 'crashes' I mean uncaught exceptions. However the code does use some JNI so it'd be nice to be able to catch crashes from bad JNI code, but I have a feeling that's JVM specific.</p>
<p>For simple catch-all handling, you can use the following static method in <a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html" rel="nofollow noreferrer">Thread</a>. From the Javadoc:</p> <blockquote> <p>static void <a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)" rel="nofollow noreferrer"><strong>setDefaultUncaughtExceptionHandler</strong></a>(<a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html" rel="nofollow noreferrer">Thread.UncaughtExceptionHandler</a> eh) <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.</p> </blockquote> <p>This is a very broad way to deal with errors or unchecked exceptions that may not be caught anywhere else.</p> <p><strong>Side-note:</strong> It's better if the code can catch, log and/or recover from exceptions closer to the source of the problem. I would reserve this kind of generalized crash handling for totally unrecoverable situations (i.e. subclasses of <a href="http://java.sun.com/javase/6/docs/api/java/lang/Error.html" rel="nofollow noreferrer">java.lang.Error</a>). Try to avoid the possibility of a <a href="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html" rel="nofollow noreferrer">RuntimeException</a> ever going completely uncaught, since it might be possible--and preferable--for the software to survive that.</p>
<p>Not sure if this is what you needing, but you can also detect if an exception has occurred from within your native code. See <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp5234" rel="nofollow noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp5234</a> for more info.</p>
8,699
<p>I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table?</p>
<blockquote> <p>SELECT LEN(columnName) AS MyLength FROM myTable</p> </blockquote>
<p>If you want to find out the max there should be a way for you to get the schema of the table. Normally you can do something like <a href="http://dev.mysql.com/doc/refman/5.0/en/show-columns.html" rel="nofollow noreferrer">SHOW COLUMNS</a> in SQL or a <a href="http://dev.mysql.com/doc/refman/5.0/en/describe.html" rel="nofollow noreferrer">DESCRIBE</a> style command. In a mysql shell that can be shortened to:</p> <pre><code>desc tablename; </code></pre> <p>Then if you want to determine the length of a string there is normally a function like <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_length" rel="nofollow noreferrer">LENGTH</a> <em>(for bytes)</em> or <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length" rel="nofollow noreferrer">CHAR_LENGTH</a> <em>(for characters)</em>.</p> <pre><code>SELECT *, LENGTH(fieldname) AS len FROM tablename </code></pre>
5,719
<p>I want to pass the params collection from the controller to the model to parse filtering and sorting conditions. Does having a method in the model that takes the params from the controller break MVC?</p>
<p>It depends. You are passing a hash of data to the model and saying "make sense of this".</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_params(params) .... end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_params(params) end end </code></pre> <p>This is OK. But you may find yourself wanting to do this from many different actions. You are unlikely to be able to make the params exactly the same in each case, so you will need multiple methods on your model, one for each action:</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_update_params(params) # do stuff end def update_from_settings_params(params) # do different stuff end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_update_params(params) end def change_settings ... @model.update_from_settings_params(params) end end </code></pre> <p>This is not OK and you are making the model do controller work. A reasonable halfway house is to create a method on your model that accepts a canonical data hash, and then translate between the params and the canonical hash in the controller:</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_data(hash) validate_data!(hash) # do stuff end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_data(translate_update_params) end def change_settings ... @model.update_from_data(translate_change_settings_params) end end </code></pre> <p>Although you should make sure to carefully document the format of the data hash that the model accepts. We actually go so far as to use a YAML validation library (<a href="http://rjbs.manxome.org/rx/" rel="nofollow noreferrer">Rx</a>) to ensure that the model only accepts valid data.</p> <p>Sorry about the long answer, but I haven't got the time to write a shorter one ;).</p>
<p>I don't believe it does, but then again I am not a rails veteran by any means. Typically, the params hash is used in the controller and that action may or may not read and write model information, so I guess if the params were to go through a method belonging to the model, it would be the same thing.</p> <p>Either way I think you will still need to send the params through a controller, so why not do your processing there, then send the processed data to the model through a method of the model?</p>
44,778
<p>Is it possible to get a breakdown of CPU utilization <strong>by database</strong>?</p> <p>I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like <code>taskmgr</code>) or each SPID (like <code>spwho2k5</code>), I want to view the total CPU utilization of each database. Assume a single SQL instance.</p> <p>I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the <code>sqlservr.exe</code> CPU load.</p>
<p>Sort of. Check this query out:</p> <pre><code>SELECT total_worker_time/execution_count AS AvgCPU , total_worker_time AS TotalCPU , total_elapsed_time/execution_count AS AvgDuration , total_elapsed_time AS TotalDuration , (total_logical_reads+total_physical_reads)/execution_count AS AvgReads , (total_logical_reads+total_physical_reads) AS TotalReads , execution_count , SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 , ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt , query_plan FROM sys.dm_exec_query_stats AS qs cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY 1 DESC </code></pre> <p>This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots.</p> <p>When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this:</p> <pre><code>USE msdb DECLARE @StringToExecute VARCHAR(1000) SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog' EXEC @StringToExecute </code></pre> <p>The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption?</p> <p>It gets worse when you:</p> <ul> <li>Join between multiple databases</li> <li>Run a transaction in multiple databases, and the locking effort spans multiple databases</li> <li>Run SQL Agent jobs in MSDB that "work" in MSDB, but back up individual databases</li> </ul> <p>It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level.</p> <p>In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though.</p> <p>For more of those, check out the <a href="http://www.toadworld.com/platforms/sql-server/w/wiki/10040.transact-sql-code-library.aspx" rel="noreferrer">T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia)</a>.</p> <p><em>Updated on 1/29 to include total numbers instead of just averages.</em></p>
<p>Take a look at <a href="http://www.sqlsentry.com/" rel="nofollow noreferrer">SQL Sentry</a>. It does all you need and more.</p> <p>Regards, Lieven</p>
4,862
<p>I'm working on a site similar to digg in the respect that users can submit "stories". </p> <p>I keep track of how many "votes" and "similar adds" each item got. Similar adds are defined as two users adding the same "link". </p> <p>Here is <em>part</em> of the algorithm (essentially the most important):</p> <pre><code>y = day number sy = number of adds on day y ∑ y[1:10] sy / y </code></pre> <p>So basically calculate the number of "similar adds" on a specified day and divide by the number of seconds since the content was posted. Do this for the past 10 days (as an example). </p> <p>However, I'm not sure how to implement this so that it performs well. Every method I can think of will be really slow. </p> <p>The only way I can think of implementing this is by calculating the number of adds for the past 10 days for each item submitted will take forever. (so a sql command with a group by date executed 10 times for the past 10 days - obviously this method sucks).</p> <p>Even if I keep a table that I update once a day (and run the above sql in the background), that will still be ridiculously slow once the database gets large. Plus the rating will be "outdated" since it's not live (e.g. breaking news "items" will never reach the top). </p> <p>Does anyone have any experience of how to go about doing this?</p>
<p>Try this one: everyone has one vote. Your vote sticks to the last thing you voted for. The time thing would come from user behaviour.</p>
<p>There wouldn't be a need to execute SQL 10 times to get the result, you could get it in one execution something like:</p> <pre><code>select sum(dayval) from ( select count(*) / (current_date-day+1) dayval from votes where story_id = 123 and day &gt;= current_date - 9 group by (current_date-day+1) ) </code></pre> <p>(Actual code varies according to DBMS used). </p> <p>I'm not claiming this would perform well though!</p> <p>Perhaps a compromise: calculate and store the "start of day" value in a daily batch process, but then add 1 to the stored value for each vote received during the day?</p>
48,090
<p>Distributing ASP.NET user controls across different projects can be really useful when you want to create a library of controls that can be used by different projects.</p> <p>Unfortunately, to my knowledge, ASP.NET (2.0 at least) doesn't support this very cleanly.</p> <p>The only technique I know of is to add the control to another project, then copy the ascx (and only the ascx, unless you want to extend the control of course) file into the project that references the control, and remove the CodeBehind reference from it.</p> <p>It works, but it feels hackish. </p> <p>Does anyone know of a better way to split controls across projects? (perhaps 3.5 helps somehow?)</p>
<p>You could check out this article by Scott Guthrie:</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx" rel="nofollow noreferrer">Building Re-Usable ASP.NET User Control and Page Libraries with VS 2005</a></p>
<p>Check this out: <a href="http://support.microsoft.com/kb/324785" rel="nofollow noreferrer">How to share ASP.NET pages and user controls between applications by using Visual C# .NET</a></p> <p>You'll find other resources like this at Google.</p>
41,908
<p>I run into this occasionally and always forget how to do it.</p> <p>One of those things that pop up ever so often.</p> <p>Also, what's the formula to convert angles expressed in radians to degrees and back again?</p>
<pre><code>radians = degrees * (pi/180) degrees = radians * (180/pi) </code></pre> <p>As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion <a href="https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi">here</a></p>
<pre><code>radians = (degrees/360) * 2 * pi </code></pre>
16,453
<p>I am using <a href="http://www.simpletest.org/" rel="nofollow noreferrer">Simpletest</a> as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.</p> <p>I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.</p> <p>Are there any good extended HTML reporters or GUI's out there for Simpletest?</p> <p>Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried <a href="http://cool.sourceforge.net/" rel="nofollow noreferrer">Cool PHPUnit Test Runner</a>, but was not convinced.</p>
<p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p> <pre><code>python script_a.py | python script_b.py </code></pre> <p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow noreferrer">standard streams</a> on Wikipedia.</p> <p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p> <pre><code>import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() </code></pre> <p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow noreferrer">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow noreferrer">file objects</a>.</p> <p>For use with pipes, reading from standard input as <a href="https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939">lassevk</a> suggested you'd do something like this:</p> <pre><code>import sys x = sys.stderr.readline() y = sys.stdin.readline() </code></pre> <p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow noreferrer">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow noreferrer">pipes</a> module.</p> <p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow noreferrer">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
<p>In which context are you asking?</p> <p>Are you trying to capture the output from a program you start on the command line?</p> <p>if so, then this is how to execute it:</p> <pre><code>somescript.py | your-capture-program-here </code></pre> <p>and to read the output, just read from standard input.</p> <p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>
4,458
<p>Is it possible to listen for a certain hotkey (e.g:<kbd>Ctrl</kbd><kbd>-</kbd><kbd>I</kbd>) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?</p> <p>EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say <kbd>Ctrl</kbd><kbd>-</kbd><kbd>+</kbd>, <kbd>Ctrl</kbd> and <kbd>+</kbd>) you could execute that action when you press the keys. If I would map <kbd>Ctrl</kbd><kbd>-</kbd><kbd>+</kbd> to the volume increase action, each time I press <kbd>ctrl</kbd><kbd>-</kbd><kbd>+</kbd> the volume should increase by a certain amount.</p> <p>Thanks</p>
<p>How global do your hotkeys need to be? Is it enough for them to be global for a X session? In that case you should be able to open an Xlib connection and listen for the events you need.</p> <p>Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled. Clearly this is not what we want. We need to process the event before any other window can get to it. We need to call <a href="http://tronche.com/gui/x/xlib/input/XGrabKey.html" rel="nofollow noreferrer">XGrabKey</a> on the root window with the keycode and modifiers of our hotkey to accomplish this.</p> <p>I found a good example <a href="http://ubuntuforums.org/showpost.php?p=5419687&amp;postcount=1" rel="nofollow noreferrer">here</a>.</p>
<p>In UNIX, your access to a commandline shell is via a <strong>terminal</strong>. This harks back to the days when folks accessed their big shared computers literally via terminals connected directly to the machines (e.g. by a serial cable).</p> <p>In fact, the 'xterm' program or whatever derivative you use on your UNIX box is properly referred to as a <strong>terminal emulator</strong> - it behaves (from both your point of view and that of the operating system) much like one of those old-fashioned terminal machines.</p> <p>This makes it slightly complicated to handle input in interesting ways, since there are lots of different kinds of terminals, and your UNIX system has to know about the capabilities of each kind. These capabilities were traditionally stored in a <strong>termcap</strong> file, and I think more modern systems use <strong>terminfo</strong> instead. Try</p> <pre><code>man 5 terminfo </code></pre> <p>on a Linux system for more information.</p> <p>Now, the good news is that you don't need to do too much messing about with terminal capabilities, etc. to have a commandline application that does interesting things with input or windowing features. There's a library, <strong>curses</strong>, that will help. Lookup </p> <pre><code>man 3 ncurses </code></pre> <p>on your Linux system for more information. You will probably be able to find a decent tutorial on using curses online.</p>
10,042
<p>Let's collect some tips for evaluating the appropriate use of global.asax.</p>
<p>It's simple to use if your session and application initialization code is very small and application-specific. Using an HttpModule is more useful if you want to reuse code, such as setting up rules for URL rewriting, redirects or auth. An HttpModule can cover everything a Global.asax file can. They can also be removed and added easily using your .config.</p>
<p>Global.asax can inherit from your own class that inherits httpapplication. Gives you more options as well as putting the bulk of the code you might have in global into a class library.</p> <p>EDIT: Having your HttpApplication class (global.asax parent) in a seperate class library can promote reusability too. Although i agree that using HttpModules is better suited for many tasks, but this still has many uses, for one, cleaner code.</p>
16,426
<p>I have a need to allow for a user to download an event that has multiple meeting dates. To do this I have created a memorystream to be downloaded which produces a .ics file. For example:</p> <pre> BEGIN:VCALENDAR PRODID:-//Company//Product//EN VERSION:2.0 METHOD:PUBLISH BEGIN:VEVENT SUMMARY:Subject of Event LOCATION:Location of Event UID:1227559810-8527e2c-20847@domain.com DESCRIPTION:Some description DTEND:20081101T200000Z DTSTART:20081101T200000Z PRIORITY:3 END:VEVENT BEGIN:VEVENT ... END:VEVENT END:VCALENDAR </pre> <p>If I only include one VEVENT in this file it will save it to my existing Outlook calendar. However, when I have multiple VEVENTs it wants to open it as a new calendar and files it under "Other Calendars".</p> <p>Is there a way (without using File - Import from within Outlook) to specify that the calendar should be imported automatically into the existing calendar when opened?</p> <p>UPDATE: To clarify, each VEVENT is related to a single "Appointment". However there may or may not be a recurring pattern.</p> <p>-Mike</p>
<p>I don't think this will work. Outlook is limited in importing those "open" specs. I had a similar problem trying to import a vCard file with multiple contacts. I ended up splitting the file and writing a script in Outlook to import all the files in a directory.</p>
<p>This works: Take the ICS file, drag &amp; drop on the calendar button in Outlook (bottom left corner on mine). That adds multiple entries to the default calendar, without any prompting when an ICS file contains multiple vevents. Updates &amp; deletes of multiples are my next challenge.</p> <p>Double clicking the same file has very different results: Creates a new calendar, and the busy indicator is ignored. The drag &amp; drop that I described keeps the busy indicator intact like it is in the ICS file</p> <p>X-MS-OLK-FORCEINSPECTOROPEN:TRUE opened the 1st entry so it could be approved &amp; added. Subsequent vevents are ignored.</p> <p>X-MS-OLK-FORCEINSPECTOROPEN:FALSE or removing the line entirely had the same results on Outlook 365 for me.</p> <p>Also, when double clicking an ICS file with multiple vevents, this is what I saw: Outlook is not entirely compatible because a new calendar gets created named "untitled". The mail app that comes with Windows 10 is compatible &amp; all entries are added to the calendar properly (might be because the Win 10 mail app only has 1 calendar? I don't know- I'm writing for Outlook only)</p>
43,346
<p>The documentation available on the <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html" rel="noreferrer">boost website</a> is... limited.</p> <p>From what I've been able to read, the general consensus is that it is simply difficult to find good documentation on the boost::asio library.</p> <p>Is this really the case? If so, why?</p> <p>Notes:</p> <ul> <li>I have already found the (non-boost) <a href="http://tenermerx.com/Asio/WebHome" rel="noreferrer">Asio website</a> - and the documentation looks to be identical to that on the boost website.</li> <li>I know that Boost::asio is new! I'm looking for solutions not excuses.</li> </ul> <p>Edit:</p> <ul> <li>There is a <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2054.pdf" rel="noreferrer">proposal to add a networking library to standard library for TR2</a> written by the author of Boost:asio (Christopher Kohlhoff). While it isn't documentation for boost:asio, it does use it as a base for the TR2 proposal. Since the author put more effort into this document, I have found it to be somewhat helpful, if not as a reference, then at least as an overview. </li> </ul>
<p>First, I've been using Boost.Asio for quite a while already -- and I share your concern. To address your question:</p> <ul> <li>There really is very scarce documentation about Boost.Asio aside from the introduction and tutorial. I am not the author, but this is mostly because there are just too many things to document for something as low-level as an Asynchronous IO Library.</li> <li>The examples give more away than the tutorials do. If you don't mind spending a little time looking at the different examples, I would think they should suffice to get you started. If you want to run away with it, then the reference documentation should help you a lot.</li> <li>Ask around in the Boost Users and Boost Developers mailing list if you're really stuck or looking for specific guidance. I'm pretty sure a lot of people will be willing to address your concerns on the mailing lists.</li> </ul> <p>There are efforts (not part of Boost.Asio) to expose a lot of the functionality and possible alternative use cases. This at best is scattered around the web in blogs and other forms of non-packaged documentation.</p> <p>One thing that is unclear and which will really need close coordination with the author and developers of the Boost.Asio library would be as far as extending and customizing it for a specific platform or adding specific new functionality. This should be improved though but the good thing is it's looking like Asio will be a reference implementation for a standard library technical report (for an asynchronous IO library in the STL) in the future.</p>
<p>I stumbled on the following pdf: <a href="http://boost.cowic.de/rc/pdf/asio_doc.pdf" rel="nofollow noreferrer">http://boost.cowic.de/rc/pdf/asio_doc.pdf</a></p>
30,315
<p>The only method provided by the DNN framework to get a module by ID also required a tab ID. What can I do if I don't <em>have</em> a tab ID?</p>
<p>The GetModule method off of the DotNetNuke.Entities.Modules.ModuleController class will accept a "null" value for tab ID if you don't have a tab ID. That is, try the following:</p> <pre><code>new ModuleController().GetModule(moduleId, DotNetNuke.Common.Utilities.Null.NullInteger) </code></pre> <p>See also <a href="http://weblogs.asp.net/briandukes/archive/2008/10/29/get-module-by-moduleid.aspx" rel="noreferrer">my blog post on the subject</a>.</p>
<p>Brian, I just took a look at the code for GetModule(), and there isn't any specific VB code in the framework that checks for the tabid being null. What's interesting though is that the stored procedure that is part of the SqlDataProvider selects rows from the Modules view that have a matching moduleid, no matter what tabid is... </p> <pre><code>ALTER PROCEDURE [dbo].[dnn_GetModule] @ModuleId int, @TabId int AS SELECT * FROM dbo.dnn_vw_Modules WHERE ModuleId = @ModuleId AND (TabId = @TabId or @TabId is null) </code></pre> <p>If I understand this correctly, this would return all the rows where moduleid is the one you specified, no matter if @tabid is null or not. That makes the @TabId rather pointless, don't you think?</p>
30,822
<p>I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it.</p> <p>So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.</p>
<p>I wrote a plugin sometime back for <strong><a href="http://meetselva.github.io/attrchange/">attrchange</a></strong> listener which basically adds a listener function on attribute change. Even though I say it as a plugin, actually it is a simple function written as a jQuery plugin.. so if you want.. strip off the plugin specfic code and use the core functions.</p> <p><strong>Note: This code doesn't use polling</strong> </p> <p>check out this simple demo <a href="http://jsfiddle.net/aD49d/">http://jsfiddle.net/aD49d/</a></p> <pre><code>$(function () { var prevHeight = $('#test').height(); $('#test').attrchange({ callback: function (e) { var curHeight = $(this).height(); if (prevHeight !== curHeight) { $('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight); prevHeight = curHeight; } } }).resizable(); }); </code></pre> <p><strong>Plugin page:</strong> <a href="http://meetselva.github.io/attrchange/">http://meetselva.github.io/attrchange/</a></p> <p><strong>Minified version:</strong> (1.68kb)</p> <pre><code>(function(e){function t(){var e=document.createElement("p");var t=false;if(e.addEventListener)e.addEventListener("DOMAttrModified",function(){t=true},false);else if(e.attachEvent)e.attachEvent("onDOMAttrModified",function(){t=true});else return false;e.setAttribute("id","target");return t}function n(t,n){if(t){var r=this.data("attr-old-value");if(n.attributeName.indexOf("style")&gt;=0){if(!r["style"])r["style"]={};var i=n.attributeName.split(".");n.attributeName=i[0];n.oldValue=r["style"][i[1]];n.newValue=i[1]+":"+this.prop("style")[e.camelCase(i[1])];r["style"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data("attr-old-value",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i==="function"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t&lt;o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data("attr-old-value",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on("DOMAttrModified",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if("onpropertychange"in document.body){return this.on("propertychange",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery) </code></pre>
<p>You can use this, but it only supports Firefox and Chrome.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(element).bind('DOMSubtreeModified', function () { var $this = this; var updateHeight = function () { var Height = $($this).height(); console.log(Height); }; setTimeout(updateHeight, 2000); });</code></pre> </div> </div> </p>
20,821
<p>I am building a multithreaded system that works like this:</p> <p>While there are entities:</p> <ol> <li><p>Gets an entity from nHibernate (using the current session)</p></li> <li><p>Starts a new thread that will work with this entity*</p></li> </ol> <p>When I start this new thread, it is required to have a new Session, because nHibernate is not thread-safe. I create it, but the entity retrieved before doesn't work for this session.</p> <p>Today I'm resolving this situation retrieving from nHibernate a new Entity passing the id. But this is expensive, and I'm trying to save some time to achieve my SLA.</p> <p>Is there any way for linking this object to this new session without needing to do a new database call? The other session will not be closed, they're all opened until the end of the application.</p>
<p>If you're working with detached objects, you will have to reattach them to the session. You can do that if you have the correct Hibernate ids of the objects you're working with, calling a get, and then merging your copy with the one Hibernate just put into session. Make sure you use merge, though, because saveOrUpdate() will not delete any children that are missing from the detached object, just add the new children and save changes to existing children.</p>
<p>I detached it from the first thread, after attaching to the other thread.</p>
34,335
<p>In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser,</p> <p>Does anyone know the right incantation to figure that out?</p>
<p>The problem with using script to check whether javascript is enabled is that you only find that out after the script hasn't run.</p> <p>Some solutions try the opposite - they use javascript to set a value and then supply Javascript enabled controls if that value is later detected. However, this fails with javascript-sometimes-enabled tools like the Firefox NoScript plugin.</p> <p>A more robust solution is to always send the plain-HTML compatible control, and then have javascript run on page load to add the correct event handlers/extra DOM elements/etc.</p> <p>However I don't know how this fits in with the ASP.NET approach takes to controls.</p>
<p>This is a way to check when a form is being submitted. </p> <p><a href="https://web.archive.org/web/20210428071600/http://www.4guysfromrolla.com/webtech/082400-1.shtml" rel="nofollow noreferrer">https://web.archive.org/web/20210428071600/http://www.4guysfromrolla.com/webtech/082400-1.shtml</a></p> <p>I dont think there is any Request property that will tell you when the page is first requested. There is a property that will tell you if the browser supports JS, but not if its enabled. <a href="http://msdn.microsoft.com/en-us/library/aa332781(VS.71,printer).aspx" rel="nofollow noreferrer">See Here</a></p>
30,594
<p>I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have <code>/* .. */</code> comments, and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?</p>
<p>This is <a href="http://www.doxygen.nl/manual/docblocks.html#pythonblocks" rel="noreferrer">documented on the doxygen website</a>, but to summarize here:</p> <p>You can use doxygen to document your Python code. You can either use the Python documentation string syntax:</p> <pre><code>"""@package docstring Documentation for this module. More details. """ def func(): """Documentation for a function. More details. """ pass </code></pre> <p>In which case the comments will be extracted by doxygen, but you won't be able to use any of the <a href="http://www.doxygen.nl/manual/commands.html#cmd_intro" rel="noreferrer">special doxygen commands</a>.</p> <p><strong>Or</strong> you can (similar to C-style languages under doxygen) double up the comment marker (<code>#</code>) on the first line before the member:</p> <pre><code>## @package pyexample # Documentation for this module. # # More details. ## Documentation for a function. # # More details. def func(): pass </code></pre> <p>In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting <code>OPTMIZE_OUTPUT_JAVA</code> to <code>YES</code>.</p> <p>Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?</p>
<p>An other very good documentation tool is <a href="http://www.sphinx-doc.org/en/master/index.html" rel="nofollow noreferrer">sphinx</a>. It will be used for the upcoming python 2.6 <a href="http://docs.python.org/dev/" rel="nofollow noreferrer">documentation</a> and is used by <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow noreferrer">django</a> and a lot of other python projects.</p> <p>From the sphinx website:</p> <ul> <li><strong>Output formats</strong>: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions</li> <li><strong>Extensive cross-references</strong>: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information</li> <li><strong>Hierarchical structure</strong>: easy definition of a document tree, with automatic links to siblings, parents and children</li> <li><strong>Automatic indices</strong>: general index as well as a module index</li> <li><strong>Code handling</strong>: automatic highlighting using the Pygments highlighter</li> <li><strong>Extensions</strong>: automatic testing of code snippets, inclusion of docstrings from Python modules, and more</li> </ul>
8,303
<p>How can I run a stored procedure from a CL program? RUNSQLSTM requires a source member, but I just want to build a command so users can pass in variables easily, so this won't work.</p>
<p>You can call the system program <code>QZDFMDB2</code> and pass it one parameter with the SQL string to execute. In this case the SQL string is the call to your stored procedure:</p> <pre><code> CALL PGM(QZDFMDB2) PARM('CALL PROCEDURE (''XYZ'', ''ABC'')') </code></pre> <p>To substitute in your values use a variable for the PARM:</p> <pre><code> DCL VAR(&amp;CALL) TYPE(*CHAR) LEN(200) CHGVAR VAR(&amp;CALL) VALUE('CALL PROCEDURE (''' *CAT &amp;PARM1 *TCAT ''', ''' *CAT &amp;PARM2 *TCAT ''')') CALL PGM(QZDFMDB2) PARM(&amp;CALL) </code></pre>
<p><code>QCMDEXC</code> might be the command you are looking for.</p>
30,706
<p>We use ASP.NET, C#</p> <p>When making an update to one of our websites, we roll out the entire site rather than updating just the pages or sections that have changed. This scares me.</p> <p>Is this a good idea? Should I roll out only the changes? </p> <p>Should I break my site into smaller projects? </p> <p>What is best practice?</p>
<p>You should always roll out the entire site. Because the actually executable code is contained mostly in the DLLs, you can't actually only roll out the pages that changed, like you could with the old ASP. If there are parts of your website that are actually separate, you can break them apart into separate projects, and deploy each entire section separately. </p> <p>Also, if putting up the whole site scares you, you probably need better testing or quality assurance standards. There should always be a copy of your entire site that can go live at any time, in case the server dies, and you have to replace it, or something else goes wrong.</p>
<p>Depends on how you test prior to deployment.</p> <p>If you (automatically) test everything prior to release, isn't the only downside the overhead of the file transfer.</p>
30,222
<p>I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys?</p> <p>For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a width setting for each column for each list view I would like a simple method to load / save the widths automatically.</p> <p>Below is an example of the <strong>save</strong> method I have tried:</p> <pre><code>internal sealed partial class Settings { public void SetListViewColumnWidths(ListView listView) { String baseKey = listView.Name; foreach (ColumnHeader h in listView.Columns) { String key = String.Format("{0}-{1}", baseKey, h.Index); this[key] = h.Width; } } } </code></pre> <p>When running that code I get the error <strong>"The settings property 'TestsListView-0' was not found."</strong> Is there something I am missing?</p>
<p>Store your column width settings in an Xml Serializable object. Ie, something that implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="nofollow noreferrer">IXmlSerializable</a> then create a single setting entry of that type in Settings.settings.</p> <p>A good option would probably be an Xml Serializable Dictionary. A quick <a href="http://www.google.com.au/search?&amp;q=xml+serializable+dictionary" rel="nofollow noreferrer">google search</a> found quite a few different blog posts that describe how to implement that.</p> <p>As mentioned in other answers you'll need to ensure that this object is a User setting. You may also need to initialize the setting instance. Ie, create a XmlSerializableDictionary() instance and assign it to the setting if the setting is null. The settings subsystem doesn't create default instances of complex setting objects.</p> <p>Also, if you want these settings to persist between assembly versions (ie, be upgradable) you will need to upgrade the settings on application startup. This is described in detail on <a href="http://cs.rthand.com/blogs/blog_with_righthand/archive/2005/12/09/246.aspx" rel="nofollow noreferrer">Miha Markič's</a> blog and <a href="http://blogs.msdn.com/rprabhu/articles/433979.aspx" rel="nofollow noreferrer">Raghavendra Prabhu's</a> blog.</p>
<p>I think the error</p> <blockquote> <p>The settings property 'key' was not found.</p> </blockquote> <p>occurs because the 'key' value does not exist in your settings file (fairly self-explanatory).</p> <p>As far as I am aware, you can't add settings values programmatically, you might need to investigate adding all of the settings you need to the file after all, although once they are there, I think you'll be able to use the sort of code you've given to save changes.</p> <p>To Save changes, you'll need to make sure they are 'User' settings, not 'Application'.</p> <p>The Settings file is quite simple XML, so you might be able to attack the problem by writing the XML directly to the file, but I've never done it, so can't be sure it would work, or necessarily recommend that approach.</p> <p><a href="http://msdn.microsoft.com/en-us/library/cftf714c.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cftf714c.aspx</a> is the MSDN link to start with.</p>
24,568
<p>I'm curious about people's experiences using AR's to_xml() to build non-entity fields (as in, not an attribute of the model you are serializing, but perhaps, utilizing the attributes in the process) from a controller. </p> <p>to_xml seems to supply a few options for doing this. </p> <p>One is by passing in references to methods on the object being acted on: during the serialization process, these methods are invoked and their results are added to the generated document. I'd like to avoid this path because some of the generated data, while depending on the object's attributes, could be outside of the scope of the model itself -- e.g., building a URL to a particular items "show" action. Plus, it requires too much forethought. I'd like to just be able to change the resultant document by tweaking the to_xml code from the controller. I don't want the hassle of having to declare a method in the object as well. </p> <p>The same goes for overriding to_xml in each object. </p> <p>The other two options seem to fit the bill a little better: one is by passing in procs in the serialization options that generate these fields, and the other is by passing in a block that will yielded to after serialization the objects attributes. These provide the kind of at-the-point-of-invocation customizing that I'm looking for, and in addition, their declarations bind the scope to the controller so that they have access to the same stuff that the controller does, but these methods seem critically limited: AFAICT they contain no reference to the object being serialized. They contain references to the builder object, which, sure I guess you could parse within the block/proc and find the attributes that have already been serialized and use them, but that's a harangue, or at least uneasy and suboptimal. </p> <p>Correct me if I'm wrong here, but what is the point of having procs/blocks available when serializing one or more objects if you have to access to the object itself.</p> <p>Anyway, please tell me how I'm wrong, because it seems like I must be overlooking something here. </p> <p>Oh and yeah, I know that I could write my own view. I'm trying to leverage respond_to and to_xml to achieve minimal extra files/lines. (Though, that is what I resorted to when I couldn't figure out how to do this with AR's serialization.)</p> <p>**EDIT 3.29.09 -- I just submitted a patch for this to Rails. If you're interested, show some support :) <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml" rel="nofollow noreferrer">https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml</a></p>
<p>Yes, an abstract class can have a constructor. Consider this:</p> <pre><code>abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } } </code></pre> <p>The superclass <code>Product</code> is abstract and has a constructor. The concrete class <code>TimesTwo</code> has a constructor that just hardcodes the value 2. The concrete class <code>TimesWhat</code> has a constructor that allows the caller to specify the value.</p> <p>Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.</p> <blockquote> <p>NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.</p> </blockquote>
<p>Yes..It is like any other class. It can have a constructor and it is called after creating object for the base class.</p>
32,593
<p>What's the best way to throw an exception in objective-c/cocoa?</p>
<p>I use <code>[NSException raise:format:]</code> as follows:</p> <pre><code>[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];</code></pre>
<p>There is no reason not to use exceptions normally in objective C even to signify business rule exceptions. Apple can say use NSError who cares. Obj C has been around a long time and at one time ALL C++ documentation said the same thing. The reason it doesnt matter how expensive throwing and catching an exception is, is the lifetime of an exception is exceedingly short and...its an EXCEPTION to the normal flow. I have never heard anyone say ever in my life, man that exception took a long time to be thrown and caught. </p> <p>Also, there are people that think that objective C itself is too expensive and code in C or C++ instead. So saying always use NSError is ill-informed and paranoid.</p> <p>But the question of this thread hasnt yet been answered whats the BEST way to throw an exception. The ways to return NSError are obvious.</p> <p>So is it: [NSException raise:... @throw [[NSException alloc] initWithName.... or @throw [[MyCustomException... ?</p> <p>I use the checked/unchecked rule here slightly differently than above.</p> <p>The real difference between the (using the java metaphor here) checked/unchecked is important --> whether you can recover from the exception. And by recover I mean not just NOT crash. </p> <p>So I use custom exception classes with @throw for recoverable exceptions, because its likely I will have some app method looking for certain types of failures in multiple @catch blocks. For example if my app is an ATM machine, I would have a @catch block for the "WithdrawalRequestExceedsBalanceException".</p> <p>I use NSException:raise for runtime exceptions since I have no way to recover from the exception, except to catch it at a higher level and log it. And theres no point in creating a custom class for that.</p> <p>Anyway thats what I do, but if there's a better, similarly expressive way I would like to know as well. In my own code, since I stopped coding C a hella long time ago I never return an NSError even if I am passed one by an API.</p>
41,996
<p>I wrote a program using AutoIT to fetch information from a number of websites using Internet Explorer. AutoIT is capable of hiding the window so that it is not visible, however when I navigate to a new website on that hidden window I still get the IE navigation sounds (button click sound, etc.).</p> <p>How can I disable the sounds from playing using AutoIT? (Muting the computer, or altering settings in the control panel would not be ideal).</p>
<pre><code>(data.RoleOwners.length === 0) </code></pre>
<p>An array (being an object too) can have non numeric properties which are not picked up by testing for zero length. You need to iterate through the properties just like testing for an empty object. If there are no properites then the array is empty.</p> <pre><code>function isEmptyObject(obj) { // This works for arrays too. for(var name in obj) { return false } return true } </code></pre>
43,421
<p>does anybody know how could I get the TWO most largest values from the third column on the following array?</p> <pre><code>$ar = array(array(1, 1, 7.50, 'Hello'), array(1, 2, 18.90, 'Hello'), array(3, 5, 11.50, 'Hello'), array(2, 4, 15.90, 'Hello')); </code></pre> <p>Output should be:</p> <pre><code>15.90 18.90 </code></pre> <p>Thanks in advance</p>
<p>If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using <a href="http://www.php.net/manual/en/function.usort.php" rel="nofollow noreferrer"><code>usort</code>()</a> and providing an appropriate callback. Then take the first two values:</p> <pre><code>function cmp($a, $b) { $a = $a[2]; $b = $b[2]; return $a == $b ? 0 : $a &lt; $b ? 1 : -1; } usort($ar, 'cmp'); </code></pre>
<p>One of the simplest ways to do this is to collect all the values into a single array, sort the array, then print out the first two values.</p> <p>There are more efficient ways that don't involve sorting the whole array, but the above should get you started.</p>
31,800
<p>In Flash when you set text in a TextField object with the htmlText property, changing the alpha value no longer works. Is there a way around that?</p>
<p>Some confusion here.</p> <ol> <li><p>Whether alpha works or not depends on whether the text field uses device fonts, not whether it uses HTML. (Device fonts are used any time you have a dynamic/input text and you don't embed the font.)</p></li> <li><p>If possible, simply publish for Flash player 10, which now supports alpha for device fonts. (Note that you have to set the <code>alpha</code> property of the textfield or its parent - choosing a transparent color for the text itself doesn't work.)</p></li> <li><p>Fallback option for v8-9 is to force bitmap caching by applying a filter. For example, you could use a drop shadow with the color set to be transparent. This causes Flash to render the text field into a bitmap before drawing it to the screen, so your alpha is applied to the bitmap and everything works. </p></li> <li><p>For player version 7 or lower, there's no way to get alpha for device fonts. You have to either embed the font or learn to live without alpha. :D</p></li> </ol>
<p>Dynamic text doesn't support the alpha property (among others). I assume setting it to HTML text imposes the same limits. One way I've found around this is to contain the text field in a movie clip and set the alpha on the movie clip instead.</p>
42,343
<p>I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?</p>
<p>I had to find the same answer. The best example I found is <a href="http://www.cssplay.co.uk/menu/tablescroll.html" rel="noreferrer">http://www.cssplay.co.uk/menu/tablescroll.html</a> - I found example #2 worked well for me. You will have to set the height of the inner table with Java Script, the rest is CSS.</p>
<p>If its ok to use JavaScript here is my solution Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!</p> <p>Tested in: Opera, Chrome, Safari, FF, IE5.5(<strong>Epic script fail</strong>), IE6, IE7, IE8, IE9</p> <pre><code>//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width $(document).ready(function () { $("table.Scrollify").each(function (index, element) { var header = $(element).children().children().first(); var headerHtml = header.html(); var width = $(element).outerWidth(); var height = parseInt($(element).css("height")) - header.outerHeight(); $(element).height("auto"); header.remove(); var html = "&lt;table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"&gt;&lt;tr&gt;" + headerHtml + "&lt;/tr&gt;&lt;/table&gt;&lt;div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\"&gt;" + $(element).parent().html() + "&lt;/div&gt;"; $(element).parent().html(html); }); }); //Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels //License: Apache License, version 2 function scrollbarWidth() { var scr = null; var inn = null; var wNoScroll = 0; var wScroll = 0; // Outer scrolling div scr = document.createElement('div'); scr.style.position = 'absolute'; scr.style.top = '-1000px'; scr.style.left = '-1000px'; scr.style.width = '100px'; scr.style.height = '50px'; // Start with no scrollbar scr.style.overflow = 'hidden'; // Inner content div inn = document.createElement('div'); inn.style.width = '100%'; inn.style.height = '200px'; // Put the inner div in the scrolling div scr.appendChild(inn); // Append the scrolling div to the doc document.body.appendChild(scr); // Width of the inner div sans scrollbar wNoScroll = inn.offsetWidth; // Add the scrollbar scr.style.overflow = 'auto'; // Width of the inner div width scrollbar wScroll = inn.offsetWidth; // Remove the scrolling div from the doc document.body.removeChild( document.body.lastChild); // Pixel width of the scroller return (wNoScroll - wScroll); } </code></pre> <p>Edit: Fixed height.</p>
15,853
<p>Are there any good JavaScript frameworks out there which primary audience is not web programming? Especially frameworks/libraries which improves the object orientation? The framework should be usable within an desktop application embedding a JavaScript engine (such as Spidermonkey or JavaScriptCore), so no external dependency are allowed.</p>
<p><a href="http://dojotoolkit.org/" rel="nofollow noreferrer">Dojo</a> can be used (and is used) in non-browser environments (e.g., Rhino, Jaxer, SpiderMonkey). It can be easily adapted for other environments too &mdash; all DOM-related functions are separated from functions dealing with global language features.</p> <p><a href="http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.declare" rel="nofollow noreferrer">dojo.declare()</a> (<a href="http://docs.dojocampus.org/dojo/declare" rel="nofollow noreferrer">more docs</a>) comes in the Dojo Base (as soon as you load dojo.js) and implements full-blown OOP with single- and multiple- inheritance, automatic constructor chaining, and super-calls. In fact it is the cornerstone of many Dojo facilities.</p> <p>Of course there are more low-level facilities like <a href="http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.mixin" rel="nofollow noreferrer">dojo.mixin()</a> to mix objects together and <a href="http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.extend" rel="nofollow noreferrer">dojo.extend()</a> to extend a prototype dynamically.</p> <p>More language-related features can be found in <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/lang/" rel="nofollow noreferrer">dojox.lang</a>. Following parts of it are thoroughly explained and documented: <a href="http://lazutkin.com/blog/2008/jan/12/functional-fun-javascript-dojo/" rel="nofollow noreferrer">functional</a>, <a href="http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/" rel="nofollow noreferrer">AOP</a>, <a href="http://lazutkin.com/blog/2008/jun/30/using-recursion-combinators-javascript/" rel="nofollow noreferrer">recursion combinators</a>.</p> <p>Dojo comes with other batteries included from string-related algorithms to the date processing. If you are interested in those <a href="http://docs.dojocampus.org/" rel="nofollow noreferrer">you can discover them yourself</a>, or contact <a href="http://dojotoolkit.org/community/" rel="nofollow noreferrer">the Dojo community</a>.</p>
<p><a href="http://cappuccino.org/learn/tutorials/objective-j-tutorial.php" rel="nofollow noreferrer">Objective-J</a>(avascript) is one. Is that the kind of thing you are looking for?</p>
41,343
<p>I'm trying to define a table to store student grades for a online report card. I can't decide how to do it, though.</p> <p>The grades are given by subject, in a trimestral period. Every trimester has a average grade, the total missed classes and a "recovering grade" (I don't know the right term in English, but it's an extra test you take to try to raise your grade if you're below the average), I also gotta store the year average and final "recovering grade". Basically, it's like this:</p> <pre><code> |1st Trimester |2nd Trimester |3rd Trimester Subj. |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Avg. |Mis. |Rec |Year Avg. |Final Rec. Math |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 Sci. |5.33 |1 |4 |8.0 |0 |7.0 |2 |6.5 |7.0 </code></pre> <p>I could store this information in a single DB row, with each row like this:</p> <pre><code>1tAverage | 1tMissedClasses | 1tRecoveringGrade | 2tAverage | 2tMissedClasses | 2tRecoveringGrade </code></pre> <p>And so on, but I figured this would be a pain to mantain, if the scholl ever decides to grade by bimester or some other period (like it used to be up until 3 years ago).<br /> I could also generalize the table fields, and use a tinyint for flagging for which trimester those grades are, or if they're the year finals. But this one would ask for a lot of subqueries to write the report card, also a pain to mantain.</p> <p>Which of the two is better, or is there some other way? Thanks</p>
<p>You could try structuring it like this with your tables. I didn't have all the information so I made some guesses at what you might need or do with it all.</p> <p>TimePeriods:</p> <ul> <li>ID(INT) </li> <li>PeriodTimeStart(DateTime)</li> <li>PeriodTimeEnd(DateTime)</li> <li>Name(VARCHAR(50)</li> </ul> <p>Students:</p> <ul> <li>ID(INT) </li> <li>FirstName(VARCHAR(60))</li> <li>LastName(VARCHAR(60))</li> <li>Birthday(DateTime) </li> <li>[any other relevant student field information added...like contact info, etc]</li> </ul> <p>Grading:</p> <ul> <li>ID(INT)</li> <li>StudentID(INT)</li> <li>GradeValue(float)</li> <li>TimePeriodID(INT)</li> <li>IsRecoveringGrade(boolean)</li> </ul> <p>MissedClasses:</p> <ul> <li>ID(INT)</li> <li>StudentID(INT)</li> <li>ClassID(INT)</li> <li>TimePeriodID(INT)</li> <li>DateMissed(DateTime)</li> </ul> <p>Classes:</p> <ul> <li>ID(INT)</li> <li>ClassName (VARCHAR(50))</li> <li>ClassDescription (TEXT)</li> </ul>
<p>I think the best solution is to store one row per period. So you'd have a table like:</p> <pre><code>grades ------ studentID periodNumber averageGrade missedClasses recoveringGrade </code></pre> <p>So if it's 2 semesters, you'd have periods 1 and 2. I'd suggest using period 0 to mean "overall for the year".</p>
31,718
<p>I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?</p> <p>I would like to be able to use a RichTextBox to allow better formatting of the input value. Can this be done without creating a custom editor class?</p>
<p>To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.</p> <p>What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...</p> <pre><code>[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public override string Text { get { return _string; } set { _string = value; } } </code></pre> <p>Another nice one they provide for you is the ability to edit an array of strings...</p> <pre><code>[Editor("System.Windows.Forms.Design.StringArrayEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] public string[] Lines { get { return _lines; } set { _lines = value; } } </code></pre>
<p>I think what you are looking for is Custom Type Descriptors. You could read up a bit and get started here: <a href="http://www.codeproject.com/KB/miscctrl/bending_property.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/bending_property.aspx</a></p> <p>I am not sure you can do any control you want, but that article got me started on propertygrids.</p>
9,810
<p>If you have Mathematica code in foo.m, Mathematica can be invoked with <code>-noprompt</code> and with <code>-initfile foo.m</code> (or <code>-run "&lt;&lt;foo.m"</code>) and the command line arguments are available in <code>$CommandLine</code> (with extra junk in there) but is there a way to just have some mathematica code like</p> <pre><code>#!/usr/bin/env MathKernel x = 2+2; Print[x]; Print["There were ", Length[ARGV], " args passed in on the command line."]; linesFromStdin = readList[]; etc. </code></pre> <p>and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?</p>
<p>MASH -- Mathematica Scripting Hack -- will do this.</p> <p>Since Mathematica version 6, the following perl script suffices:</p> <p><a href="http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl" rel="nofollow noreferrer">http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl</a></p> <p>For previous Mathematica versions, a C program is needed:</p> <p><a href="http://ai.eecs.umich.edu/people/dreeves/mash/pre6" rel="nofollow noreferrer">http://ai.eecs.umich.edu/people/dreeves/mash/pre6</a></p> <p>UPDATE: At long last, Mathematica 8 supports this natively with the "-script" command-line option:</p> <p><a href="http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/" rel="nofollow noreferrer">http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/</a></p>
<p>For mathematica 7</p> <pre><code>$ cat test.m #!/bin/bash MathKernel -noprompt -run &lt; &lt;( cat $0| sed -e '1,4d' ) | sed '1d' exit 0 ### code start Here ... ### Print["Hello World!"] X=7 X*5 </code></pre> <p>Usage:</p> <pre><code>$ chmod +x test.m $ ./test.m "Hello World!" 7 35 </code></pre>
17,836
<p>How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project?</p> <p>I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter.</p> <pre><code>CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol); </code></pre> <p>provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...</p>
<p>As a workaround, I have started to create a string representing a currency value and determining the position of the currency symbol by searching the string, but this sure looks fishy to me.</p> <pre><code> CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle); double someNumber = 0; CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &amp;someNumber); </code></pre> <p>...</p> <p>Feel free to hit me with a rolled-up newspaper and tell me the real answer...</p>
<p>You could try inspecting the format string returned from <code>CFNumberFormatterGetFormat</code>. It <a href="http://unicode.org/reports/tr35/tr35-6.html#Number_Format_Patterns" rel="nofollow noreferrer">looks like</a> you want to search for <code>¤</code> which is <code>\u00A4</code>.</p>
24,185
<p>I know this is particularly difficult with CSS and the current set of browsers, but nonetheless I have the requirement.</p> <p>I need to be able to have 3 divs in a column. Each div should be able to take up a certain percentage of the vertical space (for example, 33%). The contents of each div <em>could</em> end up being larger than the available space, so the div should be able to overflow and give the user scrollbars.</p> <p>My problem is that I'm having trouble figuring out how to give each panel that vertical height. Any ideas?</p>
<p>Maybe I'm missing something, but given:</p> <pre><code> &lt;div id="column"&gt; &lt;div id="a" class="cell"&gt;A&lt;/div&gt; &lt;div id="b" class="cell"&gt;B&lt;/div&gt; &lt;div id="c" class="cell"&gt;C&lt;/div&gt; &lt;/div&gt; </code></pre> <p>What's wrong with:</p> <pre><code> #column { height: 100%; width: 20%; } #column .cell { height: 31%; margin: 1%; background-color: green; overflow: auto; } </code></pre>
<p>The following renders properly on IE7, Firefox 3, and Google Chrome, now that I've fixed the boneheaded error in the CSS:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #one {height: 33%; overflow: auto;} #two {height: 33%; overflow: auto;} #three {height: 33%; overflow: auto;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p id="one"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.&lt;/p&gt; &lt;p id="two"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.&lt;/p&gt; &lt;p id="three"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget pede et eros adipiscing ornare. Sed ipsum dui, pulvinar eget, iaculis at, fermentum ac, lorem. Phasellus bibendum diam a nibh. In turpis lacus, condimentum id, faucibus ut, rhoncus id, enim. Quisque nec nunc at lacus placerat facilisis. Etiam mi lectus, placerat sit amet, ultricies at, tempus in, augue. Nunc in ante et erat ullamcorper pulvinar. Etiam turpis sapien, consequat vel, dignissim in, porttitor at, lectus. Integer dictum, massa eu scelerisque pretium, magna ligula auctor sapien, et tincidunt sem libero ac arcu. In at metus. Quisque quis diam at ipsum eleifend volutpat. Mauris tempor rutrum lectus. Proin fermentum nisi eu sem. Nulla eu eros. Donec velit metus, tristique tincidunt, egestas sed, tincidunt fermentum, nibh. In hac habitasse platea dictumst. Vivamus porta. Proin rhoncus ullamcorper leo. Nulla viverra, eros a dictum interdum, ante diam luctus metus, non placerat tellus metus ac lacus.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
46,034
<p>I often run into the following problem.</p> <p>I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down.</p> <p>So, I make a push to the live system and get a big, obvious error that there is no <code>NewColumnX</code>, ugh.</p> <p>Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great.</p>
<p>In Ruby on Rails, there's a concept of a <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations" rel="noreferrer">migration</a> -- a quick script to change the database.</p> <p>You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a column). Each migration is numbered, and a table keeps track of your current db version.</p> <p>To <em>migrate up</em>, you run a command called "db:migrate" which looks at your version and applies the needed scripts. You can migrate down in a similar way.</p> <p>The migration scripts themselves are kept in a version control system -- whenever you change the database you check in a new script, and any developer can apply it to bring their local db to the latest version.</p>
<p>In the absence of a VCS for table changes I've been logging them in a wiki. At least then I can see when and why it was changed. It's far from perfect as not everyone is doing it and we have multiple product versions in use, but better than nothing.</p>
2,280
<p>In all the Git tutorials I've read they say that you can do:</p> <pre><code>git init git add . git commit </code></pre> <p>When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.</p>
<p>You're meant to put the commit message in this text file, then save and quit.</p> <p>You can change the default text editor that git uses with this command:</p> <pre><code>git config --global core.editor "nano" </code></pre> <p>You have to change nano to whatever command would normally open your text editor.</p>
<p>The following is probably the easiest way to commit all changes:</p> <pre><code>git commit -a -m "Type your commit message here..." </code></pre> <p>Of course there are much more detailed ways of committing, but that should get you started.</p>
8,514
<p>Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly.</p> <p>Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one?</p> <p>Thank you.</p>
<p>An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do.</p> <p>Use ${ant.project.name} in file names, so you only have to mention your application name in the project element. For example, if you generate myapp.jar:</p> <pre><code>&lt;project name="myapp"&gt; ... &lt;target name="jar"&gt; ... &lt;jar jarfile="${ant.project.name}.jar" ... </code></pre> <p>Structure your source directory structure so that you can package your build by copying whole directories, rather than naming individual files. For example, if you are copying JAR files to a web application archive, do something like:</p> <pre><code>&lt;copy todir="${war}/WEB-INF/lib" flatten="true"&gt; &lt;fileset dir="lib" includes="**/*.jar"&gt; &lt;/copy&gt; </code></pre> <p>Use properties files for machine-specific and project-specific build file properties.</p> <pre><code>&lt;!-- Machine-specific property over-rides --&gt; &lt;property file="/etc/ant/build.properties" /&gt; &lt;!-- Project-specific property over-rides --&gt; &lt;property file="build.properties" /&gt; &lt;!-- Default property values, used if not specified in properties files --&gt; &lt;property name="jboss.home" value="/usr/share/jboss" /&gt; ... </code></pre> <p>Note that Ant properties cannot be changed once set, so you override a value by defining a new value <em>before</em> the default value.</p>
<p>I used to do exactly the same thing.... then I switched to <a href="http://maven.apache.org/" rel="nofollow noreferrer">maven</a>. Maven relies on a simple xml file to configure your build and a simple repository to manage your build's dependencies (rather than checking these dependencies into your source control system with your code). </p> <p>One feature I really like is how easy it is to version your jars - easily keeping previous versions available for legacy users of your library. This also works to your benefit when you want to upgrade a library you use - like junit. These dependencies are stored as separate files (with their version info) in your maven repository so old versions of your code always have their specific dependencies available. </p> <p>It's a better Ant.</p>
4,785
<p>I'm having a lot of trouble printing polypropylene right now, and I think it may have to do with the conditions. I'm using a very thin coat of ABS on the base plate (just as you would do when printing with ABS) in order to promote sticking.</p> <p>In this following first picture, I attempted with a 240°C tip and a 150°C bed (above PP's Tg). Oddly enough, one side actually looked somewhat decent while the other clearly had trouble sticking. The print speed on this was 1500 mm/min.</p> <p>In the second picture, I was printing with the tip at 220°C and a 50°C bed. What's interesting in that print (you may be able to see it) is that the polymer extruded with little blips of material followed by a more stringy section, rather than a steady, even filament. (Print speed on this was 2100 mm/min)</p> <p><a href="https://i.stack.imgur.com/KCbye.jpg" rel="nofollow noreferrer" title="240°C tip and a 150°C bed"><img src="https://i.stack.imgur.com/KCbye.jpg" alt="240°C tip and a 150°C bed" title="240°C tip and a 150°C bed"></a></p> <p><a href="https://i.stack.imgur.com/IaF8Z.jpg" rel="nofollow noreferrer" title="220°C tip and a 50°C bed"><img src="https://i.stack.imgur.com/IaF8Z.jpg" alt="220°C tip and a 50°C bed" title="220°C tip and a 50°C bed"></a></p> <p>Does anyone have suggestions for doing better prints with PP? </p>
<p>Polypropylene CAN be printed with excellent results, you just need a good filament roll and good printing setup. A few days ago I read this topic and was kind of afraid of testing it, now I am so happy I tried it.</p> <p>I am printing the PP filament from the brand Smart Materials 3D (search on google).</p> <p>I am using a Prusa i3 Mk2, bed heated to 70ºC and hotend to 210ºC. I ventilate the printer as much as possible: room windows open and fan at 100% after second layer. </p> <p>IMPORTANT: apply some cheap brown packaging adhesive strips to the bed, where the part is going to touch the bed, with adhesive facing down. I tried many other solutions but none worked.</p> <p><a href="https://i.stack.imgur.com/8SBUz.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/8SBUz.gif" alt="enter image description here"></a></p> <p>I have printed so far at 20mm/s constant, with 0.2 mm layer heigth, 0.4 mm extrusion width, 0.8mm retraction, flow 125%. Still optimizing setings. Parts come out very nice, with good flexibility and amazing inter layer bonding. Density is a bit lower than ABS, so excellent, and impact resistance is awesome. Check some parts I printed today:</p> <p><a href="https://i.stack.imgur.com/m3bXX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/m3bXX.jpg" alt="enter image description here"></a></p>
<p>First picture clearly shows that temperature was too hight, second one suggests too small extruding speed (too little) which is connected to your printing speed.</p> <p>35mm/s is quite slow :)</p>
245
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
<p>Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code <a href="http://osx-trash.rubyforge.org/git?p=osx-trash.git;a=blob;f=bin/trash;h=26911131eacafd659b4d760bda1bd4c99dc2f918;hb=HEAD" rel="noreferrer">here</a> via RubyCocoa. The the gist of it is:</p> <pre><code>url = NSURL.fileURLWithPath(path) finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder") item = finder.items.objectAtLocation(url) item.delete </code></pre> <p>You could easily do something similar with PyObjC.</p>
<p>Another one in ruby:</p> <pre><code>Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete </code></pre> <p>You will need <a href="http://rubygems.org/gems/rb-appscript" rel="nofollow noreferrer">rb-appscript</a> gem, you can read about it <a href="http://appscript.sourceforge.net/rb-appscript/index.html" rel="nofollow noreferrer">here</a></p>
31,064
<p>I'm trying to connect my PC to my Anet A8 through <a href="https://www.pronterface.com/" rel="nofollow noreferrer">Pronterface</a> on Ubuntu.</p> <p>But when I'm clicking on the &quot;connect&quot; button in Pronterface, all I see is &quot;<em>Connecting ...</em>&quot;.</p> <p>What I did so far</p> <ul> <li>added my user to the <code>dialout</code> group</li> <li>tried to run it as <code>root</code></li> <li>tried different baudrates</li> <li>switch to different USB cables</li> <li>tried to install and run it on a different machine and different OS (Windows) with nearly the same result (additionally I see repeated lines with <code>M105</code>, but no response)</li> </ul> <p>The printer itself works - I want to connect to it, to &quot;PID tune&quot; it, because I added a different fan duct.</p> <p><strong>How can I make sure the board isn't somewhat damaged, and its just my setup?</strong></p>
<p>I have this printer and used this board many times over USB.</p> <p>The genuine Arduino boards use the FTDI FT232RL to convert USB signals to UART signals.</p> <p>The problem with these Arduino based clone boards is that they do not use the FTDI chips as these are too expensive. These boards use a CH340G chip which is a Chinese clone which requires a specific driver to be installed before you can communicate with the board:</p> <p><a href="https://i.stack.imgur.com/C5712.jpg" rel="nofollow noreferrer" title="CH304G chipset on Anet A8 board"><img src="https://i.stack.imgur.com/C5712.jpg" alt="CH304G chipset on Anet A8 board" title="CH304G chipset on Anet A8 board" /></a> <em>Image shows a close-up of the CH340G chipset on the Anet A8 controller board.</em></p> <p>When you bought the printer, the SD-card contained the driver that you need to install on your OS. I remember that this driver was for the Windows OS. However, you can download the driver for many platforms (Windows, Mac and Linux) directly from the <a href="http://www.wch.cn/download/CH341SER_EXE.html" rel="nofollow noreferrer">manufacturer</a>.</p>
<p>You may need to install a device driver for the USB interface chip that your printer uses. I'm guessing that the Anet A8 uses a clone of the FTDI FT232RL chip (which was and may still be common with cheap Chinese printers).</p> <p>If this is the case, you will need to install the appropriate driver from this site: <a href="https://www.ftdichip.com/Drivers/VCP.htm" rel="nofollow noreferrer">FTDI Chip Virtual COM Port Drivers</a>.</p> <p>Edit: I can confirm that Pronterface will not work with my Tronxy X1 (which uses an FT232RL clone) on the latest version of Ubuntu.</p>
1,749
<p>I have read the following properties from AD,</p> <pre><code>TerminalServicesProfilePath TerminalServicesHomeDirectory TerminalServicesHomeDrive </code></pre> <p>I've tried DirectoryEntry and DirectorySearcher. But they does not include the properties.</p> <p>I found some example in vbscript and VC to read them. However I failed to make it working in C#. Am I missing some tricky thing?</p> <p>EDIT: Am I have to run it on "Windows Server" to make it works? Can it be read from win XP?</p>
<p>I don't remember exactly, but it's something like this:</p> <pre><code>//user is a DirectoryEntry IADsTSUserEx adsiUser = (IADsTSUserEx)user.NativeObject; </code></pre> <p>then you can get the TerminalServices properties you want via adsiUser.</p> <p>From my experience you're better off developing on a Windows Server with access to AD due to the libraries you use. Then you'll probably make the above work, too :)</p>
<p>This works for me:</p> <pre><code> DirectoryEntry user = new DirectoryEntry("LDAP://" + sLDAP_SERVER + "/cn=" + SAMAccount + "," + sLdapFullPath, sUser, sPwd); //ActiveDs.IADsUser iADsUser = (ActiveDs.IADsUser)user.NativeObject; ActiveDs.IADsUser cont = null; cont = user.NativeObject as ActiveDs.IADsUser; TSUSEREXLib.IADsTSUserEx m_TsUser = (TSUSEREXLib.IADsTSUserEx)cont; int m_TSLogonDisabled = 0; m_TsUser.AllowLogon = m_TSLogonDisabled; </code></pre>
46,333
<p>I've done some Googling, and can't find anything, though maybe I'm just looking in the wrong places. I'm also not very adept at VBA, but I'm sure I can figure it out with the right pointers :)</p> <p>I have a string I'm building that's a concatenation of various cells, based on various conditions. I hit these in order.</p> <pre><code>=IF(A405&lt;&gt;A404,G405,G405&amp;H404) </code></pre> <p>What I want to do is go back through my concatenated list, removing a superseded value if the superseder is in the list.</p> <p>For example, see the following list:</p> <pre><code>A, D, G, Y, Z </code></pre> <p>I want to remove <code>D</code> <em>if</em> and <strong>only</strong> <em>if</em> <code>Y</code> is present.</p> <p>How would I go about this? (VBA or in-cell, though I'd prefer in-cell)</p>
<p>Try:</p> <pre><code>=IF(ISERROR(FIND("Y",A1)),A1,SUBSTITUTE(A1,"D, ","")) </code></pre> <p>But that assumes you always have the comma and space following the D.</p>
<p>It's probably easier to start at the end, make your additions to the beginning of the string, and only add D if Y is not present.</p>
32,947
<p>I have an Excel spreadsheet with 1 column, 700 rows. I care about every seventh line. I don't want to have to go in and delete the 6 rows between each row I care about. So my solution was to create another sheet and specify a reference to each cell I want.</p> <pre><code>=sheet1!a1 =sheet1!a8 =sheet1!a15 </code></pre> <p>But I don't want to type in each of these formulas ... `100 times.I thought if I selected the three and dragged the box around, it would understand what I was trying to do, but no luck.</p> <p>Any ideas on how to do this elegantly/efficiently?</p>
<p>In A1 of your new sheet, put this:</p> <pre><code>=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0) </code></pre> <p>... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.</p> <p>If you want to copy the nth line but multiple columns, use the formula:</p> <pre><code>=OFFSET(Sheet1!A$1,(ROW()-1)*7,0) </code></pre> <p>This can be copied right too.</p>
<p>Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);</p> <p>If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.</p>
25,923
<p>I've got two applications I'm developing using Qt on windows. I want the user to be able to press a button in one application which makes the other application come to the foreground. (The programs communicate using QLocalSocket and named pipes.)</p> <p>Currently I'm using Qt's QWidget::activateWindow() which occasionally brings the application to the foreground, but most of the time it just highlights the program on the taskbar.</p> <p>Can someone please tell me how to do this, preferably using Qt although failing that using the WIN32 API would be fine.</p> <hr> <p>Unfortunately, I couldn't find a way to do this only with Qt. I solved it using Chris Becke's suggestion of calling SetForegroundWindow from the currently active application.</p>
<p>Are you sure this is not a debugging issue? The deal is, if an application HAS the foreground, it is allowed to change the foreground.</p> <p>Clicking a button on window A will give that windows thread foreground activation. If it calls SetForegroundWindow (or equivalent) on the other window, that window WILL be given the foreground.</p> <p>If, on the other hand, it simply sends a message to the other app, which tries to SetForeground on itself, that will fail. AllowSetForegroundWindow is used in situations where a 'legacy' app needs to be given permission - by a foreground app - to take the foreground. Once again, AllowSet... only works if called from a thread that owns the current active foreground window.</p>
<p>I think the APIs you need are <a href="http://msdn.microsoft.com/en-us/library/ms632668(VS.85).aspx" rel="nofollow noreferrer">AllowSetForegroundWindow()</a> and <a href="http://msdn.microsoft.com/en-us/library/ms633539(VS.85).aspx" rel="nofollow noreferrer">SetForegroundWindow()</a>. I don't know what the equivalent Qt calls are.</p>
24,982
<p>I'm writing a resource handling method where I control access to various files, and I'd like to be able to make use of the browser's cache. My question is two-fold:</p> <ol> <li><p>Which are the definitive HTTP headers that I need to check in order to know for sure whether I should send a 304 response, and what am I looking for when I do check them?</p></li> <li><p>Additionally, are there any headers that I need to send when I initially send the file (like 'Last-Modified') as a 200 response?</p></li> </ol> <p>Some psuedo-code would probably be the most useful answer.</p> <hr> <p>What about the cache-control header? Can the various possible values of that affect what you send to the client (namely max-age) or should only if-modified-since be obeyed?</p>
<p>Here's how I implemented it. The code has been working for a bit more than a year and with multiple browsers, so I think it's pretty reliable. This is based on <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">RFC 2616</a> and by observing what and when the various browsers were sending.</p> <p>Here's the pseudocode:</p> <pre> server_etag = gen_etag_for_this_file(myfile) etag_from_browser = get_header("Etag") if etag_from_browser does not exist: etag_from_browser = get_header("If-None-Match") if the browser has quoted the etag: strip the quotes (e.g. "foo" --> foo) set server_etag into http header if etag_from_browser matches server_etag send 304 return code to browser </pre> <p>Here's a snippet of my server logic that handles this.</p> <pre> /* the client should set either Etag or If-None-Match */ /* some clients quote the parm, strip quotes if so */ mketag(etag, &sb); etagin = apr_table_get(r->headers_in, "Etag"); if (etagin == NULL) etagin = apr_table_get(r->headers_in, "If-None-Match"); if (etag != NULL && etag[0] == '"') { int sl; sl = strlen(etag); memmove(etag, etag+1, sl+1); etag[sl-2] = 0; logit(2,"etag=:%s:",etag); } ... apr_table_add(r->headers_out, "ETag", etag); ... if (etagin != NULL && strcmp(etagin, etag) == 0) { /* if the etag matches, we return a 304 */ rc = HTTP_NOT_MODIFIED; } </pre> <p>If you want some help with etag generation post another question and I'll dig out some code that does that as well. HTH!</p>
<p>regarding cache-control:</p> <p>You shouldn't have to worry about the cache-control when serving out, other than setting it to a reasonable value. It's basically telling the browser and other downstream entities (such as a proxy) the maximum time that should elapse before timing out the cache.</p>
2,647
<p>What is the best way to parse a float in CSharp? I know about TryParse, but what I'm particularly wondering about is dots, commas etc.</p> <p>I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round. How can I best capture this?</p>
<p>I agree with leppie's reply; to put that in terms of code:</p> <pre><code>string s = "123,456.789"; float f = float.Parse(s, CultureInfo.InvariantCulture); </code></pre>
<p>Since you don't know the web user's culture, you can do some guesswork. TryParse with a culture that uses , for separators and . for decimal, AND TryParse with a culture that uses . for separators and , for decimal. If they both succeed but yield different answers then you'll have to ask the user which they intended. Otherwise you can proceed normally, given your two equal results or one usable result or no usable result.</p>
17,797
<p>I am currently updating a web app that uses ActiveX objects in client side code to manipulate some xml. Of course, this app only works in IE and I need to get it cross browser compatible.</p> <p>I am looking to get a javascript xml library to handle the cross browser oddities, and was wondering if the ASP.Net ajax library would work. I have looked around a bit, but I haven't been able to any examples of loading a fresh xmldom object up using this. If not, any other good libraries out there I should take a look at?</p> <p>Thanks</p>
<p>Is "sometex.png" in your resources? If you right-click on the .app that Xcode creates and select "Show Package Contents", do you see it there? It sounds like it's not being bundled with your app at build time.</p>
<p>Looks like the program can't find "sometex.png". When I replace "sometex.png" with the entire path"users/ blah blah /sometex.png" the crash doesn't happen.</p>
31,768
<p>I have used checkbox column in gridview. I want to check status of that checkboxes. On click of a button it should be checked that if any checkbox is checked or not. If none checkbox is checked then it should display alert message that check checkbox first.</p>
<p>Hey, I found answer. It is as follows:</p> <pre><code>function checkBoxselectedornot() { var frm=document.forms['aspnetForm']; var flag=false; for(var i=0;i&lt;document.forms[0].length;i++) { if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1) { if(document.forms[0].elements[i].checked) { flag=true } } } if (flag==true) { return true }else { alert('Please select at least one Event.') return false } } </code></pre>
<pre><code> &lt;script type="text/javascript" language="javascript"&gt; function CheckboxSelect() { var LIntCtr; var LIntSelectedCheckBoxes = 0; for (LIntCtr = 0; LIntCtr &lt; document.forms[0].elements.length; LIntCtr++) { if ((document.forms[0].elements[LIntCtr].type == 'checkbox') &amp;&amp; (document.forms[0].elements[LIntCtr].name.indexOf('chkID') &gt; -1)) { if (document.forms[0].elements[LIntCtr].checked == true) { LIntSelectedCheckBoxes = parseInt(LIntSelectedCheckBoxes) + 1; } } } if (parseInt(LIntSelectedCheckBoxes) == 0) { alert('User(s) Must Be Selected For operation !'); return false; } } &lt;/script&gt; </code></pre>
45,425
<p>OK, so Sybase (12.5.4) will let me do the following to DROP a table if it already exists:</p> <pre><code>IF EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'a_table' AND type = 'U' ) DROP TABLE a_table GO </code></pre> <p>But if I try to do the same with table creation, I always get warned that the table already exists, because it went ahead and tried to create my table and ignored the conditional statement. Just try running the following statement twice, you'll see what I mean:</p> <pre><code>IF NOT EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'a_table' AND type = 'U' ) CREATE TABLE a_table ( col1 int not null, col2 int null ) GO </code></pre> <p>Running the above produces the following error:</p> <blockquote> <p><em>SQL Server Error on (localhost) Error:2714 at Line:7 Message:There is already an object named 'a_table' in the database.</em></p> </blockquote> <p>What's the deal with that?!</p>
<p>The only workaround I've come up with so far is to use execute immediate:</p> <pre><code>IF NOT EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'a_table' AND type = 'U' ) EXECUTE("CREATE TABLE a_table ( col1 int not null, col2 int null )") GO </code></pre> <p>works like a charm, feels like a dirty hack.</p>
<pre><code>IF object_id('a_table') IS NULL BEGIN CREATE TABLE a_table ( col1 int not null, col2 int null ) END </code></pre>
39,653
<p>I'm trying to use <a href="http://www.jboss.org/community/docs/DOC-10032" rel="noreferrer">this method</a> for receiving mail in our EJB3 app. In short, that means creating an MDB with the following annotations:</p> <pre><code>@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "mailServer", propertyValue = "imap.company.com"), @ActivationConfigProperty(propertyName = "mailFolder", propertyValue = "INBOX"), @ActivationConfigProperty(propertyName = "storeProtocol", propertyValue = "imap"), @ActivationConfigProperty(propertyName = "debug", propertyValue = "false"), @ActivationConfigProperty(propertyName = "userName", propertyValue = "username"), @ActivationConfigProperty(propertyName = "password", propertyValue = "pass") }) @ResourceAdapter("mail-ra.rar") @Name("mailMessageBean") public class MailMessageBean implements MailListener { public void onMessage(final Message msg) { ...snip... } } </code></pre> <p>I have this working, but the situation is less than ideal: The hostname, username and password are hardcoded. Short of using ant and build.properties to replace those values before compilation, I don't know how to externalize them. </p> <p>It would be ideal to use an MBean, but I have no idea how to get the values from the MBean to the MDB configuration.</p> <p>How should I do this?</p>
<p>You can externalise the annotations into the ejb-jar.xml that you deploy in the META-INF of your jar file as follows:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ejb-jar version="3.0"&gt; &lt;enterprise-beans&gt; &lt;message-driven&gt; &lt;ejb-name&gt;YourMDB&lt;/ejb-name&gt; &lt;ejb-class&gt;MailMessageBean&lt;/ejb-class&gt; &lt;activation-config&gt; &lt;activation-config-property&gt; &lt;activation-config-property-name&gt;username&lt;/activation-config-property-name&gt; &lt;activation-config-property-value&gt;${mdb.user.name}&lt;/activation-config-property-value&gt; &lt;/activation-config-property&gt; ... ... &lt;/activation-config&gt; &lt;/message-driven&gt; &lt;/enterprise-beans&gt; </code></pre> <p></p> <p>Then you can set the mdb.user.name value as a system property as part of the command line to your application server using -Dmdb.user.name=theUserName and it will magically get picked up by the mdb.</p> <p>Hope that helps.</p>
<p>As of JBoss AS 5.1 at least, you can use AOP to configure the @ActivationConfigProperties. I discovered this by looking at the examples that jboss provides <a href="http://docs.jboss.org/ejb3/docs/tutorial/1.0.0/ejb3-1.0.0-tutorials.zip" rel="nofollow">here</a>. This is useful if you do not want your username and passwords available to the entire container in a systems property, or if you are like me and never, I repeat NEVER, want to deploy an artifact with a username/password in it. Any how, here is the jist...</p> <p>Annotate the mdb like this...</p> <pre><code>... @MessageDriven @AspectDomain("TestMDBean") public class TestMDBean implements MessageListener { ... </code></pre> <p>Then add a ${whatever}-aop.xml to the deploy dir with internals like below. I left the original comments in there in case Jaikiran does make the changes mentioned...</p> <blockquote> <p>Note: the annotation must be on one line only.</p> </blockquote> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;aop xmlns="urn:jboss:aop-beans:1.0"&gt; &lt;!-- TODO: Jaikiran - These interceptor declarations need not be here since they are already declared through the ejb3-interceptors-aop.xml. Duplicating them leads to deployment errors. However, if this custom-ejb3-interceptors-aop.xml needs to be independent, then we must find a better way of declaring these. Right now, commenting these out, can be looked at later. --&gt; &lt;!-- &lt;interceptor class="org.jboss.ejb3.AllowedOperationsInterceptor" scope="PER_VM"/&gt; &lt;interceptor class="org.jboss.ejb3.entity.TransactionScopedEntityManagerInterceptor" scope="PER_VM"/&gt; &lt;interceptor factory="org.jboss.ejb3.security.RunAsSecurityInterceptorFactory" scope="PER_CLASS"/&gt; &lt;interceptor class="org.jboss.ejb3.stateless.StatelessInstanceInterceptor" scope="PER_VM"/&gt; &lt;interceptor factory="org.jboss.ejb3.interceptor.EJB3InterceptorsFactory" scope="PER_CLASS_JOINPOINT"/&gt; &lt;interceptor factory="org.jboss.aspects.tx.TxInterceptorFactory" scope="PER_CLASS_JOINPOINT"/&gt; --&gt; &lt;domain name="TestMDBean" extends="Message Driven Bean" inheritBindings="true"&gt; &lt;annotation expr="!class(@org.jboss.ejb3.annotation.DefaultActivationSpecs)"&gt; @org.jboss.ejb3.annotation.DefaultActivationSpecs (value={@javax.ejb.ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @javax.ejb.ActivationConfigProperty(propertyName="destination", propertyValue="queue/MyQueue"), @javax.ejb.ActivationConfigProperty(propertyName="user", propertyValue="testusr"), @javax.ejb.ActivationConfigProperty(propertyName="password", propertyValue="testpwd")}) &lt;/annotation&gt; &lt;/domain&gt; &lt;/aop&gt; </code></pre>
39,688
<p>I guess, the following is a standard problem on every school or university:</p> <p>It is Your job to teach programming. Unfortunately, some of the students are semi-professionals and have years of experience while others do not even know the basic concepts, e.g. the concept "typed variable".</p> <p>As far as I know, this leads to one of the following situations:</p> <ol> <li>Programming is tought from its very basics. The experienced students get bored and discontinue to visit the lectures. As a consequence, they will miss even the stuff they do not already know.</li> <li>Teachers and professors claim that they require basic knowledge (whatever that means). Inexperienced students cannot follow the lectures and a lot of them will focus on unimportant stuff (e.g. understanding every detail of a complex example while not getting the concept behind the example). Some of them will give up.</li> <li>Universities invent an artificial programming language to give experienced programmers and newbies "equal chances". Most students will get frustrated about the "useless language".</li> </ol> <p>Is there a fourth solution, which is better than those above?</p>
<p>I think the best way to keep it interesting is to bring up practical and interesting exercises along the theory. Taking a problem-solution approach is great (with interesting, funny, exciting, real-world problems). This requires the professor himself to have hands-on experience, work with new technologies and know them pretty well and not just teach what he had learned a couple decades ago.</p> <p>The thing is, programming should be learned by practice. The instructor should focus on motivating students to code and try to solve problems themselves. This can be done by assigning a complete life-like project at the beginning of the course and working through the subproblems that occur in the project in the class. This way, students will have an idea why some specific feature in the programming language exists and where it might be useful.</p> <p>Just a thought though. Not tried it! ;)</p>
<p>In one course I took, a large part of the course grade was derived from a end-of-term project which was announced in advance with extra credit available for assorted add-ons and frills. Sufficiently experienced student could start working on it while their less prepraed brethren were being taught the basics.</p> <p>But as Dave Markle says, part of this is a matter of getting the right students into your class: you really want a cohort that is fiarly well matched at the start.</p>
45,283
<p>What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980&lt; where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?</p>
<p>Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger. </p> <p>Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people. </p> <p>Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it. </p> <p>I could see a situation like this making a detectable difference:</p> <pre><code>inline int aplusb_pow2(int a, int b) { return (a + b)*(a + b) ; } for(int a = 0; a &lt; 900000; ++a) for(int b = 0; b &lt; 900000; ++b) aplusb_pow2(a, b); </code></pre>
<p>Conclusion from <a href="https://stackoverflow.com/questions/60830/what-is-wrong-with-using-inline-functions">another discussion</a> here:</p> <p><strong>Are there any drawbacks with inline functions?</strong></p> <p>Apparently, There is nothing wrong with using inline functions.</p> <p>But it is worth noting the following points!</p> <ul> <li><p>Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inline_Functions" rel="nofollow noreferrer">- Google Guidelines</a></p></li> <li><p>The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html" rel="nofollow noreferrer">- Source</a></p></li> <li><p>There are few situations where an inline function may not work:</p> <ul> <li>For a function returning values; if a return statement exists.</li> <li>For a function not returning any values; if a loop, switch or goto statement exists. </li> <li>If a function is recursive. <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html" rel="nofollow noreferrer">-Source</a></li> </ul></li> <li><p>The <code>__inline</code> keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not <code>__inline</code> is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the <code>__inline</code> keyword to be ignored. <a href="http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/clug/zcoptinl.htm" rel="nofollow noreferrer">-Source</a></p></li> </ul>
17,580
<p>Does anyone know of a simple way of getting the raw xml that is returned from querying a webservice?</p> <p>I have seen a way of doing this via <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2006/10/09/Examine-XML-of-Web-Service-Response.aspx" rel="noreferrer">Web Services Enhancements</a>, but I don't want an added dependency.</p>
<p>I would primarily use a text field, or a series of text fields, even if you are using a numerical phone number for the following reasons. </p> <ol> <li>Phone numbers have a great range of values, including extension numbers which may result in numerical columns losing precision.</li> <li>Losing precision in a phone number is rather bad. </li> <li>There is no logical reason to want to perform math ( addition/multiplication ) on a phone number. </li> </ol> <p>Additionally, you may want to specify how you are using this data. If you are planning an automated messaging service, you're going to need a series of relaying agents to broadcast via, so you may as well add an identifier that pertains to the relay the information pertains to. Then all you have to worry about is that the relaying agent can understand the content in the text fields. </p>
<p>I don't know if you have read these two questions, but they might help you a little.</p> <ul> <li><a href="https://stackoverflow.com/questions/290597/phone-number-columns-in-a-database">Phone Number Columns in a Database</a></li> <li><a href="https://stackoverflow.com/questions/41925/is-there-a-standard-for-storing-normalized-phone-numbers-in-a-database">Is there a standard for storing normalized phone numbers in a database?</a></li> </ul> <p>Perhaps it would be wise to store the type of number (landline, cell, fax) and/or the messages that can be received on it (voice, text, email). Note that in the US, it is also possible to send text messages to a phone via email, but I believe that is dependent on the carrier.</p>
40,617
<p>I need to queue events and tasks for external systems in a reliable/transactional way. Using things like MSMQ or ActiveMQ look very seductive, but the transactional part becomes complicated (MSDTC, etc).</p> <p>We could use the database (SQL Server 2005+, Oracle 9+) and achieve easier transactional support, but the queuing part becomes uglier.</p> <p>Neither route seems all that great and is filled with nasty gotchas and edge cases.</p> <p>Can someone offer some practical guidance in this matter?</p> <p>Think: E/C/A or a scheduled task engine that wakes up every so often and see if there are any scheduled tasks that need running at this time (i.e. next-run-date has passed, but expiration-date has not yet been reached).</p>
<p>our system has 60 computers, each running 12 tasks (threads) which need to "get next job". All in all, it comes to 50K "jobs" per day. do the math of how many transactions per minute and realize task time is variable, so it is possible to get multiple "pop" events at the exact same time.</p> <p>We had our first version using MSMQ. conclusion: <strong>stay away</strong>. While it did do just fine with the load and synchronization issues, it had 2 problems. one annoying and one deal breaker.</p> <p><em>Annoying:</em> as Enterprise software, MSMQ has security needs that just make it one more thing to set up and fight with the customers network admin.</p> <p><em>Deal breaker:</em> then came the time we wanted to take the next job, but not using a simple pop but something like "get next BLUE job" or "get next YELLOW job". can't do it!</p> <p>We went to plan B: Implemented our own Q with a single SQL 2005 table. <strong>could not be happier</strong></p> <p>I stressed test it with 200K messages per day, worked. We can make the "next" logic as complicated as we want.</p> <p>the catch: you need to be very careful with the SQL that takes the next item. Since you want it to be fast and NON locking. there are 2 very important SQL <strong>hints</strong> we used based on some research. The magic goes something like this:</p> <pre><code>SELECT TOP 1 @Id = callid FROM callqtbl WITH (READPAST, XLOCK) where 1=1 ORDER BY xx,yy </code></pre>
<p>Is WebSphere MQ (MQ Series) an option? Is supports transactional messaging.</p>
20,029
<p>I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) )</p> <p>In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field).</p> <p>When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again.</p> <p>In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause).</p> <p>The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved.</p> <p>Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation?</p> <p>EDIT:</p> <p>Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis)</p> <p><strong>(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)</strong></p> <pre><code> declare @p1 int set @p1=180150003 declare @p3 int set @p3=2 declare @p4 int set @p4=4 declare @p5 int set @p5=-1 </code></pre> <p><strong>(Retreiving the table that holds definition information for the user-generated fields)</strong></p> <pre><code> exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5 go </code></pre> <p><strong>(I think my code was iterating through the list of them here, grabbing the current information)</strong></p> <pre><code> exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,1025,1,1 go exec sp_cursorfetch 180150003,1028,1,1 go exec sp_cursorfetch 180150003,32,1,1 go </code></pre> <p><strong>(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)</strong></p> <pre><code> exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go </code></pre> <p><strong>(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)</strong> </p> <pre><code> ALTER TABLE CustomizableTable DROP COLUMN _weveknown; </code></pre> <p><strong>(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)</strong></p> <p><code><pre> go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf' go ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give' go ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up' go ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy' go ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you' go ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never' go ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna' go ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL go </pre></code></p> <p><strong>(Closing the Transaction...?)</strong></p> <p><code><pre> exec sp_cursorclose 180150003 go </pre></code></p> <p>After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction.</p>
<p>The code is using a server-side cursor, that's what those calls are for. The first set of calls is preparing/opening the cursor. Then fetching rows from the cursor. Finally closing the cursor. Those sprocs are analogous to the OPEN CURSOR, FETCH NEXT, CLOSE CURSOR T-SQL statements.</p> <p>I'd have to take a closer look (which I will), but my guess is there is something going on with the server-side cursor, the encapsulating transaction, and the DDL.</p> <p>Some more questions:</p> <ol> <li>Are you meaning to use server-side cursors in this case?</li> <li>Are the ADO Commands all using the same active connection?</li> </ol> <p><strong>Update:</strong></p> <p>I'm not exactly sure what's going on.</p> <p>It looks like you're using server-side cursors so you can use Recordset.Update() to push changes back to the server, in addition to executing generated SQL statements to alter schema and update data in the dynamic table(s). Using the same connection, inside an explicit transaction.</p> <p>I'm not sure what effect the cursor operations will have on the rest of the transaction, or vice-versa, and to be honest I'm surprised this isn't working.</p> <p>I don't know how large of a change it would be, but I would recommend moving away from the server-side cursors and building the UPDATE statements for your table updates.</p> <p>Sorry I couldn't be of more help.</p> <p>BTW- I found the following information on the sp_cursor calls:</p> <p><a href="http://jtds.sourceforge.net/apiCursors.html" rel="nofollow noreferrer">http://jtds.sourceforge.net/apiCursors.html</a></p>
<p>The behavior you describe is allowed. How is the code making the schema changes? Building SQL on the fly and executing through an ADO Command? Or using ADOX?</p> <p>If you have access to the database server, try running a SQL Profiler trace while testing the scenario you outlined. See if the trace logs any errors/rollbacks.</p>
8,235
<p>I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.</p> <p>My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using <code>gcc</code>).</p> <p>I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?</p>
<p>For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in <code>execinfo.h</code> to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found <a href="http://www.gnu.org/software/libc/manual/html_node/Backtraces.html" rel="noreferrer">in the libc manual</a>.</p> <p>Here's an example program that installs a <code>SIGSEGV</code> handler and prints a stacktrace to <code>stderr</code> when it segfaults. The <code>baz()</code> function here causes the segfault that triggers the handler:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;execinfo.h&gt; #include &lt;signal.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } void baz() { int *foo = (int*)-1; // make a bad pointer printf("%d\n", *foo); // causes segfault } void bar() { baz(); } void foo() { bar(); } int main(int argc, char **argv) { signal(SIGSEGV, handler); // install our handler foo(); // this will call foo, bar, and baz. baz segfaults. } </code></pre> <p>Compiling with <code>-g -rdynamic</code> gets you symbol info in your output, which glibc can use to make a nice stacktrace:</p> <pre><code>$ gcc -g -rdynamic ./test.c -o test </code></pre> <p>Executing this gets you this output:</p> <pre><code>$ ./test Error: signal 11: ./test(handler+0x19)[0x400911] /lib64/tls/libc.so.6[0x3a9b92e380] ./test(baz+0x14)[0x400962] ./test(bar+0xe)[0x400983] ./test(foo+0xe)[0x400993] ./test(main+0x28)[0x4009bd] /lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb] ./test[0x40086a] </code></pre> <p>This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before <code>main</code> in addition to <code>main</code>, <code>foo</code>, <code>bar</code>, and <code>baz</code>.</p>
<p>I forgot about the GNOME tech of "apport", but I don't know much about using it. It is used to generate stacktraces and other diagnostics for processing and can automatically file bugs. It's certainly worth checking in to.</p>
10,263
<p>I print my ABS at:</p> <ul> <li>240 °C;</li> <li>with a bedtemp of 80 °C; </li> <li>5 % rectilinear infill;</li> <li>0.25 mm layer height;</li> <li>2 solid layers top and bottom; </li> <li>Fan is completely disabled;</li> <li>0.25 mm extrusion width;</li> <li>50 mm/s perimeter print speed;</li> <li>60 mm/s infill speed;</li> <li>20 mm/s top solid and solid speed;</li> <li>No acceleration.</li> </ul> <p>When printing ABS, I place an aluminum foil lined cardboard box over my printer to help keep the ambient temps up for less warping and stronger prints. I've never actually measured the temperature inside, but the cardboard box insulates very well. </p> <p>I get this weird kind of tearing in my prints, I'm not sure if it's from too large of gaps in my infill, too fast print speeds, or not enough top layers. </p> <p><a href="https://i.stack.imgur.com/r0Y27.jpg" rel="nofollow noreferrer" title="Torn print"><img src="https://i.stack.imgur.com/r0Y27.jpg" alt="Torn print" title="Torn print"></a></p> <p>Another guess is some kind of drooping because of the high ambient temps. </p> <p>The tearing only occurs on large top layer surfaces. </p>
<p>Looking at the infill pattern visible through the tears in the top layer, it looks as if you have unreliable extrusion on the infill layers also.</p> <p>The solid fill layer is lifted and torn, so it is unlikely that one or two more layers of solid fill will make the result better. In my experience, bumps lead to taller bumps and print failure.</p> <p>These diagnostic steps have helped me:</p> <ul> <li><p>Print a 3 layer solid fill version, the top surface should be smooth and free of bumps;</p></li> <li><p>Print a single layer version, it should be smooth, well attached to the print bed, of even thickness, and a good surface for the next layer.</p></li> </ul> <p>Given your results, I am suspicious that you may have one of these problems, which I've listed in the order of likelihood:</p> <ol> <li><p>Partially blocked nozzle</p></li> <li><p>Excessive drag from the filament supply, such as a spool with crossed filament which jams itself, preventing unwrapping;</p></li> <li><p>Extruder feed roller slipping (perhaps full of dust), often a side effect of 1 and 2;</p></li> <li><p>G-code error dropping the temperature;</p></li> <li><p>Bad heater or thermistor, perhaps intermittent short of the thermistor, causing under heating even though the "average" indicated temperature is correct.</p></li> </ol> <p>Printing gliders is a cool application. It shows off the weight advantage extrusion 3-D printing can deliver. Nice.</p>
<p>This looks a bit like you may have a level issue with your printer. I've had similar results when my nozzle isn't clean and my bed is slightly off level. When the nozzle isn't clean (inside and out) either the flow rate out is different than what you set it to be due to back pressure or there is material on the nozzle causing the nozzle to drag through the molten plastic. </p> <p>I also use a lower nozzle temperature, around 220-230°C. Printing with 10% infill is my standard setting with two shell layers, honeycomb fill or diamond fill. </p>
673
<p>I have basically succumbed to the fact that if you are a hardcore computer user, you will have to reimage your computer every few months because something bad happened. Because of this, I bought imaging software and then really got into imaging. I am now ready to move my development environment completely into a virtual machine so that I can test sites on IIS as though I am on a dev network (and backup these images easily).</p> <p>The question is, what is the best virtual development platform for a 4 gb laptop? A virtual Vista Business with 3 gb of ram, windows XP sp3 with 3 gb of ram, or Windows Server 2003 with 3 gb of usable ram.</p> <p>Tools I will need to install:</p> <p>*sql server 2005 dev edition<br/> *vs 2008 sp1 <br/> *tools for silverlight<br/> *and multiple other smaller testing tools<br/></p>
<p>I have tried the following combinations:</p> <ul> <li>Windows XP SP3 on Virtual Server 2005 R2 </li> <li>Windows Vista Business x64 on Virtual Server 2005 R2 </li> <li>Windows XP on Virtual PC 2007 </li> <li>Windows 2003 on Virtual Server 2005 R2 </li> <li>Windows XP on VMWare Fusion</li> </ul> <p>and the Virtual Server installations where either local or hosted on a server and they all ran fine and about the same speed.</p> <p>The VMWare Fusion Virtual Machine running under OS X is (seat of the pants) significantly faster than the others. I haven't tested VMWare on Windows to see if it is VMWare or the Hardware making the difference, but it's something worth looking into.</p>
<p>I think the biggest question (from my standpoint) is whether or not you'll be doing development (like SharePoint) that requires a server platform. If you anticipate a lot of SharePoint development (or perhaps Exchange, or BizTalk, or another product that requires development be done on a server platform), then go with Windows Server 2003. If not, then I'd probably choose XP, though Vista isn't a bad development platform.</p>
49,181
<p>Greetings, </p> <p>I have a particular object which can be constructed from a file, as such:</p> <pre><code>public class ConfigObj { public ConfigObj(string loadPath) { //load object using .Net's supplied Serialization library //resulting in a ConfigObj object ConfigObj deserializedObj = VoodooLoadFunction(loadpath); //the line below won't compile this = thisIsMyObj; } } </code></pre> <p>I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:</p> <ul> <li>Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.</li> <li>Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.</li> </ul> <p>I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?</p>
<p>Your second option is what is called a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow noreferrer">factory method</a> and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.</p>
<p>I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.</p>
25,486
<p>I have a form that sits behind ASP.NET forms authentication. So far, the implementation follows a typical "out of the box" type configuration.</p> <p>One page allows users to post messages. If the user sits on that page for a long time to compose the message, it may run past the auth session expiration. In that case, the post does not get recorded... they are just redirected to the login page.</p> <p>What approach should I take to prevent the frustrating event of a long message being lost? </p> <p>Obviously I could just make the auth session really long, but there are other factors in the system which discourage that approach. <strong>Is there a way I could make an exception for this particular page so that it will never redirect to the Login so long as its a postback?</strong></p>
<p>My coworker came up with a general solution to this kind of problem using an HttpModule.</p> <p>Keep in mind he decided to to handle his own authentication in this particular application.</p> <p>Here goes:</p> <p>He created an HttpModule that detected when a user was no longer logged in. If the user was no longer logged in he took the ViewState of that page along with all the form variables and stored it into a collection. After that the user gets redirected to the login page with the form variables of the previous page and the ViewState information encoded in a hidden field.</p> <p>After the user successfully reauthenticates, there is a check for the hidden field. If that hidden field is available, a HTML form is populated with the old post's form variables and viewstate. Javascript was then used auto submit this form to the server.</p>
<p>When the session timeout happens the user's session (and page information) get disposed, which would mean the eventual postback would fail. As the others have suggested there are some work arounds, but they all assume you don't care about authentication and security on that particular page.</p> <p>I would recommend using Ajax to post back silently every 10 mins or so to keep it alive, or increase the timeout of the session as you suggest. You could try to make a page specific section in your web config and include in there a longer timeout.</p>
37,072
<p>I have an asp.net textbox and a MaskedEditExtender control attached to it. The textbox is used for date input. The MaskedEditExtender has MaskType="Date" Mask="99/99/9999".</p> <p>When the form is submitted with an invalid date, the browser shows a Javascript error "... string was not recognized as a valid datetime".</p> <p>I know why the error shows up. Is there a way to use the extender to just control what the user enters and not validate or convert the input? </p>
<p>Stop the form from submitting with an invalid date. Use a MaskedEditValidator</p>
<p>Don't specify mask type as "Date", that should stop this error.</p>
18,221
<p>I'm looking for SMS library that is written in c#, anyone the best library for it and it's free ? I can find more than 1 in Linux, but I'm can't found anything that is written in c# and free</p>
<p>To logon as the 'console' user (the one to be used for logging in locally) then you use a parameter for mstsc.exe From a command prompt type in mstsc /h to see the help. MSTSC /ADMIN /V:YOURSERVERNAME or MSTSC /CONSOLE /V:YOURSERVERNAME</p> <p>(depending on the version that you have)</p>
<p>Here's how you can switch over.</p> <ol> <li>Start task manager</li> <li>Switch to the users tab</li> <li>There should be two users listed. The one you logged on with and the original session you are trying to connect to.</li> <li>Right click on the one you want to connect to and select "Switch" or "connect". I can't remember the exact one. </li> </ol>
42,548