instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Do you use Luabind, toLua++, or some other library (if so, which one) or none at all?</p> <p>For each approach, what are the pro's and con's?</p>
<p>I can't really agree with the 'roll your own' vote, binding basic types and static C functions to Lua is trivial, yes, but the picture changes the moment you start dealing with tables and metatables; things go trickier very quickly.</p> <p>LuaBind seems to do the job, but I have a philosophical issue with it. For me it seems like if your types are already complicated the fact that Luabind is heavily templated is not going to make your code any easier to follow, as a friend of mine said "you'll need Herb Shutter to figure out the compilation messages". Plus it depends on Boost, plus compilation times get a serious hit, etc.</p> <p>After trying a few bindings, Tolua++ seems the best. Tolua doesn't seem to be very much in development, where as Tolua++ seems to work fine (plus half the 'Tolua' tutorials out there are, in fact, 'Tolua++' tutorials, trust me on that:) Tolua does generate the right stuff, the source can be modified and it seems to deal with complicated cases (like templates, unions, nameless structs, etc, etc)</p> <p>The biggest issue with Tolua++ seems to be the lack of proper tutorials, pre-set Visual Studio projects, or the fact that the command line is a bit tricky to follow (you path/files can't have white spaces -in Windows at least- and so on) Still, for me it is the winner.</p>
<p>I don't use any library. I have used SWIG to expose a C library some time ago, but there was too much overhead, and I stop using it.</p> <p>The pros are better performance and more control, but its takes more time to write.</p>
12,889
<p>I have a VS solution, with the following projects.</p> <p>-GUI<br> -DataAccess<br> -BusinessLogic<br> -BusinessObjects </p> <p>but where should the main model class reside? This is usually a cache of a set of objects which are the results from the data access layer and the GUI using virtual grids to view data inside the model. The question would be the same using MVC or MVP</p> <p>thoughts?</p>
<p>This is a subjective question, but often to enforce that your model objects don't have direct dependencies to infrastructure, people often put them in a separate project. you also need to consider what other projects might use these model objects.</p> <p>Another option for splitting up functionality into separate deployable units (assemblies) is so that teams can function more independently. Separate projects based on frequency of deployment and team autonomy.</p> <p>Lastly I've seen some projects where the model objects were invoked remotely (like with .NET remoting) and served up on an application server separate from the web server. I really don't recommend this approach, but it's an option.</p> <p>If you don't plan on reusing them, and you're cognizant of the fact that placing them in the same assembly <em>allows</em> you to create cross dependencies with anything else defined in that project, but you're smart enough not to do it, you can place them all in the same project.</p> <p>That said, 99% of the time I have these projects:</p> <ul> <li>UI</li> <li>Core</li> <li>Persistence</li> <li>Tests</li> </ul> <p>But you still have to take your project needs into account.</p>
<p>My solutions have 3 (non-test) projects </p> <ol> <li>UI - obvious</li> <li>Core - all domain objects and business logic</li> <li>Data Access - Repository pattern for populating/saving Model objects</li> </ol>
37,519
<p>So in my simple learning website, I use the built in ASP.NET authentication system. </p> <p>I am adding now a user table to save stuff like his zip, DOB etc. My question is:</p> <ol> <li>In the new table, should the key be the user name (the string) or the user ID which is that GUID looking number they use in the <code>asp_ tables</code>. </li> <li>If the best practice is to use that ugly guid, does anyone know how to get it? it seems to not be accessible as easily as the name (<code>System.Web.HttpContext.Current.User.Identity.Name</code>)</li> <li>If you suggest I use neither (not the guid nor the userName fields provided by ASP.NET authentication) then how do I do it with ASP.NET authentication? One option I like is to use the email address of the user as login, but how to I make ASP.NET authentication system use an email address instead of a user name? (or there is nothing to do there, it is just me deciding I "know" userName is actually an email address?</li> </ol> <p>Please note:</p> <ul> <li>I am not asking on how get a GUID in .NET, I am just referring to the userID column in the <code>asp_ tables</code> as guid.</li> <li>The user name is unique in ASP.NET authentication.</li> </ul>
<p>You should use some unique ID, either the GUID you mention or some other auto generated key. However, this number should never be visible to the user.</p> <p>A huge benefit of this is that all your code can work on the user ID, but the user's name is not really tied to it. Then, the user can change their name (which I've found useful on sites). This is especially useful if you use email address as the user's login... which is very convenient for users (then they don't have to remember 20 IDs in case their common user ID is a popular one).</p>
<p>I agree with Mike Stone. I would also suggest only using a GUID in the event you are going to be tracking an enormous amount of data. Otherwise, a simple auto incrementing integer (Id) column will suffice.</p> <p>If you do need the GUID, .NET is lovely enough that you can get one by a simple...</p> <pre><code>Dim guidProduct As Guid = Guid.NewGuid() </code></pre> <p>or</p> <pre><code>Guid guidProduct = Guid.NewGuid(); </code></pre>
2,689
<p>I've created a Visual Basic WPF Application project that contains Toy.edmx, an ADO.NET Entity Data Model generated from a database called Toy.</p> <p>Its <em>Window1.xaml.vb</em> file looks like this:</p> <pre> 1 Class Window1 2 3 Private Sub Window1_Loaded( _ 4 ByVal sender As System.Object, _ 5 ByVal e As System.Windows.RoutedEventArgs) _ 6 Handles MyBase.Loaded 7 8 Dim dc As New ToyEntities1 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Select c).First.FirstName 11 12 End Sub 13 14 End Class </pre> <p>That runs just fine.</p> <p>But, if I add the file <em>Client.vb</em>...</p> <pre> 1 Partial Public Class Client 2 Function IsWashington() As Boolean 3 Return Me.LastName = "Washington" 4 End Function 5 End Class </pre> <p>...and add a WHERE clause to my <em>Window1.xaml.vb</em> query...</p> <pre> 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Where c.IsWashington _ 11 Select c).First.FirstName </pre> <p>...then I get this NotSupportedException:</p> <blockquote> <p>LINQ to Entities does not recognize the method 'Boolean IsWashington()' method, and this method cannot be translated into a store expression.</p> </blockquote> <p>How do I extend ADO.NET Entity Framework objects with partial classes?</p>
<p>The problem is that you're writing code, and expecting the Entity Framework to translate that into SQL... it can't do that. Just like LINQ to SQL can't do that.</p> <p>Imagine if your property read a file from the "C:\" drive... how do you think it would handle that? - not possible.</p>
<p>What type is Client class?</p> <p>You might need to add namespace (same as that in which Client "Entity classs" is defined) to the file containing "IsWashington".</p>
32,521
<p>At work one of our target platforms is a resource constrained mini-server running Linux (kernel 2.6.13, custom distribution based on an old Fedora Core). The application is written in Java (Sun JDK 1.6_04). The Linux OOM killer is configured to kill processes when memory usage exceeds 160MB. Even during high load our application never go over 120MB and together with some other native processes that are active we stay well within the OOM limit.</p> <p>However, it turns out that the Java Runtime.getRuntime().exec() method, the canonical way to execute external processes from Java, has a <a href="http://developers.sun.com/solaris/articles/subprocess/subprocess.html" rel="noreferrer">particularly unfortunate implementation on Linux</a> that causes spawned child processes to (temporarily) require the same amount of memory as the parent process since the address space is copied. The net result is that our application gets killed by the OOM killer as soon as we do Runtime.getRuntime().exec().</p> <p>We currently work around this by having a separate native program do all external command execution and we communicate with that program over a socket. This is less than optimal.</p> <p>After <a href="http://aggregat4.net/2008/06/java-runtimeexec-dangerous-on-linux/" rel="noreferrer">posting about this problem online</a> I got some feedback indicating that this should not occur on "newer" versions of Linux since they implement the posix fork() method using copy-on-write, presumably meaning it will only copy pages that it needs to modify when it is required instead of the entire address space immediately.</p> <p>My questions are:</p> <ul> <li>Is this true?</li> <li>Is this something in the kernel, the libc implementation or somewhere else entirely?</li> <li>From what version of the kernel/libc/whatever is copy-on-write for fork() available?</li> </ul>
<p>This is pretty much the way *nix (and linux) have worked since the dawn of time(or atleat the dawn of mmus). </p> <p>To create a new process on *nixes you call fork(). fork() creates a copy of the calling process with all its memory mappings, file descriptors, etc. The memory mappings are done copy-on-write so (in optimal cases) no memory is actually copied, only the mappings. A following exec() call replaces the current memory mapping with that of the new executable. So, fork()/exec() is the way you create a new process and that's what the JVM uses.</p> <p>The caveat is with huge processes on a busy system, the parent might continue to run for a little while before the child exec()'s causing a huge amount of memory to be copied cause of the copy-on-write. In VMs , memory can be moved around a lot to facilitate a garbage collector which produces even more copying.</p> <p>The "workaround" is to do what you've already done, create an external lightweight process that takes care of spawning new processes - or use a more lightweight approach than fork/exec to spawn processes (Which linux does not have - and would anyway require a change in the jvm itself). Posix specifies the posix_spawn() function, which in theory can be implemented without copying the memory mapping of the calling process - but on linux it isn't.</p>
<p>1: Yes. 2: This is divided into two steps: Any system call like fork() is wrapped by the glibc to the kernel. The kernel part of the system-call is in kernel/fork.c 3: I don't know. But I would bet that your kernel has it.</p> <p>The OOM killer kicks in when Low memory is threatened on 32bit boxes. I've never had an issue with this, but there are ways to keep OOM at bay. This problem could be some OOM configuration issue.</p> <p>Since you are using a Java application, you should consider moving to 64bit Linux. That should definitely fix it. Most 32bit apps can run on a 64bit kernel with no issues as long as relevant libraries are installed. </p> <p>You could also try the PAE kernel for 32 bit fedora.</p>
25,764
<p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
<p>It's not possible to build an entire page using just <code>genshi.builder.tag</code> -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.</p> <p><code>genshi.builder.tag</code> is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.</p> <p>See documentation for:</p> <ul> <li><a href="http://genshi.edgewall.org/wiki/Documentation/0.5.x/templates.html" rel="noreferrer">Creating and using templates</a></li> <li><a href="http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html" rel="noreferrer">The XML-based template language</a></li> <li><a href="http://genshi.edgewall.org/wiki/ApiDocs/0.5.x/genshi.builder" rel="noreferrer"><code>genshi.builder</code> API docs</a></li> </ul> <p>If you really want to generate a full document using only <code>builder.tag</code>, this (completely untested) code could be a good starting point:</p> <pre><code>from itertools import chain from genshi.core import DOCTYPE, Stream from genshi.output import DocType from genshi.builder import tag as t # Build the page using `genshi.builder.tag` page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text"))) # Convert the page element into a stream stream = page.generate () # Chain the page stream with a stream containing only an HTML4 doctype declaration stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream)) # Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc) text = stream.render ('html') </code></pre> <p>The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.</p>
<p>Genshi.builder is for "programmatically generating markup streams"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.</p> <p>You can, however do the following:</p> <pre><code>&gt;&gt;&gt; import genshi.output &gt;&gt;&gt; genshi.output.DocType('html') ('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd') </code></pre> <p>See other Doctypes here: <a href="http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType" rel="nofollow noreferrer">http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType</a></p> <pre><code>[1] genshi.builder.__doc__ </code></pre>
13,762
<p>I'm doing some profiling on a 1.1 app and have identified a problem. It seems that this function is taking forever to load on a certain page:</p> <p>ParserCacheItem System.Web.UI.TemplateControlParser.CompileAndGetParserCacheItem(String, String, HttpContext)</p> <p>I've searched around with no luck about what this does. Does anyone know what this function is doing? If I knew then maybe it would shed some light on the situation.</p> <p>Thanks!?</p>
<p>Its really a process of elimination.</p> <p>I've had similar problems where it seemed where I was the only one that had encounted a particular issue.</p> <p>By breaking my page down I found the control that was causing the timeout/error and did some more specific searches around it.</p> <p>I then found that the error actually had nothing to do with the symptoms I was experiencing, it was being masked by other issues.</p> <p>It is an investment in time but you might find that there's some control or part of your page thats timing out for some completely unobvious reason and isn't being reported in anyway. You did hint that page was complex.</p>
<p>What does the page consist of?</p> <p>Have you tried:</p> <ul> <li>removing all elements from the page and running the profiler again and seeing if the same error occurs, if it doesn't add each element back to narrow down what was causing it</li> <li>are all the namespace references correct for the .aspx?</li> <li>have you tried running the app on another box thats running IIS to see if configuration might be the issue?</li> </ul>
19,945
<p>I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first?</p> <p>Is there some kind of hash function that can take identical input, but in any order, and still produce the same result?</p>
<p>The easiest way would seem to be to hash each line on the way in, storing the hash and the original data, and then compare each new hash with your collection of existing hashes. If you get a positive, you could compare the actual data, to make sure it's not a false positive - though this would be extremely rare, you could go with a quicker hash algorithm, like MD5 or CRC (instead of something like SHA, which is slower but less likely to collide), just so it's quick, and then compare the actual data when you get a hit.</p>
<p>So you have input like</p> <pre><code>A B C D D E F G C B A D </code></pre> <p>and you need to detect that the first and third lines are identical?</p>
8,972
<p>I could do this in C#..</p> <pre><code>int number = 2; string str = "Hello " + number + " world"; </code></pre> <p>..and str ends up as "Hello 2 world".</p> <p>In VB.NET i could do this..</p> <pre><code>Dim number As Integer = 2 Dim str As String = "Hello " + number + " world" </code></pre> <p>..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."</p> <p>I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?</p>
<p>In VB I believe the string concatenation operator is &amp; rather than + so try this:</p> <pre><code>Dim number As Integer = 2 Dim str As String = "Hello " &amp; number &amp; " world" </code></pre> <p>Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that <code>System.String</code> doesn't define an addition operator - it's all hidden in the compiler by calls to <code>String.Concat</code>. (This allows much more efficient concatenation of multiple strings.)</p>
<p>The VB plus (+) operator is ambiguous.</p> <p>If you don't have Option Explicit on, if my memory serves me right, it is possible to do this:</p> <pre><code>Dim str = 1 + "2" </code></pre> <p>and gets str as integer = 3.</p> <p>If you explicitly want a string concatenation, use the ampersand operator</p> <pre><code>Dim str = "Hello " &amp; number &amp; " world" </code></pre> <p>And it'll happily convert number to string for you.</p> <p>I think this behavior is left in for backward compatibility.</p> <p>When you program in VB, always use an ampersand to concatenate strings.</p>
34,147
<p>I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:</p> <blockquote> <p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**</p> <p>at x.Foo.FooGO()</p> <p>at x.Foo.Foo2(String groupName_) in Foo.cs:line 123</p> <p>at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**</p> <p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p> </blockquote> <p>I look in my references, and I only have a reference to <code>Utility version 1.2.0.203</code> (the other one is old).</p> <p>Any suggestions on how I figure out what is trying to reference this old version of this DLL file?</p> <p>Besides, I don't think I even have this old assembly on my hard drive. Is there any tool to search for this old versioned assembly?</p>
<p>The .NET Assembly loader:</p> <ul> <li>is unable to find 1.2.0.203</li> <li>but did find a 1.2.0.200</li> </ul> <p>This assembly does not match what was requested and therefore you get this error.</p> <p>In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application path.</p> <p>run below command to add the assembly dll file to GAC:</p> <pre class="lang-bash prettyprint-override"><code>gacutil /i &quot;path/to/my.dll&quot; </code></pre> <p>Also see <a href="https://learn.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference" rel="noreferrer">https://learn.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference</a>.</p>
<p>Try adding whatever's missing to the global assembly cache.</p>
26,427
<p>I am creating an SQL view for a file that strips out the spaces in a particular field. My question is if there is a why to set a key on that new view so a person can still CHAIN the file. We are on V5R3.</p>
<p>Okay found the answer at <a href="http://archive.midrange.com/midrange-l/200809/msg01062.html" rel="nofollow noreferrer">http://archive.midrange.com/midrange-l/200809/msg01062.html</a>.</p> <p>It is not possible at V5R3. Supposedly at V6R1 this is possible.</p>
<p>Could you accomplish the same thing using a logical file or with an <code>OPNQRYF</code> statement? Both of those allow you to set key fields and may be able to strip out the spaces in a file.</p>
14,815
<p>Could some one point to articles / books on how to create good flow chart diagrams?</p>
<p><strong>BoUML-it's free!</strong></p> <p>I've used this open source tool for the last 6 months at work to create UML diagrams: bouml.free.fr/ </p> <p>I've used it on both a Macbook running OS X, as well as Ubuntu Linux on a desktop, both with success. It also does codegen (although I haven't used this feature myself). If you create a diagram from within BoUML, you can right click ->Tools->HTML etc,etc., and it and actually generate the diagram -- this will create a whole tree of html, css, etc., and include a .png file which you can later choose to import into a Word-like document.</p> <p>If you're new to UML, and would like to explore that route, I suggest UML Distilled by Martin Fowler as a way to quickly ramp up. I still use this as a reference when I'm putting diagrams together and I forget some syntactical detail ;) The nice thing about UML is that most programmers will understand it. If you don't want to buy a book you can, of course, Google 'UML tutorial' and get a slew of free info. </p> <p><strong>Non-UML:</strong></p> <p>You can also use open office's draw application to do some simple flow charting. It has some nice non-uml shapes, so if you're not trying to be 'strict' in the sense of conforming to UML, and just want a simple flow chart, that may be a good choice.</p>
<p>Tutorial <a href="http://www.nos.org/htm/basic2.htm" rel="nofollow noreferrer">here</a>.</p> <p>Also get a copy of Microsoft <a href="http://office.microsoft.com/en-gb/visio/default.aspx" rel="nofollow noreferrer">Visio</a>.</p>
37,547
<p>I'm roughing a layout together and doing some browser testing. Never came across this issue before, check out the contact form in the footer of this page</p> <p><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer"><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer">http://staging.terrilynn.com/fundraising/</a></a></p> <p>There is a div with a width of 298px floated to the right that comes first in the source order. It is followed by several other divs, each with their child form elements floated left.</p> <p>The div's that should appear to the left of right-floated message div are disappearing.</p> <p>Page displays correctly in firefox. Any help would be appreciated.</p> <pre><code>&lt;div id='footer-contact-form'&gt; &lt;h1&gt;Request Information &lt;span class='note'&gt;(all fields required)&lt;/span&gt;&lt;/h1&gt; &lt;form class="monkForm" method="post" action="http://my.ekklesia360.com/FormBuilder/handleSubmit.php" id="footer-info-request"&gt; &lt;fieldset&gt; &lt;legend&gt;Footer Info Request&lt;/legend&gt; &lt;div class="textarea required" id="w2376"&gt; &lt;p class="data"&gt; &lt;label for="area_2376"&gt;Message&lt;/label&gt; &lt;textarea id="area_2376" name="e_2376" rows="5" cols="20"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2377"&gt; &lt;p class="data"&gt; &lt;label for="text_2377"&gt;Name&lt;/label&gt; &lt;input id="text_2377" type="text" name="e_2377" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2378"&gt; &lt;p class="data"&gt; &lt;label for="text_2378"&gt;Phone&lt;/label&gt; &lt;input id="text_2378" type="text" name="e_2378" value="" /&gt; &lt;/p&gt;&lt;/div&gt; &lt;div class="text" id="w2379"&gt; &lt;p class="data"&gt; &lt;label for="text_2379"&gt;Email&lt;/label&gt; &lt;input id="text_2379" type="text" name="e_2379" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;p id="formsubmit"&gt;&lt;input type="submit" name="submit" value="Send" /&gt;&lt;/p&gt; &lt;input type="hidden" name="token" value="8143f99c1d01b4d1207dbe7860e5586d" /&gt; &lt;input type="hidden" name="SITEID" value="2185" /&gt; &lt;input type="hidden" name="cpBID" value="367780" /&gt; &lt;input type="hidden" name="formslug" value="footer-info-request" /&gt; &lt;input type="hidden" name="CMSCODE" value="EKK" /&gt; &lt;input type="hidden" name="fkey" value="" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- #footer-contact-form --&gt; </code></pre>
<p>I guess I found the problem:</p> <p>screen.css (line 382)</p> <pre><code>#footer-contact-form div { margin:0 300px 10px 0; overflow:hidden; } </code></pre> <p>"overflow:hidden" causes the problem.</p>
<p>Have you tried not floating the <code>&lt;p&gt;</code> elements to the left? Why are you actually doing this? It isn't required in the current layout.</p>
23,299
<p>So I'm looking for a pattern like this:</p> <blockquote> <p>size='0x0'</p> </blockquote> <p>In a log file, but I'm only interested in large sizes (4 digits or more). The following regex works great in EditPadPro (nice tool BTW)</p> <pre><code>size='0x[0-9a-fA-F]{4,} </code></pre> <p>But the same RegEx does not work in awk - seems like the repetition <code>{4,}</code> is messing it up. Same with WinGrep - any idea from the RegEx gurus? Thanks!</p>
<p>You can in fact use awk, with a caveat.</p> <p>As mentioned on the following page, you need a special command-line option (--re-interval) to make it work out, since the interval expression (the {4,}) is not in the standard:</p> <p><a href="http://kansai.anesth.or.jp/gijutu/awk/gawk/gawk_28.html" rel="noreferrer">http://kansai.anesth.or.jp/gijutu/awk/gawk/gawk_28.html</a></p> <p>So in the end, you'll want something that looks like:</p> <pre><code>awk --re-interval "/size='0x[0-9a-fA-F]{4,}'/" thefile </code></pre> <p>This will print out the lines that match.</p>
<p>Don't forget the last apostrophe.</p> <pre><code>' </code></pre>
33,911
<p>Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:</p> <pre><code>ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. </code></pre> <p>At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?</p> <hr> <p>EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.</p> <hr> <p>EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.</p> <hr> <p>EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.</p> <p>Any help would be appreciated!</p>
<p>(this is what finally got everything to work for me)</p> <p>Make sure EVERY socket that the socket in A connects to has </p> <pre><code>socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true); </code></pre> <p>set upon being initiated. </p>
<p>you can't rely on object being garbage collected in C# (i assume you're using c#, based on tagging) if it holds resources like being bound to the network resource like in your example, or holding some other kind of stream, a file stream would be a common example.</p> <p>you have to assure to release the resources that the object is holding, so that it can be garbage collected. otherwise it won't be garbage collected, but remain living somewhere in the memory. your pseudocode example doesn't provide that you're doing the resources releasing, you just state that the object gets (should get) garbage collected.</p>
7,078
<p>I've just changed the motherboard on my Ender 3 Pro with a MKS GEN_L v1.0 and flashed the latest Marlin version on it.</p> <p>I've calibrated my bed manually using the default XY and Z auto home commands on OctoPrint and a piece of paper.</p> <p>I'm happy with the calibration, however whenever I launch a print the Z axis moves up from the calibrated position by about 4 mm and starts extruding.</p> <p>I've checked my Z endstop status with <code>M119</code> and it's triggered at the right calibrated position.</p> <p>How can I correct this?</p>
<p>I've actually found what the issue was. It turns out that my Z steps were way out of whack (i.e. 4000 steps/mm instead of 400). Apparently, that's the default value in GitHub for version 2.0 of Marlin. Not sure if that's a typo or a valid value, anyhow setting it to 400 fixed it.</p>
<p>If you are already sure that homing is performed correctly and in valid position, then there are few reasons why printer may start printing in unexpected position.</p> <p>Do the following checks to narrow down the actual one:</p> <ul> <li><p><strong>steps/mm</strong>: use <a href="https://marlinfw.org/docs/gcode/M503.html" rel="nofollow noreferrer"><code>M503</code></a> (or <a href="https://marlinfw.org/docs/gcode/M092.html" rel="nofollow noreferrer"><code>M92</code></a> without parameters) to check if currently configured steps/mm match <a href="https://blog.prusaprinters.org/calculator_3416/#steppermotors" rel="nofollow noreferrer">your hardware setup</a> for each axis</p> </li> <li><p><strong>offsets:</strong> use <a href="https://marlinfw.org/docs/gcode/M503.html" rel="nofollow noreferrer"><code>M503</code></a> (or <a href="https://marlinfw.org/docs/gcode/M206.html" rel="nofollow noreferrer"><code>M206</code></a> without parameters) to check that there are no offsets configured</p> </li> <li><p><strong>backoff:</strong> look in <em>Configuration_adv.h</em> for following line:</p> <pre><code>//#define HOMING_BACKOFF_POST_MM { 2, 2, 2 } // (mm) Backoff from endstops after homing </code></pre> <p>(Having the backoff set is nothing wrong, actually. But be sure to also check final positioning in the generated file.)</p> </li> <li><p><strong>slicer's Start G-code:</strong> review slicer configuration, if there is nothing suspicious injected to the print file, which could temporarily overrid printer setup - esepecially <a href="https://marlinfw.org/docs/gcode/M428.html" rel="nofollow noreferrer">M428</a>, <a href="https://marlinfw.org/docs/gcode/M206.html" rel="nofollow noreferrer">M206</a>, <a href="https://marlinfw.org/docs/gcode/G092.html" rel="nofollow noreferrer">G92</a> <em>(set position is normal for E in relative extrusion mode, but suspicious for X,Y,Z)</em></p> </li> <li><p><strong>generated file:</strong> review initial part of generated G-Code file, if there are any similar surprises, and if on initial layer section there is expected move to valid Z position before extrusion is made</p> </li> </ul>
1,851
<p>My account is in the securityadmin role and I cannot grant myself sysadmin permission. I wish to gain access to a database so I can add my account to a particular role within it. <br /> As I don't yet have access to the database I can't use the UI.</p> <p>Does anyone know if this is possible and what SQL commands will achieve this in SQL Server 2005? <br />Thanks!</p>
<p>There are two securityadmin roles at play here.</p> <p>in this case db_securityadmin (database role) won't be much good to you, membership of this role is good for adding users to custom database roles (not the built-in db_* roles)</p> <p>Books Online is a bit misleading on this.</p> <p>securityadmin (server role) will allow you to do things like reset passwords but you will prolly need sysadmin to grant your user account into a database.</p> <p>The other thing is if you are able to log into the machine running SQL Server with an account in the Administrators group you will be mapped to sysadmin when running Management Studio using Trusted Authentication.</p> <p>Hope this helps</p>
<p>The <strong>sysadmin role</strong>, as the name implies, can do anything within SQL Server. It has complete rights over the SQL Server. It is the only role that can add others to the sysadmin role. There isn’t anything within SQL Server a sysadmin role member can’t do.</p> <p>You could use the system stored procedure <strong>add_srvrolemember</strong> to assign users to this role.</p> <p><strong>Example:</strong></p> <pre><code>EXEC sp_addsrvrolemember 'BUILTIN\Administrators', 'sysadmin' </code></pre>
30,062
<p>I have a CommonUtils lib I have built into a dll which I file reference from several of my projects. CommonUtils depends on log4net.dll which was set as a file reference and copy-local=true when CommonUtils.dll was built. log4net.dll and CommonUtils.dll are not in GAC.</p> <p>Everything works fine in MyWorkingProject where I only have a file reference to CommonUtils.dll - log4net.dll shows up in the output directory (as it is a dependency of CommonUtils.dll but not referenced from MyWorkingProject). However if I create a new project to add some unittests: MyWorkingProjectTest and project reference MyWorkingProject and then file reference CommonUtils.dll again here (I want to use some of the CommonUtils) then upon building log4net.dll which is a dependency in both the project reference and in the file reference as well does not get copied to the output directory.</p> <p>Can anyone clarify what is happening here? Does the compiler not know which of the log4net.dll files it should grab? Is there something I am doing wrong here? Should I do this in some other way for the log4net.dll to get copied explicitly? Does it make any sense that I have to explicitly reference log4net does it?</p>
<p>This is by design. You need to think about the implications that automatic inheritance of references would cause. While you can logically see what the references should be, there is no such delineation to the compiler. You could, theoretically, end up reproducing the Framework and a good part of your OS if it walked the entire dependency tree.</p> <p>It definitely is a pain, and I agree with and understand your frustration, but I assume that Microsoft was not able to find a logical way to do this otherwise.</p>
<p>When I've had a similar situation in the past, I received a compiler warning within Visual Studio telling me that I needed to add a reference to the dependent library.</p> <p>Are you receiving such a warning when you compile? If so, follow the advice it gives and you should find Log4net copied to your output directory.</p>
49,013
<p>I have a form that contains a bunch of checkboxes. Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that.</p> <p>So I might have: Red Orange X Yellow Blue X Green</p> <p>And I'd like my textfield to end up with the content "Yellow, Green" . </p> <p>This doesn't seem too complicated, but I am totally out of my league. I already use jQuery for a few other things so I have the framework ready, if that makes it easer.</p> <p>Thanks for any advice --</p>
<p>Just use this code:</p> <pre><code>$(function(){ $('#YourFormID').bind('submit',function(){ var serializedCheckboxes = ''; $("input[type=checkbox]").each(function() { if($(this).attr("checked")) { serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value"); } }); $("input[name=allchecks]").attr("value", serializedCheckboxes); }); }); </code></pre> <p>It starts when page is loaded and bind to "submit" event of your form correct function</p>
<p>First hack at it (without testing):</p> <pre><code>var serializedCheckboxes = ''; $("input type='checkbox'").each(function() { if($(this).attr("checked")) { serializedCheckboxes += $(this).attr("value") + ','; } }); $("input name='allchecks').attr("value", serializedCheckboxes); </code></pre>
37,132
<p>Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use <em>exceptions</em> for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations.</p> <p>So I do a trick like this:</p> <pre><code>do { bool isGood = true; .... some code if(!isGood) break; .... some more code if(!isGood) break; .... some more code } while(false); ..... some other code, which has to be executed. </code></pre> <p>I use a "fake" loop which will run once, and I can abort it by <em>break</em> or <em>continue</em>.</p> <p>Some of my colleagues did not like that, and they called it "bad practice". I personally find that approach pretty slick. But what do you think?</p>
<p>Bad practice, it depends.</p> <p>What I see in this code is a very creative way to write &quot;goto&quot; with less sulphur-smelling keywords.</p> <p>There are multiple alternatives to this code, which can or can not be better, depending on the situation.</p> <h2>Your do/while solution</h2> <p>Your solution is interesting if you have a lot of code, but will evaluate the &quot;exit&quot; of this processing at some limited points:</p> <pre><code>do { bool isError = false ; /* some code, perhaps setting isError to true */ if(isError) break ; /* some code, perhaps setting isError to true */ if(isError) break ; /* some code, perhaps setting isError to true */ } while(false) ; // some other code </code></pre> <p>The problem is that you can't easily use your &quot;if(isError) break ;&quot; is a loop, because it will only exit the inner loop, not your do/while block.</p> <p>And of course, if the failure is inside another function, the function must return some kind of error code, and your code must not forget to interpret the error code correctly.</p> <p>I won't discuss alternatives using ifs or even nested ifs because, after some thinking, I find them inferior solutions than your own for your problem.</p> <h2>Calling a goto a... goto</h2> <p>Perhaps you should put clearly on the table the fact you're using a goto, and document the reasons you choose this solution over another.</p> <p>At least, it will show something could be wrong with the code, and prompt reviewers to validate or invalidate your solution.</p> <p>You must still open a block, and instead of breaking, use a goto.</p> <pre><code>{ // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. while(/* etc.*/) { // etc. for(/* etc.*/) { // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. } // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. } // etc. } MY_EXIT: // some other code </code></pre> <p>This way, as you exit the block through the goto, there is no way for you to bypass some object constructor with the goto (which is forbidden by C++).</p> <p>This problem solves the process exiting from nested loops problem (and using goto to exit nested loops is an example given by B. Stroustrup as a valid use of goto), but it won't solve the fact some functions calls could fail and be ignored (because someone failed to test correctly their return code, if any).</p> <p>Of course, now, you can exit your process from multiple points, from multiple loop nesting depth, so if it is a problem...</p> <h2>try/catch</h2> <p>If the code is not supposed to fail (so, failure is exceptional), or even if the code structure can fail, but is overly complex to exit, then the following approach could be clearer:</p> <pre><code>try { // All your code // You can throw the moment something fails // Note that you can call functions, use reccursion, // have multiple loops, etc. it won't change // anything: If you want to exit the process, // then throw a MyExitProcessException exception. if(/* etc. */) { // etc. while(/* etc.*/) { // etc. for(/* etc.*/) { // etc. if(/*some failure condition*/) throw MyExitProcessException() ; // etc. } // etc. callSomeFunction() ; // the function will throw if the condition is met // so no need to test a return code // etc. } // etc. } // etc. } catch(const MyExitProcessException &amp; e) { // To avoid catching other exceptions, you should // define a &quot;MyExitProcessException&quot; exception } // some other code </code></pre> <p>If some condition in the code above, or inside some functions called by the code above, is not met, then throw an exception.</p> <p>This is somewhat weightier than your do/while solution, but has the same advantages, and can even abort the processing from inside loops or from inside called functions.</p> <h2>Discussion</h2> <p>Your need seems to come from the fact you can have a complex process to execute (code, functions calls, loops, etc.), but you want to interrupt it over some condition (probably either failure, or because it succeeded sooner than excepted). If you can rewrite it in a different way, you should do it. But perhaps, there is no other way.</p> <p>Let's assume that.</p> <p><strong>If you can code it with a try/catch, do it</strong>: To interrupt a complex piece of code, throwing an exception is the right solution (the fact you can add failure/success info inside your exception object should not be underestimated). You will have a clearer code after that.</p> <p>Now, if you're in a speed bottleneck, resolving your problem with thrown exceptions as an exit is not the fastest way to do it.</p> <p>No one can deny your solution is a glorified goto. There won't be a goto-spaghetti code, because the do/while won't let you do that, but it is still a semantic goto. This can be the reasons some could find this code &quot;bad&quot;: They smell the goto without finding its keyword clearly.</p> <p>In this case (and in this performance, profiled-verified) case only, your solution seems Ok, and better than the alternative using if), but of lesser quality (IMHO) than the goto solution which at least, doesn't hide itself behind a false loop.</p> <h2>Conclusion</h2> <p>As far as I am concerned, I find your solution creative, but I would stick to the thrown exception solution.</p> <p>So, in order of preference:</p> <ol> <li>Use try/catch</li> <li>Use goto</li> <li>Use your do/while loop</li> <li>Use ifs/nested ifs</li> </ol>
<p>I think I'd have to agree with your colleagues just because of readability, it's not clear atfirst glance what you are trying to accomplish with this code.</p> <p>Why not just use </p> <pre><code>if(isGood) { ...Execute more code } </code></pre> <p>?</p>
30,239
<p>How to enable inno-db support on installed instance of MySql?</p> <p>I have installed mysql-5.0.67-win32. 'InnoDB' is 'DISABLED' when executing 'show engines'. According to documentation MySql is compiled with support of inno-db (From doc: A value of DISABLED occurs either because the server was started with an option that disables the engine, or because not all options required to enable it were given.)</p> <p>In my.ini I commented line with 'skip-innodb'. This didn't help. All other inno-db related variables remain unchanged.</p> <p>I have performed some unusual action before I experienced described situation. I have mysql-4.0.17-win installed. I uninstall it and after this installed mysql-5.0.67-win32. In installation wizard I chose MyISAM support only (as far as I understand I disabled inno-db support in such way. When I tried to reinstall with support of inno-db I had problems of using my previous database 'mysql' with account information).</p> <p>MySQL documentation says that I should use mysqldump to export data and after this to import exported data in process of upgrade. I tried to do so, but when importing data I obtained message about syntax error (I think that it is connected with some incompatibilities of 4-th and 5-th version of mysql)</p>
<p>Should be enabled by default. There are some situations where wrong permissions on the MySQL lib folder cause InnoDB to bark. Check your MySQL error log for permission errors.</p>
<p>have you checked the startup parameters? maybe the shell script or batch file that you use to start up the server disable the engine on the command line.. IIRC command line flags trumps the .ini settings. </p>
13,718
<p>PostgreSQL allows the creation of 'Partial Indexes' which are basically indexes with conditional predicates. <a href="http://www.postgresql.org/docs/8.2/static/indexes-partial.html" rel="nofollow noreferrer">http://www.postgresql.org/docs/8.2/static/indexes-partial.html</a> </p> <p>While testing, I found that they are performing very well for a case where the query is accessing only certain 12 rows in a table with 120k rows. </p> <p>But before we deploy this, are there any disadvantages or caveats we should be aware of?</p>
<p>Pro:</p> <blockquote> <p>This reduces the size of the index, which will speed up queries that do use the index. It will also speed up many table update operations because the index does not need to be updated in all cases</p> </blockquote> <p>Con:</p> <p>Since this no longer is a real index, if you do full join or filtering on values not covered by the index, the performance will degrade as your table size grows.</p>
<p>Pro:</p> <blockquote> <p>This reduces the size of the index, which will speed up queries that do use the index. It will also speed up many table update operations because the index does not need to be updated in all cases</p> </blockquote> <p>Con:</p> <p>Since this no longer is a real index, if you do full join or filtering on values not covered by the index, the performance will degrade as your table size grows.</p>
35,923
<p>You know, sometimes it happens that you run out of ideas for your next hobbistic programming project, and then... you ask for help on StackOverflow :)</p> <p>So: what would it be your suggestion for a rocking web application (it may be implemented using <a href="http://code.google.com/appengine/" rel="nofollow noreferrer">Google App Engine</a> and it may use the new fresh <a href="http://www.google.com/friendconnect/" rel="nofollow noreferrer">Google Friend Connect</a> APIs) to develop in 20 or 30 days of spare time?</p> <p>Any constructive and creative suggestion is warmly appreciated. <br/>Thanks</p>
<p>Why not join an existing Open Source project using those technologies? In my opinion it is a great way to learn new stuff and picking up good habits :-)</p>
<p>An application tracking allergies (symptoms, counter indicators, food lists and places where you can actually buy such food).</p> <p>The tricky part would be to allow users to filter the data without exposing their own health to the world. I was thinking about a client side CSS file which hides the part of the site which is not relevant plus a strict policy not to track page access and/or IP addresses.</p>
45,314
<p>I am using SQL Server 2005 CE framework 3.5 and attempting to use merge replication between my hand held and my SQL Server. When I run the code to synchronise it just seems to sit forever, and when I put a breakpoint in my code it never gets past the call to Synchronize().</p> <p>If I look at the replication monitor in sql server, it gets to the point where it says the subscription is no longer synchronising and doesn't show any errors. Therefore I am assuming this to mean the synchronisation is complete.</p> <p><a href="http://server/virtualdirectory/sqlcesa35.dll?diag" rel="nofollow noreferrer">http://server/virtualdirectory/sqlcesa35.dll?diag</a> does not report any issues.</p> <p>This is my first attempt at any handheld development, so I may have done something daft. However, SQL Server seems to be reporting a successful synchronisation.</p> <p>Any help would be greatly appreciated as I have spent ages on this ! </p> <p>Here is my code.</p> <pre><code>const string DatabasePath = @"SD Card\mydb.sdf"; var repl = new SqlCeReplication { ConnectionManager = true, InternetUrl = @"http://server/virtualdirectory/sqlcesa35.dll", Publisher = @"servername", PublisherDatabase = @"databasename", PublisherSecurityMode = SecurityType.DBAuthentication, PublisherLogin = @"username", PublisherPassword = @"password", Publication = @"publicationname", Subscriber = @"PPC", SubscriberConnectionString = "Data Source=" + DatabasePath }; try { Cursor.Current = Cursors.WaitCursor; if (!File.Exists(DatabasePath)) { repl.AddSubscription(AddOption.CreateDatabase); } repl.Synchronize(); MessageBox.Show("Successfully synchronised"); } catch (SqlCeException e) { DisplaySqlCeErrors(e.Errors, e); } finally { repl.Dispose(); Cursor.Current = Cursors.Default; } </code></pre>
<p>Another thing you can do to speed up the Synchronize operation is to specify a db file path that is in your PDA's main program memory (instead of on the SD Card as in your example). You should see a speed improvement of up to 4X (meaning the Sync may take only 25% as long as it's taking now).</p> <p>If you're running out of main program memory on your PDA, you can use System.IO.File.Move() to move the file to the SD Card after the Synchronize call. This seems a bit strange, I know, but it's much faster to sync to program memory and copy to the SD card then it is to sync directly to the SD card.</p>
<p>I have since discovered that it was just taking a long time to copy the data to the physical disk. Although the sql server replication had completed, it was still copying the data to the sd card.</p> <p>I identified this by reducing the amount of tables I am replicating and I got a more immediate response (well another error but unrelated to this issue).</p> <p>Thanks anyway :)</p>
35,145
<p>Suppose I have two classes with the same interface:</p> <pre><code>interface ISomeInterface { int foo{get; set;} int bar{get; set;} } class SomeClass : ISomeInterface {} class SomeOtherClass : ISomeInterface {} </code></pre> <p>Suppose I have an instance of ISomeInterface that represents a SomeClass. Is there an easy way to copy that into a new instance of SomeOtherClass without copying each member by hand?</p> <p><strong>UPDATE:</strong> For the record, I'm <em>not</em> trying to cast the instance of SomeClass into the instance of SomeOtherClass. What I'd like to do is something like this:</p> <pre><code>ISomeInterface sc = new SomeClass() as ISomeInterface; SomeOtherClass soc = new SomeOtherClass(); soc.foo = sc.foo; soc.bar = soc.bar; </code></pre> <p>I just don't want to have to do that for each by hand as these objects have lots of properties.</p>
<p>Isn't the point of an interface to not have to do that? Are you doing something with the concrete implementation of SomeOtherClass? Instead of using the concrete implementation, use the interface and it shouldn't matter if you use SomeClass or SomeOther class.</p> <p>Other than that, the best you could do is to write some sort of a helper function (you'd still have to do it manually, or look into reflection) that copies each Property on the Interface that would look like this:</p> <pre><code> public ISomeInterface CopyValues(ISomeInterface fromSomeClass, ISomeInterface toSomeOtherClass) { //copy properties here return toSomeOtherClass; } </code></pre> <p>However, my first instinct would be to say stay away from the implementation and concentrate using your interface instead, then it won't matter what's lying underneath.</p>
<p><a href="https://stackoverflow.com/users/12950/tvanfosson">Tvanfosson</a>'s answer can be extended using a static generic method defined in the interface:</p> <pre><code>public interface IPerson { string Name { get; set; } static void CopyProperties&lt;A, B&gt;(A source, B dest) where A : IPerson where B : IPerson { foreach (var property in typeof(IPerson).GetProperties()) { property.SetValue(dest, property.GetValue(source)); } } } </code></pre> <p>Classes implementing <code>IPerson</code>:</p> <pre><code>public class Worker : IPerson { public string Name { get; set; } } public class Manager : IPerson { public string Name { get; set; } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>var worker = new Worker { Name = &quot;John&quot; }; var manager = new Manager(); IPerson.CopyProperties(worker, manager); </code></pre> <p>Alternatively, you can use the <code>new</code> constraint to create an instance of the desired type given that it implements the interface:</p> <pre><code> public interface IPerson { string Name { get; set; } static TDest ChangeType&lt;TDest, TSource&gt;(TSource source) where TSource : IPerson where TDest : IPerson, new() { var instance = new TDest(); foreach (var property in typeof(IPerson).GetProperties()) { property.SetValue(instance, property.GetValue(source)); } return instance; } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>var worker = new Worker { Name = &quot;John&quot; }; var manager = IPerson.ChangeType&lt;Manager, Worker&gt;(worker); </code></pre>
39,002
<p>I want to use the <a href="http://msdn.microsoft.com/en-us/library/system.enterpriseservices.internal.publish.gacremove(VS.80).aspx" rel="nofollow noreferrer">Publish.GacRemove</a> function to remove an assembly from GAC. However, I don't understand what path I should pass as an argument.</p> <p>Should it be a path to the original DLL (what if I removed it after installing it in the GAC?) or the path to the assembly in the GAC?</p> <p><strong>UPDATE:</strong></p> <p>I finally used <a href="http://blogs.msdn.com/junfeng/articles/229649.aspx" rel="nofollow noreferrer">these API wrappers</a>.</p>
<p>I am using the <code>GacInstall</code> to publish my assemblies, however once installed into the gac, I sometimes delete my ‘temporary’ copy of the assemblies.</p> <p>And then, if I ever wanted to uninstall the assemblies from the gac I do not have the files at the original path. This is causing a problem since I cannot seem to get the <code>GacRemove</code> method to uninstall the assemblies unless I keep the original files.</p> <p>Conclusion: Yes, you need to specify the path to the original DLL. (And try to not move/delete it later). If you delete it, try to copy the file from the GAC to your original path and you should be able to uninstall it using <code>GacRemove</code>.</p>
<p>I am not exactly sure about it but I believe GacRemove should do the same thing as gacutil /u. So, it should be the path of your DLL. However it doesn't have to be the same DLL file. Copy of the original should suffice since what counts is the uniqueID of the DLL.</p>
6,772
<p>I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after <code>32</code>.</p> <p>For example:</p> <pre><code>for(var j = 0; j &lt; 64; j++) { mask = mask &lt;&lt; 1; console.log(mask); } </code></pre> <p>This prints value from <code>0</code> to <code>1073741824</code> but then rounds of and starts printing <code>0</code>.</p>
<p>&quot;In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation.&quot; - Douglas Crockford, <a href="http://safari.oreilly.com/9780596517748/bitwise_operators" rel="noreferrer">Javascript: The Good Parts</a></p> <p>The point is that you don't really have any reason to use bitwise operators. Just multiply or divide by 2^numbits.</p> <p>Your code should be:</p> <pre><code>for(var j = 0; j &lt; 64; j++) { mask = mask * 2; console.log(mask); } </code></pre> <p>Or generally:</p> <pre><code>function lshift(num, bits) { return num * Math.pow(2,bits); } </code></pre> <p>You get the idea.</p>
<p>With <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" rel="nofollow noreferrer">BigInt</a> you can use bitwise operators, except <code>&gt;&gt;&gt;</code>.</p> <p>For example:</p> <pre class="lang-js prettyprint-override"><code>console.log(1n &lt;&lt; 32n); // 4294967296n console.log(1n &lt;&lt; 40n); // 1099511627776n console.log((1n &lt;&lt; 40n).toString(2)); // 1 00000000 00000000 00000000 00000000 00000000 </code></pre> <p>BigInt is a 64-bit signed integer.</p>
43,776
<p>How would you format/indent this piece of code?</p> <pre><code>int ID = Blahs.Add( new Blah( -1, -2, -3) ); </code></pre> <p>or</p> <pre><code>int ID = Blahs.Add( new Blah( 1,2,3,55 ) ); </code></pre> <hr /> <h3>Edit:</h3> <p>My class has lots of parameters actually, so that might effect your response.</p>
<p>I agree with Patrick McElhaney; there is no need to nest it....</p> <pre><code>Blah aBlah = new Blah( 1, 2, 3, 55 ); int ID = Blahas.Add( aBlah ); </code></pre> <p>There are a couple of small advantage here:</p> <ol> <li>You can set a break point on the second line and inspect 'aBlah'. </li> <li>Your diffs will be cleaner (changes more obvious) without nesting the statements, e.g. creating the new Blah is in an independent statement from adding it to the list.</li> </ol>
<p>int ID = Blahs.Add(new Blah(1,2,3,55)); // Numbers n such that the set of base 4 digits of n equals the set of base 6 digits of n.</p>
40,136
<p>Topic: Programmatically manipulate web browser in OS X 10.4.x+ Tiger/Leopard. Subjects: Webkit, Safari, Firefox, APIs, Applescript, Automator, Javascript, Ruby, Ruby on Rails, OS X, Tiger Goal: Collect/Read/Extract URLs from Safari into text (Ruby on Rails code) file. Note: A solution that uses FF would be very appreciated, too. I use Safari (v. 3.x, OS X 10.4.x) more and much prefer a solution that works in Safari.</p> <p>At times, I use the web browser to find/display multiple site pages that I 1) want to visit again later and 2) the URLs of which I want to group together in a text file for a) future reference and/or b) programmatically manipulate.</p> <p>For example: In today's NYT I find seven NYT articles I want to post to my del.icio.us acct. and share via email in their "printer friendly" format long after they are headlined in that day's online edition. I open each one in a browser window's tap, then Presto! their URLs automagically are wooshed into a file where a (custom) Ruby on Rails app sends the print versions' URLs to email addresses and my Del.icio.us acct.</p> <p>I figure there's a way to do the URL extracting step from the OS using Applescript or Automator. I figure there MAY be a way to do it with Javascript.</p> <p>My Question: How to read the web browser's tabs' location field and collate these strings into a text file (either within my OS or over the wire to a web app.)?</p> <p>Much appreciated.</p>
<p>For Safari, this would be pretty trivial to do with Applescript. I'd suggest starting with something like <a href="http://www.macosxhints.com/article.php?story=20060227192533174" rel="nofollow noreferrer">Bookmark all tabs</a> to get the basic tab-grabbing logic that you'll need, and maybe merge it into John Gruber's old <a href="http://daringfireball.net/2003/02/save_and_restore_safari_urls" rel="nofollow noreferrer">Save and restore Safari URLs</a> script to save the URLs as a list to a text file.</p> <p>There may be better Applescript solutions out there, too; those were just the first I found via Google, and both are pretty badly dated.</p> <p>For further help and resources pertaining to Applescript, I suggest the <a href="http://bbs.macscripter.net/" rel="nofollow noreferrer">MacScripter forums</a>.</p> <p>Good luck!</p>
<p>The most simple solution in Firefox is "Bookmark all open tabs" (in the bookmark menu). Give this "bookmark folder" a specific name. You can then go into your profile (<a href="http://support.mozilla.com/en-US/kb/Profiles" rel="nofollow noreferrer">http://support.mozilla.com/en-US/kb/Profiles</a>) and open the file "bookmarks.html" which contains all the info you want and then some.</p> <p>If you want to use a UI, check out the Taboo and the "Sitzungs-Manager" (probably Session-Manager). Both are for Firefox 3.0+</p> <p>Taboo allows you to save a tab for "later reading" (kind of like the bookmark menu but just a single click; will save a screenshot of the page, too).</p> <p>The session manager plugin allows you to save the currently open tabs and windows and restore them later.</p>
38,320
<p>I work with a bunch of sets in order to generate constrained random traffic, but I want to be able to call a Specman macro that computes the complement of a set with syntax like:</p> <pre><code>COMPLEMENT begin domain=[0..10,24..30], complementing_set=[2..3,27..30] end </code></pre> <p>and have it generate:</p> <pre><code>[0..1,4..10,24..26] </code></pre> <p>Every time I need the complement of a set I'm using fully populated lists (e.g. {0;1;2;3....} ) and then removing elements, instead of using Specman's built-in int_range_list object. And I'm also doing a lot of these set calculations at run-time instead of compile-time.</p>
<p>You can try this:</p> <pre><code>var domain: list of int = {0..10, 24..30}; var complementing_set: list of int = {2..3, 27..30}; var complement: list of int = domain.all(it in complementing set); </code></pre> <p>The <code>all</code> pseudo-method generates a sublist of the parent list of all the elements in the parent list for which the condition in the parentheses holds.</p>
<p>one more way may be to use uints, say you have a 500 possible values:</p> <pre><code>domain : uint(bits:500); complement : uint(bits:500); set : uint(bits:500) = domain &amp; ~complement; </code></pre> <p>you can later extract the indices with</p> <pre><code>set_l : list of uint = set[.]].all_indices(it==1); </code></pre> <p>depending on your domain to possible values ratio this method may be quicker to calculate</p>
14,284
<p>As kind of a follow up to <a href="https://stackoverflow.com/questions/111605/what-kind-of-prefix-do-you-use-for-member-variables">this question about prefixes</a>, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?</p>
<p>This is a completely subjective question. There is no "better" way.</p> <p>One way is:</p> <pre><code>private int _x; public get x():int { return _x; } public set x(int val):void { _x = val; } </code></pre> <p>Another is:</p> <pre><code>private int x; public get X():int { return x; } public set X(int val):void { x = val; } </code></pre> <p>Neither is the right answer. Each has style advantages and disadvantages. Pick the one you like best and apply it consistently.</p>
<p>In a case sensitive language I just use:</p> <pre><code>private int myValue; public int MyValue { get { return myValue; } } </code></pre> <p>Otherwise I would use an underscore</p> <pre><code>Private _myValue As Integer Public ReadOnly Property MyValue As Integer Get Return _myValue End Get End Property </code></pre>
20,424
<p>Is it possible to compile and run OpenGL programs from under Cygwin? If yes, how?</p>
<p>It is possible to compile and run OpenGL programs under Cygwin. I illustrate the basic steps here:</p> <ol> <li><p>I assume you know OpenGL programming. If not, get the <a href="http://www.opengl-redbook.com/" rel="noreferrer">Red Book</a> (<em>The OpenGL Programming Guide</em>). It is mandatory reading for OpenGL anyway.</p></li> <li><p>I assume you have Cygwin installed. If not, visit <a href="http://www.cygwin.com/" rel="noreferrer">cygwin.com</a> and install it.</p></li> <li><p>To compile and run OpenGL programs, you need the Cygwin package named <strong>opengl</strong>. In the Cygwin installer, it can be found under the <em>Graphics section</em>. Please install this package.</p></li> <li><p>Write a simple OpenGL program, say <em>ogl.c</em>.</p></li> <li><p>Compile the program using the flags <strong>-lglut32 -lglu32 -lopengl32</strong>. (This links your program with the GLUT, GLU and OpenGL libraries. An OpenGL program might typically use functions from all the 3 of them.) For example:</p> <blockquote> <p>$ gcc ogl.c -lglut32 -lglu32 -lopengl32</p> </blockquote></li> <li><p>Run the program. It's as simple as that!</p></li> </ol>
<p>I remember doing this once with some success, a few years ago, basically trying to cross compile a small Linux OpenGL C++ program. I do recall problems with Windows OpenGL drivers being behind the times (due to MS's focus on DirectX). I had NVidia OpenGL and DirectX drivers installed on my Windows system, but cygwin/g++ seemed to want to only use the Microsoft OpenGL DLLs, many years old, which do not have the latest support for all the ARB extensions, like shader programs, etc. YMMV.</p>
3,510
<p>i.e. as I compose my test suites to include other suites as well as test cases, is there a global count of how many tests the TestRunner has executed, will be executing?</p> <p>Any way I can progammatically access that count?</p>
<p>not sure about how many it has executed, but couldn't you check how many total tests using <code>self.methods.grep(/test_/)</code>?</p>
<p><code>Test::Unit::TestSuite#size</code> may be helpful.</p> <p><code>Test::Unit::TestCase#size</code> probably isn't, as it returns 1.</p>
33,145
<p>So I've got some scripts I've written which set up a Google map on my page. These scripts are in included in the <code>&lt;head&gt;</code> of my page, and use jQuery to build the map with markers generated from a list of addresses on the page.</p> <p>However, I have some exact co-ordinate data for each address which the javascript requires to place the markers correctly. This isn't information I want to be visible on the screen to the user, so what's the "best practice" way to put that data into my document?</p>
<p>I would not reccomend using style to hide something, it will show up in browsers without (or with disabled) css suppor and look strange.</p> <p>You could store it in a javascript variable or add a form with hidden values like this (inside an unused form to be sure it validates):</p> <pre><code>&lt;form action="#" method="get" id="myHiddenValues"&gt; &lt;input type="text" name="hiddenval1" id="hiddenval1" value="1234"/&gt; &lt;input type="text" name="hiddenval2" id="hiddenval2" value="5678"/&gt; &lt;/form&gt; </code></pre> <p>wich you can read and update from javascript.</p>
<p>If the information should not be visible to the user, it should not stay in the document. The data can stay in a script region for example. However if for various reasons this is not possible, you could use a div with style="display:none" that will hide the information.</p>
44,174
<p>Given the following canvas:</p> <pre><code>&lt;Canvas&gt; &lt;Canvas.LayoutTransform&gt; &lt;ScaleTransform ScaleX="1" ScaleY="1" CenterX=".5" CenterY=".5" /&gt; &lt;/Canvas.LayoutTransform&gt; &lt;Button x:Name="scaleButton" Content="Scale Me" Canvas.Top="10" Canvas.Left="10" /&gt; &lt;Button x:Name="dontScaleButton" Content="DON'T Scale Me" Canvas.Top="10" Canvas.Left="50" /&gt; &lt;/Canvas&gt; </code></pre> <p>Is it possible to scale 1 button, but not the other when ScaleX and ScaleY changes?</p>
<p>Not in XAML. You can do this in code by building the reverse transform and applying it to the object you don't want transformed.</p> <p>If you want to go fancy, you can build a dependency property that you can attach in XAML to any object you don't want to be transformed by any parent transforms. This dependency property will take the transform of the parent, build a reverse transform and apply it to the object it's attached to.</p>
<p>You could also restructure the elements so that the elements you don't want to scale with the <code>Canvas</code> are not actually children of that <code>Canvas</code>.</p> <pre><code>&lt;Canvas&gt; &lt;Canvas&gt; &lt;Canvas.LayoutTransform&gt; &lt;ScaleTransform ScaleX="1" ScaleY="1" CenterX=".5" CenterY=".5" /&gt; &lt;/Canvas.LayoutTransform&gt; &lt;Button x:Name="scaleButton" Content="Scale Me" Canvas.Top="10" Canvas.Left="10" /&gt; &lt;/Canvas&gt; &lt;Button x:Name="dontScaleButton" Content="DON'T Scale Me" Canvas.Top="10" Canvas.Left="50" /&gt; &lt;/Canvas&gt; </code></pre>
18,647
<p>I'm looking for a Windows tool that is able to log every action (read &amp; write) that were made to a specific path inside the local Filesystem in order to debug a program (find out why it is sometimes slow and sometimes not). In theory it could work like a virus scanner that is recognizing every file that any of the running programs do read or write and logs every thing that it sees.</p>
<p>To store a photo in AD, you can use the <code>jpegPhoto</code> attribute (see <a href="http://msdn.microsoft.com/en-us/library/ms676813(VS.85).aspx" rel="nofollow noreferrer">formal description in MSDN</a>). Here is <a href="http://www.arricc.net/active-directory-photos-sharepoint.php#" rel="nofollow noreferrer">a way to do it using VBScript</a>, and here's one to <a href="http://blogs.technet.com/btrst4/archive/2004/09/07/226323.aspx" rel="nofollow noreferrer">do it using VB.NET</a>.</p> <p>I'm not sure Outlook 2007 makes use of this value (my guess is - it does not), but it's worth a try. My guess is even that Outlook does not care about the <code>jpegPhoto</code> if you put someone from the GAL to your personal address book. Anyway, this should be easy enough to test. </p> <p>If all else fails, you are stuck with either making clear that it doesn't work or building a custom form that reads the value.</p>
<p>Outlook will only display the photo from a personal contact, not the GAL or AD. Making a new form is not as option.</p> <p>I have managed to use the PersonName smart tag to add a menu option to the context menu which looks up and displays the photo in a browser. Not optimal. Anyone got other ideas?</p>
35,030
<p>Do we really need a server side architecture to create a RIA application?</p> <p>My idea is the following:</p> <ul> <li>Create a complete RIA application using only Html pages, JQuery and a full client side UI set of components (choose your poison between the large number of different components available open source and not)</li> <li>Server side I have just one or more REST like web services that returns and accepts Json serialized objects</li> </ul> <p>No more dependency on the latest trend on server side architecture (Struts, Java faces, Asp.Net, MVC or any other model that was trendy sometime ago or is trendy now), web server side will be just an interface between trasnsport (Json) and the business logic layer, with very few logic in it.</p> <p>Client side we'll have a huge JavaScript application, but with modern browsers and PCs (for speed) and modern development environment for ease of maintenance (VS2008 and other tools debug JavaScript very well) I see less a problem in code maintenance for this layer than finding the developer that know the correct server layer architecture...</p> <p>Do you have comment on this scenario?</p> <p>Ciao Massimo</p>
<p>You could as easily have asked about implementing a first-class backend getting the server side right, while avoiding the latest trendy client-side fad. And I think it would be a legitimate goal in either case. You don't mention whether this is an existing application, but if it is, then I'd say, first memeorize the Fowler Refactoring book, and then go for it.</p> <p>A lot of the churn in software is useful if you know how to properly apply what you'll need to know to accomplish your client side goals, because the same concepts (SOC, coupling-vs-cohesion, DRY, YAGNI, etc.) apply to both ends, and we increasingly have at hand useful tools for applying them (which can be accomplished more or less easily with a lot of technologies.)</p>
<p>Or don't even bother with the REST / Json part and use something like DWR to talk directly from your client side code to your server POJOs.</p>
39,791
<p>I have the following fields:</p> <ul> <li>Inventory control (16 byte record) <ul> <li>Product ID code (int – 4 bytes)</li> <li>Quantity in stock (int – 4 bytes)</li> <li>Price (double – 8 bytes)</li> </ul></li> </ul> <p>How do I create a fixed length random access file using the above lengths? I tried some examples online, but I either get an EOF exception or random address values when I try to access them.</p> <p>I tried some more examples and couldn't understand the concept very well. I'm trying a project with it and will try to explore more on it.</p> <p>Here is some example data. There might be holes in the data where <code>No. in stock</code> could be <code>23 == 023</code>.</p> <pre><code> Quantity ID. No. In Stock Price ------- -------- ------ 1001 476 $28.35 1002 240 $32.56 1003 517 $51.27 1004 284 $23.75 1005 165 $32.25 </code></pre> <p>Thanks for the help.</p>
<p>java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :)</p> <pre><code>package test; import java.io.IOException; import java.io.RandomAccessFile; public class Raf { private static class Record{ private final double price; private final int id; private final int stock; public Record(int id, int stock, double price){ this.id = id; this.stock = stock; this.price = price; } public void pack(int n, int offset, byte[] array){ array[offset + 0] = (byte)(n &amp; 0xff); array[offset + 1] = (byte)((n &gt;&gt; 8) &amp; 0xff); array[offset + 2] = (byte)((n &gt;&gt; 16) &amp; 0xff); array[offset + 3] = (byte)((n &gt;&gt; 24) &amp; 0xff); } public void pack(double n, int offset, byte[] array){ long bytes = Double.doubleToRawLongBits(n); pack((int) (bytes &amp; 0xffffffff), offset, array); pack((int) ((bytes &gt;&gt; 32) &amp; 0xffffffff), offset + 4, array); } public byte[] getBytes() { byte[] record = new byte[16]; pack(id, 0, record); pack(stock, 4, record); pack(price, 8, record); return record; } } private static final int RECORD_SIZE = 16; private static final int N_RECORDS = 1024; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { RandomAccessFile raf = new RandomAccessFile(args[0], "rw"); try{ raf.seek(RECORD_SIZE * N_RECORDS); raf.seek(0); raf.write(new Record(1001, 476, 28.35).getBytes()); raf.write(new Record(1002, 240, 32.56).getBytes()); } finally { raf.close(); } } } </code></pre>
<p>With recent Java versions, you can manage Random access files using FileChannel. SeekableByteChannel interface define methods which allow you to change the position of the pointer in the destination entity like file which the channel is connected to. FileChannel implements SeekableByteChannel allowing you to manage random access files using channels. Methods size, position, truncate allow you to read and write files randomly.</p> <p>see <a href="http://www.zoftino.com/java-random-access-files" rel="nofollow noreferrer">http://www.zoftino.com/java-random-access-files</a> for details and example.</p>
24,369
<p>When I try to run the following code (from the REPL) in Clojure:</p> <pre><code>(dotimes [i 5] (.start (Thread. (fn [] (Thread/sleep (rand 1000)) (println (format "Finished %d on %s" i (Thread/currentThread))))))) </code></pre> <p>I get the following error:</p> <pre><code>java.lang.Exception: Unable to resolve symbol: i in this context clojure.lang.Compiler$CompilerException: NO_SOURCE_FILE:6: Unable to resolve symbol: i in this context at clojure.lang.Compiler.analyze(Compiler.java:3713) </code></pre> <p>What am I doing wrong here?</p>
<p>Your code works for me using the latest SVN (1144).</p> <pre><code>user&gt; (dotimes [i 5] (.start (Thread. (fn [] (Thread/sleep (rand 1000)) (println (format "Finished %d on %s" i (Thread/currentThread))))))) Finished 0 on Thread[Thread-16,5,main] Finished 4 on Thread[Thread-20,5,main] Finished 3 on Thread[Thread-19,5,main] Finished 1 on Thread[Thread-17,5,main] Finished 2 on Thread[Thread-18,5,main] </code></pre> <p>Are you using the September 16 release? You almost have to use the SVN version of Clojure. It's changing way too fast.</p>
<p>I think you mean "Calling Java from Clojure". They are still <a href="http://clojure.org/java_interop#toc14" rel="nofollow noreferrer">fiddling with the syntax</a>.</p>
44,492
<p>I have been experimenting with WPF and rendering strict XAML markup in a web browser, also known as Loose XAML (explained <a href="http://blogs.msdn.com/tims/archive/2005/09/21/472659.aspx" rel="nofollow noreferrer">here</a> and <a href="http://michaelbraude.com/index.php?XML/Projects/XAMLXSLT/XAMLXSLT_page1.xml" rel="nofollow noreferrer">here</a>).</p> <p>It strikes me as mostly useful for displaying static content. However, it also appears possible to bind to an XML data provider. </p> <p>Loose XAML files are not compiled with an application, which creates the following limitations:</p> <ul> <li>They do not allow external assemblies</li> <li>No use of classes, code-behind (or any C#)</li> <li>No two-way databinding</li> </ul> <p>What additional limitations are there?</p> <ul> <li>I have not found a way to databind to a database provider (SQL Server)</li> <li>Is the .NET Framework required on the client machine in order to render the XAML in the browser?</li> <li>Are Search Engines able to interrogate Loose XAML to appropriately rank the pages?</li> </ul> <p>EDIT: I have attempted to bind the XML data provider to a web service (using <a href="http://developer.yahoo.com/dotnet/howto-wpf_xaml.html" rel="nofollow noreferrer">this</a> simple example) and have not been successful. These findings lead me to further research where I found that this is not supported: "The XMLDataProvider is designed to be read-only (in other words, it doesn't provide the ability to commit changes), and it isn't able to deal with XML data that may come from other sources (such as a database record, a web service message, and so on)." -Matthew MacDonald, <em>Pro WPF</em></p>
<p>At least framework 3.0 is required to view loose XAML pages in IE. You can even check for it on your site by looking for ".NET CLR 3.0" in the user agent string.</p> <p>A database connection, if it is even possible, would not be done directly in the loose XAML because of the need for procedural code to open the connection.</p>
<p>I've done a lot of work in hosting the Dynamic Language Runtime (DLR) and allowing scripts to be embedded in XAML. I'm at the point now that I feel like Loose XAML is not a second class citizen as I can handle events, write value converters, run Python/Ruby/JScript to do things like connect to SQL server.</p> <p>See my <a href="http://www.thinkbottomup.com.au/site/blog/Embedding_DLR_Scripts_in_XAML_Part_1" rel="nofollow noreferrer">blog</a> to see if this direction suits you.</p> <p>I dynamically load assemblies using an attached property - once loaded, you can reference the classes in the assembly in the usual manner.</p> <p>So, too answer the question, there are MANY limitations of Loose XAML out of the box (like not being able to route an event to an event handler), but these can be overcome with a bit of work.</p> <p>I've only used XAML/WPF for desktop apps. Hopefully someone else jumps in to answer you browser specific questions.</p> <p>I have a library that I use in commercial work for DLR hosting and embedding DLR scripts in XAML that I've been meaning to turn into a supported product. If this would be of interest to you, be sure to let me know.</p>
19,293
<p>I'm making a twitter client, and I'm evaluating the various ways of protecting the user's login information.</p> <p>IMPORTANT: I need to protect the user's data from other other applications. For example imagine what happens if a bot starts going around stealing Twhirl passwords or Hotmail/GMail/Yahoo/Paypal from applications that run on the user's desktop.</p> <p>Clarification: I asked this before without the 'important' portion but stackoverflow's UI doesn't help with adding details later inside the Q/A conversation.</p> <ul> <li>Hashing apparently doesn't do it</li> <li>Obfuscating in a reversable way is like trying to hide behind my finger</li> <li>Plain text sounds and propably is promiscuous</li> <li>Requiring the user to type in his password every time would make the application tiresome</li> </ul> <p>Any ideas ?</p>
<p>This is a catch-22. Either you make the user type in his password every time, or you store it insecurely (obfuscated, encrypted, whatever).</p> <p>The way to fix this is for more operating systems to incorporate built-in password managers - like OS X's Keychain. That way you just store your password in the Keychain, the OS keeps it secure, and the user only has to type in 1 master password. Lots of applications (like Skype) on OS X use Keychain to do exactly what you are describing.</p> <p>But since you are probably using Windows, I'd say just go with some obfuscation and encryption. I think you may be slightly paranoid about the password-stealing-bots; if your application doesn't have a large userbase, odds are pretty low that someone will target it and specifically try to steal the passwords. Besides that, they would also have to have access to their victim's filesystem. If that's the case, they probably have a virus/worm and have bigger problems.</p>
<p>OSX: Use the Keychain</p> <p>Windows: Use CryptProtectData and CryptUnprotectData</p> <p>Linux: Use GNOME Keyring and KDE KWallet</p>
27,920
<p>What is the preferred way to use stored procedures between the following two methods and why:</p> <p>One general SP such as 'GetOrders' which returns all the columns for the table Order. Several different parts of the application will use the same SP.</p> <p>OR</p> <p>Several more specific SPs such as 'GetOrdersForUse1' and 'GetOrdersForUse2' which return a subset of all the columns. Each SP is only used by one part of the application.</p> <p>In the general case, the application will only use a subset of the columns returned by the SP. I was thinking of using the specific method for performance reasons but is it really going to be worth the extra work? I am developing a web site using ASP.NET and SQL 2005.</p>
<p>I'd recommend optimistic locking instead. you add a "version" property to your object and then hibernate does an update operation at the end and verifies that the version has not changed since you read the object. generally a much better design than pessimistic locking (nothing like finding those db deadlocks!).</p> <p>Of course, the question remains, what do you plan on doing if the object has changed?</p>
<p>You can use pessimistic lock although I wouldn't do that, but it may be useful in your case.</p> <p>Since your object is retrieved from the DB you have to lock the DB so no one else modifies your object while you're working with it.</p> <p>To do that you should <strong><a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#lock(java.lang.Object,%20org.hibernate.LockMode)" rel="nofollow noreferrer">lock</a></strong> your object.</p> <pre><code>session.lock( myObject , LockMode.UPGRADE ); </code></pre> <p>Give it a try.</p> <p><strong>EDIT</strong></p> <p>This may be more you:</p> <pre><code>// Load from DB Criteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq("id", 5) ); crit.setLockMode( LockMode.UPGRADE ); // issues a SELECT ... for UPDATE... Dummy val = crit.uniqueResult(); etc.etc </code></pre> <p><a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html#setLockMode(org.hibernate.LockMode)" rel="nofollow noreferrer">Criteria.setLockMode()</a></p>
44,076
<p>I'm trying to add support for stackoverflow feeds in my rss reader but <strong>SelectNodes</strong> and <strong>SelectSingleNode</strong> have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.</p> <p>I have gotten it to work by removing all attributes from the <strong>feed</strong> tag, but that's a hack and I would like to do it properly. So, how do you use <strong>SelectNodes</strong> with atom feeds?</p> <p>Here's a snippet of the feed.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0"&gt; &lt;title type="html"&gt;StackOverflow.com - Questions tagged: c&lt;/title&gt; &lt;link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" /&gt; &lt;subtitle&gt;Check out the latest from StackOverflow.com&lt;/subtitle&gt; &lt;updated&gt;2008-08-24T12:25:30Z&lt;/updated&gt; &lt;id&gt;http://stackoverflow.com/feeds/tag/c&lt;/id&gt; &lt;creativeCommons:license&gt;http://www.creativecommons.org/licenses/by-nc/2.5/rdf&lt;/creativeCommons:license&gt; &lt;entry&gt; &lt;id&gt;http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server&lt;/id&gt; &lt;title type="html"&gt;What is the best way to communicate with a SQL server?&lt;/title&gt; &lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" /&gt; &lt;author&gt;&lt;name&gt;Ed&lt;/name&gt;&lt;/author&gt; &lt;link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" /&gt; &lt;published&gt;2008-08-22T05:09:04Z&lt;/published&gt; &lt;updated&gt;2008-08-23T04:52:39Z&lt;/updated&gt; &lt;summary type="html"&gt;&amp;lt;p&amp;gt;I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?&amp;lt;/p&amp;gt;&lt;/summary&gt; &lt;link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/&gt; &lt;thr:total&gt;2&lt;/thr:total&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p><br/></p> <h2>The Solution</h2> <pre><code>XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr); </code></pre>
<p>Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match.</p> <p>So you can register "<a href="http://www.w3.org/2005/Atom" rel="noreferrer">http://www.w3.org/2005/Atom</a>" as "atom", and then do a SelectNodes for "atom:entry".</p>
<p>I just want to use..</p> <pre><code>XmlNodeList itemList = xmlDoc.DocumentElement.SelectNodes("entry"); </code></pre> <p>but, what namespace do the <strong>entry</strong> tags fall under? I would assume xmlns="http://www.w3.org/2005/Atom", but it has no title so how would I add that namespace?</p> <pre><code>XmlDocument document = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("", "http://www.w3.org/2005/Atom"); document.Load(feed); </code></pre> <p>Something like that?</p>
4,440
<p>using the Symbian S60 5th edition SDK released on October 2nd, I am compiling/running(on sim) the following code snippet:</p> <pre><code>void test(wchar_t *dest, int size, const wchar_t *fmt, ...) { va_list vl; va_start(vl, fmt); vswprintf(dest, size, fmt, vl); va_end(vl); } ... wchar_t str[1024]; // this crashes (2nd string 123 characters (+ \0) equals 248 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a tes"); // this works (2nd string 122 characters (+ \0) equals 246 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a te"); </code></pre> <p>For no reason obvious to me (even after having read the <a href="http://www.forum.nokia.com/document/CDL_Extension_S60_3rd_Ed_FP2/GUID-719955DA-415B-420E-9F9B-F6DB37615EC5/html/wprintf.html" rel="nofollow noreferrer">vswprintf</a> man page a hundred times) can I figure out why this code is crashing on me in the vswprintf call for long strings :-( The exact same code works fine on a Linux box. There is sufficient memory allocated for str, plus vswprintf is checking for buffer overruns anyway. Unfortunately the ... S60 debugger does not break on this crash, so I have no details :-(</p> <p>Does anybody have any ideas? </p> <p>Assuming a bug in Symbian's vswprintf routine, what would be possible replacement functions using POSIX compliant code? (this is supposed to be a cross-platform library)</p> <p>Thanks.</p>
<p>To me this looks like a job for stepping into the <code>vswprintf()</code> call. Even if you can only do assembly-level debugging, it should be clear what's more or less going on by keeping a watch on what's going into the the <code>str[]</code> memory.</p>
<p>Change the %S to a %s - uppercase to lowercase.</p> <p>In MS-based printfs, %S means unicode characters, so this is why the 123 character string fails, it expects 2 bytes per character. (note %S is not part of the standard, so Symbian may be different here)</p> <p>Actually, I think that still applies to <a href="http://www.symbian.com/developer/techlib/v70sdocs/doc_source/reference/cpp/Descriptors/FormatStringSyntax.guide.html#Descriptors.Format-string-syntax" rel="nofollow noreferrer">Symbian</a>.</p>
26,293
<p>We run a relatively high volume content site. Like most content sites, the majority of each page is relatively static. The articles rarely change, making them good candidates for some form of static/edge caching. There are two big problems, though. Secondary page elements (nav, recent content lists, etc) change pretty frequently, quickly invalidating "full" cached pages. It's also quite common that we include more dynamic bits in a page, like user specific information, etc.</p> <p>It would be really neat to have a reverse-proxy/load balancer that post-processed content and let us handle includes at the proxy/edge. The initial request to the backend would return a rough template, then the proxy software could process that template to complete it. The markup might look something like this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="content"&gt; Lorem ipsum whackem smackem. &lt;% dynamic "http://related.content.service/this/story" %&gt; &lt;/div&gt; &lt;div id="sidebar"&gt; &lt;% dynamic do |request| url = "http://my.user.service/user-widget.html" if request.cookies.contains?("user_token") url = "http://my.user.service/" + request.cookies["user_token"] + "/user-widget.html" end error_text = "User service not available" { :url =&gt; url, :timeout =&gt; 500, :error =&gt; error_text } end %&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What you'll see in that example is a small bit of Ruby that determines the included file based on a cookie value, then returns a hash with the URL to pull in, a timeout, and some default text to show in the event of an error. In theory, all the includes could be requested asynchronously as well.</p> <p>My understanding is that Amazon does something like this. Various page components are generated by backend services, with strict timeout limits to ensure overall page speed. I was hoping their CDN service would include something like this, but it's not to be!</p> <p>There's a W3 spec for Edge Side Includes (ESI) is almost what I want. There's very little support for it out there, however. It's available through Akamai, there's some Oracle software that does it, and the open source Varnish cache has a very basic implementation. It's also a really ugly XML format.</p> <p>So the question is: what out there will let me do what I want? Is anyone else doing things in this way?</p>
<p>set Nginx as a front-end, and use SSI to pick the dynamic parts of the pages. dynamic source can be an HTTP server, like Apache, or a FastCGI server, for example PHP, or Django.</p> <p>edit:</p> <p>Many webservers support some form of SSI (Server Side Includes), this feature lets you add some tags into the HTML as a very limited form of scripting, much simpler and faster (and older) than PHP. Using this you can set static pages with most of the content, and for the 'small dynamic parts', an SSI tag references a dynamic page generated somewhere else.</p> <p>I particularly like nginx as a frontend to almost anything. it's wicked fast, light on resources and hugely scalable (think lighthttp with cleaner and stabler code). the author describes it not as a general-purpose webserver; but as a proxy frontend. The backends can be an HTTP server (usually Apache) or FastCGI processes (PHP, Python, Perl, whatever), or a farm of either, or both.</p> <p>the memcached module is amazing, it uses memcached (which is the fastest and most scalable general-purpose distributed hashtable around) to directly relate a webpage with an URL, no disk access involved. since memcached is accessible from 'outside' the webserver itself, it can be used even with dynamic pages (given a sane URL/resource mapping); but I don't think it would help a lot in your case. in any case, first make it work with SSI, then you can (if necessary) optimise the dynamic part with memcached.</p>
<p>I know a few people have written about using nginx SSI with the memcache nginx module to splice together content fragments. It's a lot more limited than something like ESI, but still useful.</p>
42,542
<p>I'd like to ensure my RAII class is always allocated on the stack.</p> <p>How do I prevent a class from being allocated via the 'new' operator?</p>
<p>All you need to do is declare the class' new operator private:</p> <pre><code>class X { private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); // ... // The rest of the implementation for X // ... }; </code></pre> <p>Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X. </p> <p>To complete things, you should hide 'operator delete' and the array versions of both operators.</p> <p>Since C++11 you can also explicitly delete the functions:</p> <pre><code>class X { // public, protected, private ... does not matter static void *operator new (size_t) = delete; static void *operator new[] (size_t) = delete; static void operator delete (void*) = delete; static void operator delete[](void*) = delete; }; </code></pre> <p><strong>Related Question:</strong> <a href="https://stackoverflow.com/questions/124880/is-it-possible-to-prevent-stack-allocation-of-an-object-and-only-allow-it-to-be">Is it possible to prevent stack allocation of an object and only allow it to be instiated with ‘new’?</a></p> <p></p>
<p>In my particular situation, if the lock isn't necessary the mutex doesn't even exist, so I think that approach would be rather harder to fit.</p> <p>I guess the thing I'm really struggling to understand is the justification for prohibiting creation of these objects on the free store.</p>
15,179
<p>I am using MS SQL Server 2005, I have dates stored in epoch time (starting 1970) I need to create a statement that will affect any record that has not been updated in the last 24 hours.</p>
<p>To get the current datetime into epoch format, use (<a href="http://wiki.lessthandot.com/index.php/Epoch_Date" rel="nofollow noreferrer">via</a>):</p> <pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000',GETUTCDATE()) </code></pre> <p>To get the epoch time for now - 24 hours use:</p> <pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE())) </code></pre> <p>So, you could do:</p> <pre><code>DECLARE @24_hours_ago AS INT SELECT @24_hours_ago = DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE())) UPDATE table SET col = value WHERE last_updated &lt; @24_hours_ago </code></pre>
<p>You can convert from SQL Server DateTime to Epoch time by calculating the number of seconds that have elapsed since Jan 1, 1970, like this.</p> <p><code>Select DateDiff(Second, '19700101', GetDate())</code></p> <p>To get rows from the last 24 hours....</p> <pre><code>Select Columns From Table Where EpochColumn Between DateDiff(Second, '19700101', GetDate()) And DateDiff(Second, '19700101, GetDate()-1) </code></pre>
30,879
<p>I would like to be able to query whether or not a service is running from a windows batch file. I know I can use: </p> <blockquote> <p>sc query "ServiceName" </p> </blockquote> <p>but, this dumps out some text. What I really want is for it to set the <code>errorlevel</code> environment variable so that I can take action on that.</p> <p>Do you know a simple way I can do this?</p> <p><strong>UPDATE</strong><br> Thanks for the answers so far. I'm worried the solutions that parse the text may not work on non English operating systems. Does anybody know a way around this, or am I going to have to bite the bullet and write a console program to get this right.</p>
<pre><code>sc query "ServiceName" | find "RUNNING" </code></pre>
<p>I have created one based from above but will show if the service is installed first then get whether it is running or not.</p> <pre><code>sc query &quot;YourService&quot; | find /i &quot;failed&quot; 2&gt;&amp;1&gt;nul &amp;&amp; echo.'YourService Not Installed' || (sc query &quot;YourService&quot;| find /i &quot;running&quot; 2&gt;&amp;1&gt;nul &amp;&amp; echo.Yes || echo.No) </code></pre>
45,994
<p>We're building some software for an in-house Kiosk. The software is a basic .net windows form with an embedded browser. The Kiosk is outfitted with a mat that the user steps on. When the user steps on the mat, it sends a key comination through the keyboard. When the user steps off the mat it sends a different key combination.</p> <p>What we want to do is look for the key combination in our app, and based on if the user steps on or off, cause the browser to go to a different url.</p> <p>How do you hook the keyboard to accomodate this type of situation?</p>
<p>If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.</p> <pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { const int WM_KEYDOWN = 0x100; const int WM_SYSKEYDOWN = 0x104; if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN)) { switch (keyData) { case Keys.Down: this.Text = "Down Arrow Captured"; break; case Keys.Up: this.Text = "Up Arrow Captured"; break; case Keys.Tab: this.Text = "Tab Key Captured"; break; case Keys.Control | Keys.M: this.Text = "&lt;CTRL&gt; + M Captured"; break; case Keys.Alt | Keys.Z: this.Text = "&lt;ALT&gt; + Z Captured"; break; } } return base.ProcessCmdKey(ref msg, keyData); } </code></pre>
<p>And if your application is NOT the main window, take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms646309.aspx" rel="nofollow noreferrer">RegisterHotkey</a> Win32 API, with some info on <a href="http://pinvoke.net/default.aspx/user32/RegisterHotKey.html" rel="nofollow noreferrer">p/invoke here</a>.</p>
26,316
<p>First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. </p> <p>If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I have to know how it's made. If I see a Ruby DSL or some Ruby voodoo, I'm hooked on Ruby for a while.</p> <p>Right now I'm working as a Java developer, but plan on taking CEH in the near future. My question is: for tool writing and exploit development, which language do you find to be the most appropriate?</p> <p>Again, I don't want to cause a flame-war or any trouble, I just want honest opinions from scripters that know what they're doing.</p> <p>One more thing: maybe some of you will ask "Why settle on one language?". To answer this: I would like to choose only one language, in order to try to master it.</p>
<p>You probably want Ruby, because it's the native language for Metasploit, which is the de facto standard open source penetration testing framework. Ruby's going to give you:</p> <ul> <li><a href="http://www.metasploit.com/" rel="noreferrer">Metasploit's</a> framework, opcode and shellcode databases</li> <li>Metasploit's <a href="http://rubyforge.org/projects/ruby-lorcon/" rel="noreferrer">Ruby lorcon</a> bindings for raw 802.11 work.</li> <li>Metasploit's KARMA bindings for 802.11 clientside redirection.</li> <li><a href="http://curl.haxx.se/libcurl/ruby/" rel="noreferrer">Libcurl</a> and net/http for web tool writing.</li> <li><a href="http://rubyforge.org/projects/eventmachine" rel="noreferrer">EventMachine</a> for web proxy and fuzzing work (or RFuzz, which extends the well-known Mongrel webserver).</li> <li><a href="http://metasm.cr0.org/" rel="noreferrer">Metasm</a> for shellcode generation.</li> <li><a href="http://www.ragestorm.net/distorm/" rel="noreferrer">Distorm</a> for x86 disassembly.</li> <li><a href="http://blogfranz.blogspot.com/2008/01/bindata-for-ruby-fuzzers.html" rel="noreferrer">BinData</a> for binary file format fuzzing.</li> </ul> <p>Second place here goes to Python. There are more pentesting libraries available in Python than in Ruby (but not enough to offset Metasploit). Commercial tools tend to support Python as well --- if you're an Immunity CANVAS or CORE Impact customer, you want Python. Python gives you:</p> <ul> <li><a href="http://twistedmatrix.com/trac/" rel="noreferrer">Twisted</a> for network access.</li> <li><a href="http://www.openrce.org/downloads/details/208/PaiMei" rel="noreferrer">PaiMei</a> for program tracing and programmable debugging.</li> <li>CANVAS and Impact support.</li> <li><a href="http://www.matasano.com/log/695/windows-remote-memory-access-though-firewire/" rel="noreferrer">Dornseif's</a> firewire libraries for remote debugging.</li> <li><a href="http://pydbgeng.sourceforge.net/" rel="noreferrer">Ready integration with WinDbg</a> for remote Windows kernel debugging (there's still no good answer in Ruby for kernel debugging, which is why I still occasionally use Python). </li> <li><a href="http://peachfuzzer.com/" rel="noreferrer">Peach Fuzzer</a> and Sully for fuzzing.</li> <li>SpikeProxy for web penetration testing (also, <a href="http://www.owasp.org/index.php/Category:OWASP_Pantera_Web_Assessment_Studio_Project" rel="noreferrer">OWASP Pantera</a>).</li> </ul> <p>Unsurprisingly, a lot of web work uses Java tools. The de facto standard web pentest tool is Burp Suite, which is a Java swing app. Both Ruby and Python have Java variants you can use to get access to tools like that. Also, both Ruby and Python offer:</p> <ul> <li>Direct integration with libpcap for raw packet work.</li> <li>OpenSSL bindings for crypto.</li> <li>IDA Pro extensions.</li> <li>Mature (or at least reasonable) C foreign function interfaces for API access.</li> <li>WxWindows for UI work, and decent web stacks for web UIs.</li> </ul> <p>You're not going to go wrong with either language, though for mainstream pentest work, Metasploit probably edges out all the Python benefits, and at present, for x86 reversing work, Python's superior debugging interfaces edge out all the Ruby benefits.</p> <p>Also: it's 2008. They're not "scripting languages". They're programming languages. ;)</p>
<p>Well, what kind of exploits are you thinking about? If you want to write something that needs low level stuff (ptrace, raw sockets, etc.) then you'll need to learn C. But both Perl and Python can be used. The real question is which one suits your style more?</p> <p>As for toolmaking, Perl has good string-processing abilities, is closer to the system, has good support, but IMHO it's very confusing. I prefer Python: it's a clean, easy to use, easy to learn language with good support (complete language/lib reference, 3rd party libs, etc.). And it's (strictly IMHO) cool.</p>
10,203
<h2>Goal</h2> <p>Java client for Yahoo's HotJobs <a href="http://developer.yahoo.com/hotjobs/resume_search_user_guide/index.html" rel="nofollow noreferrer">Resumé Search REST API</a>. </p> <h2>Background</h2> <p>I'm used to writing web-service clients for SOAP APIs, where <a href="https://jax-ws.dev.java.net/jax-ws-ea3/docs/wsimport.html" rel="nofollow noreferrer">wsimport</a> generates proxy stubs and you're off and running. But this is a REST API, which is new to me.</p> <h2>Details</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="nofollow noreferrer">REST</a> API</li> <li>No <a href="http://en.wikipedia.org/wiki/Web_Application_Description_Language" rel="nofollow noreferrer">WADL</a></li> <li>No formal XML schema (XSD or DTD files). There are <a href="http://developer.yahoo.com/hotjobs/resume_search_user_guide/auth.html" rel="nofollow noreferrer">example XML request/response pairs</a>.</li> <li>No example code provided</li> </ul> <h2>Progress</h2> <p>I looked at question <a href="https://stackoverflow.com/questions/221442/rest-clients-for-java">Rest clients for Java?</a>, but the automated solutions there assume you are providing both the server and the client, with JAXB invoked on POJOs to generate a schema and a REST API.</p> <p>Using <a href="http://jersey.java.net/" rel="nofollow noreferrer">Jersey</a> (a <a href="http://jcp.org/en/jsr/detail?id=311" rel="nofollow noreferrer">JAX-RS</a> implementation), I have been able to make a manual HTTP request:</p> <pre><code>import com.sun.jersey.api.client.*; ... ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); WebResource webResource = client.resource("https://hj.yahooapis.com/v1/HJAuthTokens"); webResource.accept("application/xml"); // body is a hard-coded string, with replacements for the variable bits String response = webResource.post(String.class, body); // parse response into a org.w3c.dom.Document // interface with Document via XPATH, or write my own POJO mappings </code></pre> <p>The response can look like:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Response&gt; &lt;ResponseCode&gt;0&lt;/ResponseCode&gt; &lt;ResponseMessage&gt;Login successful&lt;/ResponseMessage&gt; &lt;Token&gt;NTlEMTdFNjk3Qjg4NUJBNDA3MkJFOTI3NzJEMTdDNDU7bG9jYWxob3N0LmVnbGJwLmNvcnAueWFob28uY29tO0pVNWpzRGRhN3VhSS4yQVRqRi4wWE5jTWl0RHVVYzQyX3luYWd1TjIxaGx6U0lhTXN3LS07NjY2MzM1OzIzNDY3NTsxMjA5MDE2OTE5OzZCM1RBMVNudHdLbl9VdFFKMFEydWctLQ==&lt;/Token&gt; &lt;/Response&gt; </code></pre> <p>Or, it can look like:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xml:lang="en-US"&gt; &lt;yahoo:description&gt;description&lt;/yahoo:description&gt; &lt;yahoo:detail&gt; &lt;ErrorCode&gt;errorCode&lt;/ErrorCode&gt; &lt;/yahoo:detail&gt; &lt;/yahoo:error&gt; </code></pre> <h2>Questions</h2> <ul> <li>Is there a way to auto-generate <a href="http://en.wikipedia.org/wiki/POJO" rel="nofollow noreferrer">POJOs</a> which can be marshalled/unmarshalled without a formal schema? </li> <li>Should I attempt to generate those POJOs by hand, with <a href="http://jaxb.java.net/" rel="nofollow noreferrer">JAXB</a> annotations?</li> <li><strong><em>Is there some tool I should be leveraging so I don't have to do all this manually?</em></strong></li> </ul>
<p>It's interesting that they provide an HTTP URL as the namespace URI for the schema, but don't actually save their schema there. That could be an oversight on their part, which an email or discussion-list posting could correct.</p> <p>One approach is to create your own schema, but this seems like a lot of work for little return. Given how simple the messages are, I wonder if you even need a POJO to wrap them? Why not just have a handler that extracts the data you need using XPath?</p> <hr> <p>Edit: blast from the past, but I saw the comment, reread the question, and realized that the first sentence was hard to understand. So, clarification:</p> <p>One very good habit, if you're going to write a publicly accessible web service, is to make your schema document available at the same URL that you use for the schema's namespace URI -- or better, have that URL be a link to complete documentation (the W3C XSD namespace is itself a good example: <a href="http://www.w3.org/2001/XMLSchema" rel="nofollow noreferrer">http://www.w3.org/2001/XMLSchema</a>).</p>
<p>Try <code>JdkRequest</code> from <a href="http://http.jcabi.com/" rel="nofollow">jcabi-http</a> (I'm a developer). This is how it works:</p> <pre><code>String body = new JdkRequest("http://www.google.com") .header("User-Agent", "it's me") .fetch() .body() </code></pre> <p>Check this blog post for more details: <a href="http://www.yegor256.com/2014/04/11/jcabi-http-intro.html" rel="nofollow">http://www.yegor256.com/2014/04/11/jcabi-http-intro.html</a></p>
46,921
<p>I'm trying to setup CruiseControl.net at the moment. So far it works nice, but I have a Problem with the MSBuild Task.</p> <p>According to the <a href="http://confluence.public.thoughtworks.org/display/CCNET/MsBuild+Task" rel="noreferrer">Documentation</a>, it passes CCNetArtifactDirectory to MSBuild. But how do I use it?</p> <p>I tried this:</p> <pre><code>&lt;buildArgs&gt; /noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test &lt;/buildArgs&gt; </code></pre> <p>But that does not work. In fact, it kills the service with this error:</p> <blockquote> <p>ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory</p> </blockquote> <p>Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer <code>/p:OutputPath</code>.</p>
<p>The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the "bin location" relevant to the working directory that you have specified.</p> <pre><code>&lt;executable&gt;c:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe&lt;/executable&gt; &lt;workingDirectory&gt;C:\data\projects\FooSolution\&lt;/workingDirectory&gt; &lt;projectFile&gt;FooSolution.sln&lt;/projectFile&gt; &lt;buildArgs&gt;/noconsolelogger /p:Configuration=Debug &lt;/buildArgs&gt; </code></pre> <p>So in the above example your build output will be put in C:\data\projects\FooSolution[ProjectName]\bin\Debug. Should you want to output to a different location you may want to look at of the tag in CCNET.</p> <pre><code>&lt;publishers&gt; &lt;xmllogger /&gt; &lt;buildpublisher&gt; &lt;sourceDir&gt;C:\data\projects\FooSolution\FooProject\bin\Debug&lt;/sourceDir&gt; &lt;publishDir&gt;C:\published\FooSolution\&lt;/publishDir&gt; &lt;useLabelSubDirectory&gt;false&lt;/useLabelSubDirectory&gt; &lt;/buildpublisher&gt; &lt;/publishers&gt; </code></pre> <p>This will allow you to publish your output to a different location.</p>
<p>Parameters like <code>CCNetArtifactDirectory</code> are passed to external programs using environment variables. They are available in the external program but they aren't inside <code>CCNET</code> configuration. This often leads to confusion.</p> <p>You can use a preprocessor constant instead: </p> <pre><code>&lt;cb:define project.artifactDirectory="C:\foo"&gt; &lt;project&gt; &lt;!-- [...] --&gt; &lt;artifactDirectory&gt;$(project.artifactDirectory)&lt;/artifactDirectory&gt; &lt;!-- [...] --&gt; &lt;tasks&gt; &lt;!-- [...] --&gt; &lt;msbuild&gt; &lt;!-- [...] --&gt; &lt;buildArgs&gt;/noconsolelogger /p:OutputPath=$(project.artifactDirectory)\test&lt;/buildArgs&gt; &lt;!-- [...] --&gt; &lt;/msbuild&gt; &lt;!-- [...] --&gt; &lt;/tasks&gt; &lt;!-- [...] --&gt; &lt;/project&gt; </code></pre>
2,327
<p>Every now and then, I accidentally hit C-x C-c in Emacs when I'm intending to just hit C-x or C-c. This, of course, closes all open frames and buffers with no confirmation. I know that I can make Emacs prompt "Are you sure you want to exit?", but I don't want to do that all the time, which would get annoying. I just want it to do it when there are more than N files (or buffers) open.</p> <p>So I'd like to bind C-x C-c to a function along the lines of:</p> <pre><code>(if (&lt; number of open buffers n) (save-buffers-kill-emacs) (are-you-sure)) </code></pre> <p>But I can't figure out how to get the number of open buffers (or the number of open frames, or the number of open files, etc).</p>
<p>This is what I use:</p> <pre><code>(defun count-buffers (&amp;optional display-anyway) "Display or return the number of buffers." (interactive) (let ((buf-count (length (buffer-list)))) (if (or (interactive-p) display-anyway) (message "%d buffers in this Emacs" buf-count)) buf-count)) </code></pre> <p>I stole it <del>, but can't remember from where</del>. from <a href="http://www.cb1.com/~john" rel="nofollow noreferrer">John Sturdy</a>, who sounds like a fascinating fellow; it's available from <a href="http://www.cb1.com/~john/computing/emacs/lisp/startup/buffer-misc.el" rel="nofollow noreferrer">his website</a>.</p>
<p>Also, you can consider using desktop-mode, which will automatically restore your buffers when you start Emacs again. Just add </p> <pre><code>(desktop-save-mode 1) </code></pre> <p>to your <code>.emacs</code>. See <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Saving-Emacs-Sessions.html" rel="nofollow noreferrer">GNU Emacs manual</a> or <a href="http://www.emacswiki.org/emacs/DeskTop" rel="nofollow noreferrer">Emacswiki</a>.</p>
45,627
<p>Well.. we've developed a j2ee application using struts2 ajax capabilities. We find that the dojo implementation is quite slow. We did the following things: 1. Custom build of the dojo library. (increased dojo.js from 240kb to 350kb) 2. Took all the static stuff out of the struts jar and kept it outside.</p> <p>The performance was significantly improved. But still it is quite heavy as you can guess with 350kb size..</p> <p>Is struts2 ajax supposed to be this heavy? or is there any lighter implementation available?</p> <hr> <p>Edit: I used Firebug and YSlow with my application. Couple of changes that improved my situation hugely are mentioned below:</p> <ol> <li>Custom build of dojo (reduced the number of I/Os)</li> <li>Move the static files out of Struts jar (helped a great deal)</li> <li>tune your server to gzip the response (reduced the response size to 1/3)</li> <li>Reduce number of images on your site.(this is obvious)</li> </ol> <p>Will keep updating on further changes..</p>
<p>First of all check that you did everything on the server to facilitate caching (e.g., setting right HTTP headers, compression, server-side caching, upstream caches, and so on). See <a href="http://lazutkin.com/blog/2007/feb/1/improving-performance/" rel="noreferrer">Improving performance&hellip;</a> for more details.</p> <p>The goal is to reduce I/O as much as possible &mdash; use Firebug or any other network traffic monitoring tool to see how much is sent back and forth. Try to minimize the number of I/O requests and the total number of bytes.</p> <p>Don't forget that it applies to your dynamic data too &mdash; choose efficient formats, bundle several related requests together, remove all deadwood that is getting sent over and over unchanged.</p> <p>If the custom build and server-side tweaks didn't help, consider restructuring your web app to be more light-weight. Examples:</p> <ul> <li>Evaluate the splash screen technique discussed in the link above.</li> <li>If you use a lot of different form widgets, see if it is really necessary, and fall back on regular DOM elements like "input", "button", "textarea", "select".</li> <li>The same goes for layout widgets. See if simple CSS can help you out.</li> <li>Evaluate building Dojo in layers instead of one monolithic dojo.js so only the necessary subset is loaded by web pages. See details in <a href="http://www.dojotoolkit.org/book/dojo-book-0-9/part-4-meta-dojo/package-system-and-custom-builds" rel="noreferrer">The Package System and Custom Builds</a>.</li> </ul> <p>Building web applications with Dojo for a living for last 2 years I still didn't see the one that cannot be optimized properly until it is fully accepted and perceived by end users as "fast", "nimble", and "light-weight".</p>
<p>Last I checked, struts was shipping a release of Dojo (0.4) that's going on 2 years old. Dojo did a rewrite for version 0.9/1.0 that had significant performance gains and reduced code size. You should make sure you're running a recent version of Dojo (current version is 1.2.3) and use the build and tips from Eugene, above.</p>
42,492
<p>Is there any advantage to using <code>__construct()</code> instead of the class's name for a constructor in PHP?</p> <p>Example (<code>__construct</code>):</p> <pre><code>class Foo { function __construct(){ //do stuff } } </code></pre> <p>Example (named):</p> <pre><code>class Foo { function Foo(){ //do stuff } } </code></pre> <p>Having the <code>__construct</code> method (first example) is possible since PHP 5.</p> <p>Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.</p>
<p>I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.</p> <p>Similarly, if you have a child class you can call </p> <pre><code>parent::__construct() </code></pre> <p>to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.</p> <p>It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs.</p> <p>For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.</p> <p>Also note that</p> <blockquote> <p>As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.</p> </blockquote> <p>Source: <a href="http://php.net/manual/en/language.oop5.decon.php" rel="noreferrer">http://php.net/manual/en/language.oop5.decon.php</a></p>
<p>I think that the main reason is that is the language convention. You don't need to force a language to act like someone else.</p> <p>I mean, in Objective-C you prefix the constructors with -init, for example. You can make your own constructor using your class name but why? Are ther some reason to use this schema instead of the language convention?</p>
26,745
<p>We distribute an application that uses an MS Access .mdb file. Somebody has noticed that after opening the file in MS Access the file size shrinks a lot. That suggests that the file is a good candidate for compacting, but we don't supply the means for our users to do that.</p> <p>So, my question is, does it matter? Do we care? What bad things can happen if our users never compact the database?</p>
<p>In addition to making your database smaller, it'll recompute the indexes on your tables and defragment your tables which can make access faster. It'll also find any inconsistencies that should never happen in your database, but might, due to bugs or crashes in Access.</p> <p>It's not totally without risk though -- a <a href="http://blogs.msdn.com/access/archive/2008/05/29/kb-article-950812-compact-and-repair-might-delete-your-database-access-2007.aspx" rel="noreferrer">bug in Access 2007</a> would occasionally delete your database during the process.</p> <p>So it's generally a good thing to do, but pair it with a good backup routine. With the backup in place, you can also recover from any 'unrecoverable' compact and repair problems with a minimum of data loss.</p>
<p>If you don't offer your users a way to decompress and the raw size isn't an issue to begin with, then don't bother.</p>
10,014
<p>Prompted by discussion in comments of a recent question whether PLA is suitable for parts that need to be in contact with acetone, I did some casual experiments and found that my clear/&quot;natural&quot; 3D Solutech PLA is mostly but not entirely resistant to acetone, while my blue Hatchbox PLA is quickly softened and deformed by it. This got me wondering: how do you go about finding PLA that's <strong>actually PLA</strong> (and nothing else)? Just &quot;clear/natural&quot; in product description does not seem to suffice.</p> <p>I know this is close to a shopping question, so please make suggestions on how it could be improved if it's too close. It'd be great if there were keywords that worked, but an answer is probably going to be more along the lines of how to go about inquiring with manufacturers or where to find places where manufacturers might advertise that their products as pure.</p>
<p>There's only two ways to make sure it is pure PLA without color and additives:</p> <ul> <li>Make it yourself. Order PLA-pellets for manufacturing and put them into a filament extrusion machine</li> <li>Contact your manufacturer and ask them to do the above for you.</li> </ul> <p>Note though that the pure PLA might have undesirable attributes for pritability that are fought with fillers and additives.</p>
<p>If acetone resistance is what you are after, try PETG:</p> <p>&quot;While the chemical resistance of PETG is one of its most desirable characteristics, it is also one of the reasons why smoothing PETG prints is challenging. Since dissolving PETG with a solvent, smoothing via solvent application (like acetone smoothing for ABS) is not a very good option.&quot; See 2. Chemical Resistance in <a href="https://3dinsider.com/how-to-smooth-petg-prints/" rel="nofollow noreferrer">https://3dinsider.com/how-to-smooth-petg-prints/</a></p>
1,690
<p>I’d like a visual database tool that will allow me to access multiple database types from the same program. I’m looking for anything that supports Mysql, PostgreSQL, and Derby. Anything else it supports is a bonus.</p>
<p>If you can get ODBC drivers for your databases (should be available from the DB vendor) you can use MS Access. If you want something free, I recommend <a href="http://www.squirrelsql.org/" rel="noreferrer">SQuirrel SQL Client</a>. It's implemented in Java, so you need JDBC drivers (usually also available for free) for each DB that you use.</p>
<p>I think you might be interested in <a href="http://www.sparxsystems.com.au/products/index.html#EA" rel="nofollow noreferrer">Sparx Enterprise Architect</a>. It could help with reverse engineering and creating fancy diagrams. It works with everything you could get drivers for but your database are natively supported.</p> <p>Vision for Enterprise Architects could do the same.</p>
39,260
<p>I have a site with the following robots.txt in the root:</p> <pre><code>User-agent: * Disabled: / User-agent: Googlebot Disabled: / User-agent: Googlebot-Image Disallow: / </code></pre> <p>And pages within this site are getting scanned by Googlebots all day long. Is there something wrong with my file or with Google?</p>
<p>It should be <code>Disallow:</code>, not <code>Disabled:</code>.</p>
<p>Also I believe that the bot goes down the page and takes the first directive that applies to it. In your case, Googlebot and Googlebot-Image would never see their specific directives because they would respect the "User-Agent: *" first.</p> <p><strong>Disregard this answer. I found information that points to this not being the case. The bot should find the directive specific to it and respect it</strong></p>
44,837
<p>I need to replace all WinAPI calls of the</p> <ul> <li>CreateFile, </li> <li>ReadFile, </li> <li>SetFilePointer,</li> <li>CloseHandle </li> </ul> <p>with my own implementation (which use low-level file reading via Bluetooth). The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files. It is also needed, that Video Player still can play files from HDD, if the file in the VideoPlayer input is a regular hdd file.</p> <p>What is the best practice for such task?</p>
<p>I suggest that you follow these steps:</p> <ol> <li>Write a set of wrapper functions, e.g MyCreateFile, MyReadFile, etc, that initially just call the corresponding API and pass the same arguments along, unmodified.</li> <li>Use your text editor to search for all calls to the original APIs, and replace these with calls to your new wrapper functions.</li> <li>Test that the application still functions correctly.</li> <li>Modify the wrapper functions to suit your own purposes.</li> </ol> <p>Note that CreateFile is a macro which expands to either CreateFileW or CreateFileA, depending on whether UNICODE is defined. Consider using LPCTSTR and the <a href="http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx" rel="nofollow noreferrer">TCHAR functions</a> so that your application can be built as either ANSI or Unicode.</p> <p>Please don't use #define, as suggested in other responses here, as this will just lead to maintenance problems, and as Maximilian correctly points out, it's not a best-practice.</p>
<p>I don't think this is best practice but it should work if you put it in an include file that's included everywhere the function you want to change is called:</p> <pre><code>#define CreateFile MyCreateFile HRESULT MyCreateFile(whatever the params are); </code></pre> <p>Implementation of MyCreateFile looks something like this:</p> <pre><code>#undef CreateFile HRESULT MyCreateFile(NobodyCanRememberParamListsLikeThat params) { if (InputIsNormalFile()) CreateFile(params); else // do your thing } </code></pre> <p>You basically make every CreateFile call a MyCreateFile call where you can decide if you want need to use your own implementation or the orginal one.</p> <p>Disclaimer: I think doing this is ugly and I wouldn't do it. I'd rather search and replace all occurences or something.</p>
8,555
<p>I Have a problem with my custom Addin to word because sometimes, MS Word was disabled my addin, and I need to write another AddIn, which Was enabled to turn - on/off my first AddIn. Is it possible?</p> <p>sorry for my English :(</p>
<p>I agree with divo, your first step would be to add some exception handling/logging in order to prevent the addin from being disabled. You can also refer to this article</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms269003(VS.80).aspx" rel="nofollow noreferrer">Debugging in Application-Level Projects </a></p> <p>However, I have also had issues with the addin somehow becoming disabled without throwing any exception. If the above approaches do not work you can always go and have another program forcibly set the LoadBehavior of your addin from 2 to 3, which should re-enable it.</p>
<p>What kind of add-in technology are you using? VSTO? What version of Office are you using?</p> <p>In general it is possible to do what you want. However, the reason that Office disables add-ins is that the add-in threw an unhandled exception. In that case Office will set the <code>LoadBehavior</code> value in the Registry to 2. </p> <p>Maybe it would be better to analyze and handle the underlying problem causing the exception.</p>
38,229
<p>My company uses a sales model of dealers, territory managers and regional managers, each with a different level of area scope (IE manage based on zips codes, states, or regions.)</p> <p>I want to create a slimmed down map that is similar to <a href="http://www.onlineatlas.us/map/united-states-map.gif" rel="nofollow noreferrer">this US state map</a> that would allow our users to manipulate who manages what.</p> <p>What are some good resources to start down this path?</p>
<p><a href="http://code.google.com/apis/kml/documentation/mapsSupport.html" rel="nofollow noreferrer">KML</a> and <a href="http://www.census.gov/geo/www/tiger/" rel="nofollow noreferrer">Tiger</a>(US) or <a href="http://www.statcan.gc.ca/mgeo/geography-geographie-eng.htm" rel="nofollow noreferrer">Maps and Geo</a>(Can)? Or with something less interactive you could possibly still use the Topologically Integrated Geographic Encoding and Referencing system.</p>
<p>A combination of <a href="http://postgis.refractions.net/" rel="nofollow noreferrer">PostGIS</a> for storing the data, <a href="http://mapserver.osgeo.org/" rel="nofollow noreferrer">MapServer</a> for generating map tiles, and <a href="http://openlayers.org/" rel="nofollow noreferrer">OpenLayers</a> for the interface should give you something to start with. Include a some PHP libraries, and your are just about there!</p>
46,942
<p>At work we use <a href="http://www.atlassian.com/software/confluence/" rel="noreferrer">confluence</a>. </p> <p>On occasion it crashes, resulting in an error 500 page being generated.</p> <p>This page includes some interesting reference information, including:</p> <blockquote> <p><strong>System Information:</strong><br> favouriteColour: Myrtle<br> javaRuntime: Java(TM) SE Runtime Environment<br> jvmVersion: 1.0<br> operatingSystem: Linux 2.6.18-92.1.13.el5<br> ...</p> </blockquote> <p><em>Myrtle?</em></p> <p>Many thoughts raged through my head. What's Myrtle? Why is it my favourite colour? <em>Is</em> it my favourite colour? Why does that particular tidbit of information require its own system property?</p> <p>At first I assumed it was just something that someone at work had done. A remnant of a project long forgotten, an old April Fools joke perhaps?</p> <p>It seems <a href="http://www.google.co.nz/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla:en-US:official&amp;hs=ENc&amp;sa=X&amp;oi=spell&amp;resnum=0&amp;ct=result&amp;cd=1&amp;q=%22favourite+Colour%3A+myrtle%22&amp;spell=1" rel="noreferrer">I was mistaken</a>. In fact, even Atlassian <a href="http://confluence.atlassian.com/display/DEVNET/Confluence+Build+Information" rel="noreferrer">acknowledges the colour</a>, though they give no reason for its existence.</p> <p>Now, I know what you're thinking? <em>Who cares?</em></p> <p>I do, gentle reader, I do. And you should too. It's little mysteries like this that make life worth living.</p> <p>So, is there one among you who knows the secret of The Mysterious Myrtle uh.. Mystery? At least one inquiring mind wants to know..</p>
<p>Your Confluence System Favourite Colour (Australian spelling FTW) is also available from Admin -> System Info.</p> <p>And if I told you any more, I'd have to kill you.</p>
<p>FWIW, I've frequently put "interesting" information in error dumps -- I've found it's easier to get people to report it in bug reports, and they're more likely to accurately report something like "myrtle" as opposed to "error #47" or whatever...</p>
42,717
<p>Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.</p>
<p>You cannot do it with a plain CEdit, you need to override a few bits.</p> <p>Implement your own ON_WM_CTLCOLOR_REFLECT handler, then return your coloured CBrush in the handler:</p> <p>(roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor)</p> <pre><code>class CColorEdit : public CEdit { .... CBrush m_brBkgnd; afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor) { m_brBkgnd.DeleteObject(); m_brBkgnd.CreateSolidBrush(nCtlColor); } } </code></pre>
<p>This can also be done without deriving from CEdit:</p> <ol> <li>Add <code>ON_WM_CTLCOLOR()</code> to your dialog's <code>BEGIN_MESSAGE_MAP()</code> code block.</li> <li><p>Add <code>OnCltColor()</code> to your dialog class:</p> <pre><code>afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); </code></pre></li> <li><p>Implement <code>OnCtlColor()</code> like so:</p> <pre><code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { if ((CTLCOLOR_EDIT == nCtlColor) &amp;&amp; (IDC_MY_EDIT == pWnd-&gt;GetDlgCtrlID())) { return m_brMyEditBk; //Create this brush in OnInitDialog() and destroy in destructor } return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); } </code></pre></li> </ol>
26,815
<p>Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?</p> <pre><code>MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error </code></pre> <p>I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?</p>
<p><strong>Most vexing parse</strong></p> <p>This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration.</p> <p>Another instance of the same problem:</p> <pre><code>std::ifstream ifs("file.txt"); std::vector&lt;T&gt; v(std::istream_iterator&lt;T&gt;(ifs), std::istream_iterator&lt;T&gt;()); </code></pre> <p><code>v</code> is interpreted as a declaration of function with 2 parameters.</p> <p>The workaround is to add another pair of parentheses:</p> <pre><code>std::vector&lt;T&gt; v((std::istream_iterator&lt;T&gt;(ifs)), std::istream_iterator&lt;T&gt;()); </code></pre> <p>Or, if you have C++11 and list-initialization (also known as uniform initialization) available:</p> <pre><code>std::vector&lt;T&gt; v{std::istream_iterator&lt;T&gt;{ifs}, std::istream_iterator&lt;T&gt;{}}; </code></pre> <p>With this, there is no way it could be interpreted as a function declaration.</p>
<p>As the others said, it is a function declaration. Since C++11 you can use brace initialization if you need to see the empty <em>something</em> that explicitly tells you that a default constructor is used.</p> <pre><code>Jedi luke{}; //default constructor </code></pre>
21,735
<p>I am new to threads and in need of help. I have a data entry app that takes an exorbitant amount of time to insert a new record(i.e 50-75 seconds). So my solution was to send an insert statement out via a ThreadPool and allow the user to begin entering the data for the record while that insert which returns a new record ID while that insert is running. My problem is that a user can hit save before the new ID is returned from that insert. </p> <p>I tried putting in a Boolean variable which get set to true via an event from that thread when it is safe to save. I then put in </p> <pre><code>while (safeToSave == false) { Thread.Sleep(200) } </code></pre> <p>I think that is a bad idea. If i run the save method before that tread returns, it gets stuck.</p> <p>So my questions are: </p> <ol> <li>Is there a better way of doing this? </li> <li>What am I doing wrong here?</li> </ol> <p>Thanks for any help.<br> Doug</p> <p><strong>Edit for more information:</strong></p> <p>It is doing an insert into a very large (approaching max size) FoxPro database. The file has about 200 fields and almost as many indexes on it.<br> And before you ask, no I cannot change the structure of it as it was here before I was and there is a ton of legacy code hitting it. The first problem is, in order to get a new ID I must first find the max(id) in the table then increment and checksum it. That takes about 45 seconds. Then the first insert is simply and insert of that new id and an enterdate field. This table is not/ cannot be put into a DBC so that rules out auto-generating ids and the like.</p> <p><strong>@joshua.ewer</strong><br> You have the proccess correct and I think for the short term I will just disable the save button, but I will be looking into your idea of passing it into a queue. Do you have any references to MSMQ that I should take a look at?</p>
<p>1) Many :), for example you could disable the "save" button while the thread is inserting the object, or you can setup a Thread Worker which handle a queue of "save requests" (but I think the problem here is that the user wants to modify the newly created record, so disabling the button maybe it's better)</p> <p>2) I think we need some more code to be able to understand... (or maybe is a synchronization issue, I am not a bug fan of threads too)</p> <p>btw, I just don't understand why an insert should take so long..I think that you should check that code first! &lt;- just as charles stated before (sorry, dind't read the post) :)</p>
<p>First, you should probably find out, and fix, the reason why an insert is taking so long... 50-75 seconds is unreasonable for any modern database for a single row insert, and indicates that something else needs to be addressed, like indices, or blocking... </p> <p>Secondly, why are you inserting the record before you have the data? Normally, data entry apps are coded so that the insert is not attempted until all the necessary data for the insert has been gathered from the user. Are you doing this because you are trying to get the new Id back from the database first, and then "update" the new empty record with the user-entered data later? If so, almost every database vendor has a mechanism where you can do the insert only once, without knowing the new ID, and have the database return the new ID as well... What vendor database are you using? </p>
49,110
<p>It's gotta be free. It's hobby, after all, not a business!. Creating for-profit software isn't an issue, but anything that requires a hardware mod is out.</p>
<p>Nope, I don't think so. The only other .NET environment for consoles I know costs money and is called unity3d: <a href="http://unity3d.com/" rel="nofollow noreferrer">http://unity3d.com/</a></p> <p>I think it supports the iPhone and the Wii and uses Mono as runtime environment. 200 bucks and you are in :)</p>
<p>It depends what you classifies as a console. The iPod Touch and the iPhone has got the iPhone SDK with which it should be possible to develop quite good games and when you're done they can easily be distributed through App Store either fer free or for a price of which you will be given 70%.</p>
14,255
<p>I've got a UI front end which talks to and manipulates a SQL Server database, and one of the things it can do is run reports on the data in the database. </p> <p>This UI can be installed on multiple computers, and so far I've just been keeping the reports in a folder with the install, but this means that any time a new report is added is has to manually be copied to every single UI install out there.</p> <p>I was thinking of storing the .rpt files in the database itself (As Blobs) and having some mechanism for the UI to fetch them when needed as a way to centralize the reports and eliminate this issue.</p> <p>Has anybody tried this, and did it work well? Or if you haven't, can you think of anything I should take into account before moving forward with this? Are the any tips, tricks, or caveats you can think of that might be helpful to me?</p>
<p>Great Question! It's kind of coincidental as we've actually just implemented this within the last six months. </p> <p>As you've suggested, we store the rpt file within the database, but do this in Server 2005 as a Image type. It works just fine and as far as the database goes, there really is no caveats that come to mind.</p> <p>Obviously, the way you access this information changes with the API. If you're using C#, this translates to using a <strong>BinaryReader</strong> to load in the rpt file, grabbing a <strong>byte array</strong>. This <strong>byte array</strong> can then be passed to the database, through a stored procedure, etc.</p> <p>I realize that you're asking specifically about blobs and Server 2008, but <strong>this works in both Server 2005 and Server 2008</strong>. Hope this sheds a bit of light. </p> <p>If you need more specific details I'd be glad to share!</p>
<p>.RPT file could be stored in database(sql) by having it type as image.Store byte array into database and then retrieve it as stream.(HINT:Treat it as image file.)</p>
22,190
<p>I am building on C++ dll, by writing code in C#.</p> <p>I get an error, saying </p> <blockquote> <p>LoaderLock was detected Message: Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.</p> </blockquote> <p>I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio. The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither.</p> <p>Can anybody explain, what this actually means?</p>
<p>The general idea of loader lock: The system runs the code in DllMain inside a lock (as in - synchronization lock). Therefore, running non-trivial code inside DllMain is &quot;asking for a deadlock&quot;, as described <a href="https://devblogs.microsoft.com/oldnewthing/20040128-00/?p=40853" rel="nofollow noreferrer">here</a>.</p> <p>The question is, why are you trying to run code inside DllMain? Is it crucial that this code run inside the context of DllMain or can you spawn a new thread and run the code in it, and not wait for the code to finish execution inside DllMain?</p> <p>I believe that the problem with manged code specifically, is that running managed code might involves loading the CLR and suchlike and there's no knowing what could happen there that would result in a deadlock... I would not heed the advice of &quot;disable this warning&quot; if I were you because most chances are you'll find your applications hangs unexpectedly under some scenarios.</p>
<p>This problem occurs because of the way in which the debugger in Visual Studio runs managed applications that use Microsoft Foundation Classes version 8.0 in one or more DLL files.</p> <p>Have a thorough reading at: <a href="http://msdn.microsoft.com/en-us/library/aa290048(vs.71).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa290048(vs.71).aspx</a></p>
8,061
<p>My company is transitioning from assembly coded microcontrollers to C. We are considering Microchip, Atmel, Renasas, et. al. for future projects using C code. Are there good training resources to bring our engineers up to speed with C? Seminars, instructors, classes, etc. The experience level of the engineers varies from no training to some knowledge. </p>
<p>Welcome to the 80's. :) Start with the either classic K&amp;R C book or my favorite C: a Reference Manual by Harbinson &amp; Steel if you can find one. I work with PICs and there are several useful books about PIC programming. I was already familiar with C from using PCs I didn't find them useful in that regard. <br><br> C allows you to be close to assembly and most compilers to include it inline, so it's as close to assembler as any high level language. You should happy and at home pretty quickly, I think. <br><br> If you are interested in jumping forward a few decades ;>) you might want to consider a Microchip C complier. I'm going to be looking into this soon and there is a good book on <a href="https://rads.stackoverflow.com/amzn/click/com/1578201101" rel="nofollow noreferrer" rel="nofollow noreferrer">Practical Statecharts in C/C++</a>.</p>
<p>The first thing that comes to mind is documentation on writing Linux device drivers. This is loosely related to what you're interested, but coding for 16 bit devices is covered in <a href="http://www.xml.com/ldd/chapter/book/ch10.html" rel="nofollow noreferrer">this</a> O'Reilly book on driver programming. In general, there should at least be a number of useful coding style conventions around.</p>
33,935
<p>Is there a WMI event you can subscribe to that will fire when a remote machine boots up and comes online, or goes offline?</p> <p>My application needs to be able to monitor machines for their availability, and ideally, I'd like something that can work via events instead of continuous polling.</p>
<p>Subscribing to a shutdown event is theoretically possible. You could subscribe to get updates to the "System" Event Log. You'd be looking for an event from Source = "EventLog" and EventID = 6006. This event contains the message:</p> <blockquote> <p>The Event log service was stopped.</p> </blockquote> <p>This is usually the last message written on shutdown. But wait! It may be problematical to receive this via WMI. Why? It may be that the WMI service itself shuts down prior to EventLog so it might be a Catch 22. You could potentially look for another message that occurs earlier during shutdown on the servers you are monitoring, and watch for that.</p> <p>A boot up event carries with it an even more troublesome set of Catch 22s. Think about how WMI eventing works for a moment. To get events, you have to open a connection to the remote WMI server via DCOM, and issue a WQL query to indicate what events you want. In order to receive a boot up event, you'd have to "magically" know to open said connection and issue said query prior to the event being fired.</p> <p>Years ago I wrote a service that collected Event Log entries from remote servers for a network monitoring application. Just the logic to detect when the DCOM connection to the remote had been lost and needed to be rebuilt was a major pain in the neck. As it happened this was a component in a larger system that pinged the remote hosts anyway, so we ended up relying on that information to know when to rebuild our DCOM connections.</p>
<p>A perusal around Microsoft's and other sites doesn't yield any information on a "boot" event in WMI. However, this <a href="http://bytes.com/forum/thread838283.html" rel="nofollow noreferrer">thread</a> suggests installing something in the startup folder on the server(s) you want to monitor.</p>
37,096
<p>I've heard some people saying that enums are evil and shouldn't be used in web services because of the mismatches that could occur between the server and the client if some values are assigned, or if the enum is marked with the <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute(VS.71).aspx" rel="noreferrer">Flags</a> attribute. They also said that web services exposing enums are harder to maintain but couldn't really give me viable arguments. So from your experience what are the pros and cons of using enums in a WCF web service?</p>
<p>The reason people recommend to avoid enums in webservices is because they create subtle backwards compatible problems.</p> <p>The same applies to regular enums but in web services the problem is even more clear specially in .NET-generated proxies (see below).</p> <ul> <li>If the enumerate is input only you have no issues.</li> <li>If the enumerate can be an out parameter then if you add a new element and you return it, old clients could have problems: <ul> <li>If the client is using a .NET-generated proxy it will break before the caller can handle it (in the deserialization)</li> <li>Even if the generated code for the proxy supported the change (for example if it maps the enumerate to a string) the user code in the client may not process properly the new unexpected value (it could easily be a never executed path)</li> </ul></li> </ul> <p>By defining the parameter as a string you signal the user of your API that the value may change in the future. Even if you think that the value will never change is a good practice to be ready.</p> <p>There is a <a href="http://www.25hoursaday.com/weblog/2005/08/31/WhyYouShouldAvoidUsingEnumeratedTypesInXMLWebServices.aspx" rel="noreferrer">good post</a> by Dare Obasanjo on this topic.</p>
<p>Here's an approach. Maybe it's cumbersome. I just really dislike not being able to use enums.</p> <p>It gracefully handles deserialization of an unrecognized value, returning the default value instead. The default value would need to be safe - either an acceptable fallback or something that the application could recognize as exceptional. (Like "Unspecified.")</p> <p>The extensions prevent having to null-check before comparing.</p> <pre><code>[DataContract] public class EnumValue&lt;T&gt; where T : struct { [DataMember] private string _raw = string.Empty; [IgnoreDataMember] private bool _parsed; [IgnoreDataMember] private T _parsedValue; public EnumValue() { Set(default(T)); } public EnumValue(T value) { Set(value); } internal T Value { get { if (_parsed) return _parsedValue; if (!Enum.TryParse&lt;T&gt;(_raw, out _parsedValue)) { _parsedValue = default(T); } _parsed = true; return _parsedValue; } } public void Set(T value) { _raw = value.ToString(); _parsedValue = value; _parsed = true; } } public static class EnumValueExtensions { public static T GetValue&lt;T&gt;(this EnumValue&lt;T&gt; enumValue) where T : struct { return enumValue == null ? default(T) : enumValue.Value; } public static bool EqualsValue&lt;T&gt;(this EnumValue&lt;T&gt; enumValue, T compareTo) where T : struct { return (enumValue.GetValue().Equals(compareTo)); } } </code></pre>
42,280
<p>I'm writing a financial application in C# where performance (i.e. speed) is critical. Because it's a financial app I have to use the Decimal datatype intensively. </p> <p>I've optimized the code as much as I could with the help of a profiler. Before using Decimal, everything was done with the Double datatype and the speed was several times faster. However, Double is not an option because of its binary nature, causing a lot of precision errors over the course of multiple operations.</p> <p>Is there any decimal library that I can interface with C# that could give me a performance improvement over the native Decimal datatype in .NET?</p> <p>Based on the answers I already got, I noticed I was not clear enough, so here are some additional details:</p> <ul> <li>The app has to be as fast as it can possibly go (i.e. as fast as it was when using Double instead of Decimal would be a dream). Double was about 15x faster than Decimal, as the operations are hardware based.</li> <li>The hardware is already top-notch (I'm running on a Dual Xenon Quad-Core) and the application uses threads, so CPU utilization is always 100% on the machine. Additionally, the app is running in 64bit mode, which gives it a mensurable performance advantage over 32bit.</li> <li>I've optimized past the point of sanity (more than one month and a half optimizing; believe it or not, it now takes approx. 1/5000 of what it took to do the same calculations I used as a reference initially); this optimization involved everything: string processing, I/O, database access and indexes, memory, loops, changing the way some things were made, and even using "switch" over "if" everywhere it made a difference. The profiler is now clearly showing that the remaining performance culprit is on the Decimal datatype operators. Nothing else is adding up a considerable amount of time.</li> <li>You have to believe me here: I've gone as far as I could possibly go in the realm of C#.NET to optimize the application, and I'm really amazed at its current performance. I'm now looking for a good idea in order to improve Decimal performance to something close to Double. I know it's only a dream, but just wanted to check I thought of everything possible. :)</li> </ul> <p>Thanks!</p>
<p>You say it needs to be fast, but do you have concrete speed requirements? If not, you may well optimise past the point of sanity :)</p> <p>As a friend sitting next to me has just suggested, can you upgrade your hardware instead? That's likely to be cheaper than rewriting code.</p> <p>The most obvious option is to use integers instead of decimals - where one "unit" is something like "a thousandth of a cent" (or whatever you want - you get the idea). Whether that's feasible or not will depend on the operations you're performing on the decimal values to start with. You'll need to be <em>very</em> careful when handling this - it's easy to make mistakes (at least if you're like me).</p> <p>Did the profiler show particular hotspots in your application that you could optimise individually? For instance, if you need to do a lot of calculations in one small area of code, you could convert from decimal to an integer format, do the calculations and then convert back. That could keep the <em>API</em> in terms of decimals for the bulk of the code, which may well make it easier to maintain. However, if you don't have pronounced hotspots, that may not be feasible.</p> <p>+1 for profiling and telling us that speed is a definite requirement, btw :)</p>
<p>What about MMX/SSE/SSE2?</p> <p>i think it will help... so... decimal is 128bit datatype and SSE2 is 128bit too... and it can add, sub, div, mul decimal in 1 CPU tick...</p> <p>you can write DLL for SSE2 using VC++ and then use that DLL in your application</p> <p>e.g //you can do something like this</p> <p><strong>VC++</strong></p> <pre><code>#include &lt;emmintrin.h&gt; #include &lt;tmmintrin.h&gt; extern "C" DllExport __int32* sse2_add(__int32* arr1, __int32* arr2); extern "C" DllExport __int32* sse2_add(__int32* arr1, __int32* arr2) { __m128i mi1 = _mm_setr_epi32(arr1[0], arr1[1], arr1[2], arr1[3]); __m128i mi2 = _mm_setr_epi32(arr2[0], arr2[1], arr2[2], arr2[3]); __m128i mi3 = _mm_add_epi32(mi1, mi2); __int32 rarr[4] = { mi3.m128i_i32[0], mi3.m128i_i32[1], mi3.m128i_i32[2], mi3.m128i_i32[3] }; return rarr; } </code></pre> <p><strong>C#</strong></p> <pre><code>[DllImport("sse2.dll")] private unsafe static extern int[] sse2_add(int[] arr1, int[] arr2); public unsafe static decimal addDec(decimal d1, decimal d2) { int[] arr1 = decimal.GetBits(d1); int[] arr2 = decimal.GetBits(d2); int[] resultArr = sse2_add(arr1, arr2); return new decimal(resultArr); } </code></pre>
47,878
<p>Reading up the new Vista/Win2008 features, I wonder what is the point of the Thread Ordering Service. In other words, in which scenario the "classic" scheduler's "fair to all" policy is not sufficient, and a definite order of threads is preferrable?</p> <p>To clarify. What would be a concrete application that would benefit from it? </p> <p>Thanks for your answers, though.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.fillschema.aspx" rel="noreferrer">SqlDataAdapter.FillSchema</a></p>
<p>Do a query that normaly would return your data and add a where clause so that no rows are returned.</p>
29,661
<p>When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas?</p> <p>I expect that it is created in a job object to be debugged. I want to place my program in a different job object.</p> <p>It's not the hosting process. I'm talking about a <a href="http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx" rel="noreferrer">Job Object</a>. This is an unmanaged C++ application.</p>
<p>This happens when <code>devenv.exe</code> or <code>VSLauncher.exe</code> run in compatibility mode. The <a href="http://msdn.microsoft.com/en-us/library/bb756937.aspx" rel="noreferrer">Program Compatibility Assistant</a> (PCA) attaches a job object to the Visual Studio process, and every child process inherits it. Check if the job name (as reported by Process Explorer) starts with <strong>PCA</strong>. If so, PCA can be disabled as described in the link. </p> <p>You can globally disable PCA using <code>Run</code> -> <code>gpedit.msc</code> -> <code>Administrative Templates\Windows Components\Application Compatibility</code> -> <code>Turn off Program Compatibility Assistant</code> -> <code>Enable</code>.</p> <p>You can disable PCA for specific executables by adding a registry entry. For Windows 7, the appropriate registry key is <code>HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant</code>. In regedit, right-click that key, select <code>New</code> -> <code>Multi-String Value</code>, name it <code>ExecutablesToExclude</code>. Set the value to the full path of <code>denenv.exe</code> and <code>VSLauncher.exe</code>, on separate lines and without quotes. For me, these were:</p> <pre><code>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe </code></pre> <p>A related issue, on Windows 7, is that executables you build in Visual Studio and run from Explorer (not Visual Studio or the command line) may run in compatibility mode, and again get job objects wrapped around them. To prevent this, your executable needs a manifest that declares compatibility with Windows 7, using the new <a href="http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx" rel="noreferrer">Application Manifest Compability section</a>. The link gives an example of a Windows 7 compatible manifest. The default manifest provided by Visual Studio 2010 does not include this Compatibility section.</p>
<p>I'm not aware of any ways to control this aspect of processes spawned for debugging by VS.NET. But there's a workaround, which is applicable to any situation in which VS.NET can't or doesn't start your process in the exact way you want:</p> <p>Start your process (possibly using a wrapper EXE that runs as part of the post-build event), then attach to the newly started process using Tools/Attach to Process. If you break into the debugger as part of your startup code, this won't even be required (and you can also debug startup issues...).</p>
11,525
<p>How do I find out which sound files the user has configured in the control panel?</p> <p>Example: I want to play the sound for "Device connected".</p> <p>Which API can be used to query the control panel sound settings?</p> <p>I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.</p> <p>Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.</p> <p>To play the "Device Conntected" sound:</p> <pre><code>::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC ); </code></pre>
<p><a href="https://learn.microsoft.com/en-us/previous-versions/ms712879(v=vs.85)" rel="nofollow noreferrer"><code>PlaySound</code></a> is the API.</p> <p>Also see <a href="https://learn.microsoft.com/en-us/windows/win32/multimedia/using-playsound-to-play-system-sounds" rel="nofollow noreferrer">Play System Sounds</a>.</p>
<p>Not Win32, but for .net anyway, you can do this using the following in C#:</p> <pre><code>System.Media.SystemSounds.Asterisk.Play(); // Plays the Asterisk sound (used for Information (i)) // Also available: // Exclamation (Warning /!\) // Hand (aka Critical Stop - Error (X)) // Question (?) // Beep (aka Default Beep) </code></pre>
9,777
<p>I want to access/read the Firmware Number of a Pendrive attached on a USB Port of a PC.</p> <p>How can I do this?</p>
<p>After hunting around for a little while I found the following links which may point you in the right direction.</p> <ol> <li><a href="http://www.alanmacek.com/usb/" rel="nofollow noreferrer">Alan Macek</a></li> <li><a href="http://www.usb.org/developers" rel="nofollow noreferrer">USB-IF Developers Area</a></li> </ol> <p><em>Edit</em>: Mind you, you could just consult the Registry, which also stores info re the currently connected USB device. See <a href="http://scissec.scis.ecu.edu.au/conference_proceedings/2007/forensics/23_Luo_Tracing_USB_Device_artefacts_on_Windows_XP.pdf" rel="nofollow noreferrer">Tracing USB Devices on XP</a></p>
<p>After hunting around for a little while I found the following links which may point you in the right direction.</p> <ol> <li><a href="http://www.alanmacek.com/usb/" rel="nofollow noreferrer">Alan Macek</a></li> <li><a href="http://www.usb.org/developers" rel="nofollow noreferrer">USB-IF Developers Area</a></li> </ol> <p><em>Edit</em>: Mind you, you could just consult the Registry, which also stores info re the currently connected USB device. See <a href="http://scissec.scis.ecu.edu.au/conference_proceedings/2007/forensics/23_Luo_Tracing_USB_Device_artefacts_on_Windows_XP.pdf" rel="nofollow noreferrer">Tracing USB Devices on XP</a></p>
47,668
<p>Drawing a parallelgram is nicely supported with Graphics.DrawImage:</p> <pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); </code></pre> <p>How, do you do 4 points (obviously the following is not supported, but this is what is wanted):</p> <pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x3, y3), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); } </code></pre>
<p>Normally you would do this with a 3x3 Matrix, but the Matrix class only lets you specify 6 values instead of 9. You might be able to do this in Direct X.</p>
<p>Closest I can find is <a href="http://vckicks.110mb.com/image-distortion.html" rel="nofollow noreferrer">this information</a>, which is extremely laggy.</p>
5,922
<p>I've removed a checked in file from the CVS branch, i.e.:</p> <pre><code>cvs remove -f file.txt cvs commit </code></pre> <p>How do I restore the file?</p>
<p>I believe that:</p> <pre><code>cvs add file.txt cvs commit file.txt </code></pre> <p>... will resurrect it from the attic.</p>
<p>Here's what I do. I just create an empty file of the same name, then add and commit it, then retrieve the older version and re-commit that.</p>
17,444
<p>I'm trying to evaluate the purchase of a statistical tool. This will be used in part by non-programming users (doing clinical studies) and in part by programmers, so I'm trying to find a good compromise between usability and automation. Of course, cost is an issue, but if I can build a solid case, we could probably buy a commercial package, so we're not totally limited to free options.</p> <p>So far, our options are:</p> <ul> <li>Statistica (which some non-programmers already know)</li> <li>Matlab Statistics toolbox (programmers already use matlab)</li> <li>R language (would need a UI for non-programmers)</li> <li>Hack something into Excel (not fun, but that's what non-programmers do right now)</li> <li>?...</li> </ul> <p>What else is out there? What's the industry standard? What kind of distinctive features should I look for? What would you recommend, and why?</p> <p>Ideally, we'd like a tool that can run both on Linux and Windows machines.</p> <p>(I work in medical imaging, so we do both biostatistics, and software engineering statistics)</p>
<p><a href="http://www.stata.com/" rel="nofollow noreferrer">Stata</a> and <a href="http://www.spss.com/" rel="nofollow noreferrer">SPSS</a> tend to be the most commonly used packages in clinical studies. Both are pretty easy to pick up and use for non-technically minded folks but are generally flexible enough. I've used Stata more than any of the others and have been pretty happy with its options (supports both menu-based and command line operation, decent enough plugin system to get new user-created modules, good graphing support).</p> <p><a href="http://www.r-project.org/" rel="nofollow noreferrer">R</a> is a little more daunting for newbie users, though it is popular with the biostatisticians. Since it's free, that's another nice point in its favor.</p>
<p>Consider Excel one more time. It is well known, and widely available. Refer this <a href="http://books.slashdot.org/books/08/10/01/1329243.shtml" rel="nofollow noreferrer">book</a> or this <a href="https://rads.stackoverflow.com/amzn/click/com/0471387347" rel="nofollow noreferrer" rel="nofollow noreferrer">book</a>.</p>
22,947
<p>Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?</p>
<p>You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. </p> <p>In your example, there isn't a really good way to spec "set_status" on the model without knowledge of what the observer is going to do to it. </p> <p>Therefore, I like to use the <a href="http://patmaddox.com/2007/11/23/better-rails-testing-decoupling-observers/" rel="noreferrer">"No Peeping Toms" plugin.</a> Given your code above and using the No Peeping Toms plugin, I would spec the model like this: </p> <pre><code>describe Person do it "should set status correctly" do @p = Person.new(:status =&gt; "foo") @p.set_status("bar") @p.save @p.status.should eql("bar") end end </code></pre> <p>You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this: </p> <pre><code>describe PersonObserver do it "should clobber the status field" do @p = mock_model(Person, :status =&gt; "foo") @obs = PersonObserver.instance @p.should_receive(:set_status).with("aha!") @obs.after_save end end </code></pre> <p>If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this:</p> <pre><code>describe Person do it "should register a status change with the person observer turned on" do Person.with_observers(:person_observer) do lambda { @p = Person.new; @p.save }.should change(@p, :status).to("aha!) end end end </code></pre> <p>99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. </p>
<p>no_peeping_toms is now a gem and can be found here: <a href="https://github.com/patmaddox/no-peeping-toms" rel="nofollow">https://github.com/patmaddox/no-peeping-toms</a></p>
5,301
<p>I am trying to setup a multi module SpringMVC appfuse applicaiton in Eclipse but it seems that I'm facing lots of errors in Eclipse after I import the project in Eclipse. Can anyone please help me with a step by step guideline showing the ideal way to setup such application in Eclipse?</p>
<p>Have you tried using maven eclipse plugin? You can just go to the project root folder (the one that contains your pom.xml file) and run "mvn eclipse:eclipse" from the command line.</p> <p>This will build project files for each of your modules and also create inter-dependencies. You can just treat your multi-module project like a workspace with multiple projects.</p> <p>Most of the errors that appear at load time, after mvn eclipse:eclipse are because of the repository variable. You can configure this by using "mvn -Declipse.workspace= eclipse:add-maven-repo".</p> <p>More info on maven eclipse plugin at <a href="http://maven.apache.org/plugins/maven-eclipse-plugin/" rel="nofollow noreferrer">http://maven.apache.org/plugins/maven-eclipse-plugin/</a>.</p> <p>Regards, Bogdan</p>
<p>What are the errors? The most common problem I can think of is library errors, in which case you have to edit the build path. </p>
17,558
<p>I'm new to Windows programming and after reading the Petzold book I wonder: </p> <p>is it still good practice to use the <code>TCHAR</code> type and the <code>_T()</code> function to declare strings or if I should just use the <code>wchar_t</code> and <code>L""</code> strings in new code?</p> <p>I will target only Windows 2000 and up and my code will be <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization" rel="noreferrer">i18n</a> from the start up.</p>
<p>The short answer: <strong>NO</strong>.</p> <p>Like all the others already wrote, a lot of programmers still use TCHARs and the corresponding functions. In my humble opinion <strong>the whole concept was a bad idea</strong>. <a href="http://en.wikipedia.org/wiki/UTF-16/UCS-2" rel="noreferrer">UTF-16</a> string processing is a lot different than simple ASCII/MBCS string processing. If you use the same algorithms/functions with both of them (this is what the TCHAR idea is based on!), you get very bad performance on the UTF-16 version if you are doing a little bit more than simple string concatenation (like parsing etc.). The main reason are <a href="http://msdn.microsoft.com/en-us/library/dd374069.aspx" rel="noreferrer">Surrogates</a>.</p> <p>With the sole exception when you <strong>really</strong> have to compile your application for a system which doesn't support Unicode I see no reason to use this baggage from the past in a new application.</p>
<p>Just adding to an old question:</p> <h1>NO</h1> <p>Go start a new CLR C++ project in VS2010. Microsoft themselves use <code>L"Hello World"</code>, 'nuff said.</p>
29,011
<p>I've seen the following code to enable double buffering on a winform:</p> <pre><code>// Activates double buffering this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); this.UpdateStyles(); </code></pre> <p>Is this different in any way from simply setting Form.DoubleBuffering = true?</p>
<p><code>Control.DoubleBuffering</code> performs</p> <pre><code>SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, value); </code></pre> <p>so your code sets <code>ControlStyles.UserPaint</code> as well (which probably has no effect at this point).</p>
<p>In .NET 1.<em>x</em>, there was no <code>DoubleBuffered</code> property on controls, so <code>SetStyle</code> was the only way to enable it. Code your see that uses <code>SetStyle</code> is probably either still around from 1.<em>x</em> days, or from developers who just haven't changed their habits since then.</p>
38,868
<p>I have to compute at libraries quite often these days, and have been having some issues with my U3 smart drive. Despite working on some computers, public libraries here restrict the execution of EXE files and disable AutoPlay, rendering my U3 apps useless. Is there a good way of getting around the restriction and getting something - anything - to run?</p>
<p>If you succeed in bypassing the restrictions and get caught, you may be banned entirely from using the computers at the library. I recommend living without the executables or finding a computer to use somewhere else.</p>
<p>I suspect that the restrictions are in place to prevent precisely that. Perhaps the restrictions are operating as intended.</p>
29,924
<p>suppose I declare a dynamic array like</p> <pre><code>int *dynArray = new int [1]; </code></pre> <p>which is initialized with an unknown amount of int values at some point.</p> <p>How would I iterate till the end of my array of unknown size?</p> <p>Also, if it read a blank space would its corresponding position in the array end up junked?</p> <h1>Copying Input From users post below:</h1> <p>Thing is:</p> <p>a) I'm not allowed to use STL (means: no )</p> <p>b) I want to decompose a string into its characters and store them. So far I wanted to use a function like this:</p> <pre><code> string breakLine (string line){ int lineSize = line.size(); const char *aux; aux=line.data(); int index=0; while (index&lt;=lineSize){ mySynonyms[index]=aux[index]; index++; } </code></pre> <p>I thought that the array aux would end up junked if there was a large blank space between the two numbers to be stored (apparently not). And I was wondering if there was a way to iterate till an undefined end in this type of array. Thanks for you answers.</p>
<p>No portable way of doing this. Either pass the size together with the array, or, better, use a standard container such as <code>std::vector</code></p>
<p>Use a vector, which has a vector.size() function that returns an integer and a vector.end() function that returns an iterator.</p>
49,534
<p>If I have data in the following format</p> <pre><code> id subid text 1 1 Hello 1 2 World 1 3 ! 2 1 B 2 2 B 2 3 Q </code></pre> <p>And would like it in this format:</p> <pre><code> id fold 1 HelloWorld! 2 BBQ </code></pre> <p>How could I accomplish it in T-SQL?</p>
<p>I would strongly suggest against that. That is the sort of thing that should be handled in your application layer.</p> <p>But... if you must:<br> <a href="https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/" rel="nofollow noreferrer">Concatenating Row Values in Transact-SQL</a></p>
<p>Wrap this in a function for a single execution...</p> <pre><code>DECLARE @returnValue varchar(4000) SELECT @returnValue = ISNULL(@returnValue + ', ' + myTable.text, myTable.text) FROM myTable RETURN @returnValue </code></pre> <p>For a small number of records this will work... any more than 5 or 10 is too many for a SQL function and it needs to be moved to app layer as others have suggested. </p>
35,277
<p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good Python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p>
<p>For the conditional statement, I would probably go with:</p> <pre><code>if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) </code></pre> <p>There's little need to use the inline <code>y if x else z</code> in this case, since the surrounding code is simple enough.</p>
<p>What about:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" if filecmp.cmp( local, config_file): to_copy = remote else: to_copy = local shutil.copyfile( to_copy, config_file ) </code></pre> <p>yikes, this open id screen name looks terrible.</p>
42,986
<p>I am having issues with a website that I am working on in which images and background-images fail to load in Internet Explorer 6.</p> <p>Here is an example of a page on which you might experience this issue:</p> <p><a href="http://www.infinitieurope.com/aboutinfiniti/environment/infiniti-environment.html" rel="nofollow noreferrer">Example Page</a></p> <p>So far I have looked at the following possible issues and pretty much ruled them out:</p> <ul> <li>XML/Extraneous data in the image files (google photoshop 7 internet explorer)</li> <li>Corrupt image files</li> </ul> <p>I have not ruled out invalid markup.</p> <p>I have noticed that there are validation errors in most of the pages where this problem has been reported and I am working on getting those fixed where appropriate.</p> <p>The behavior I see is that the page will load and all elements other than the background image render. There are no javascript errors thrown. When using Fiddler, no request for the image is made. If the browser is pointed directly to the background-image, the cache is cleared and then the browser is pointed back at the HTML page, the background-image will load inside the HTML page.</p> <p>Does anyone have any additional suggestions for ways to attack this issue?</p>
<p>Twice now I've had people have problems with photos not showing up, and it was because they were in an incorrect colorspace, using CMYK instead of RGB.</p>
<p>is it only ie6 and not ie7 too? IE is pretty strict with html sometimes, versus firefox lets you get away with more. Not sure if this helps, but I just debugged weird IE6/7 bugs by slowly taking away content. But if it's only intermittent, as in happens with the same code on and off, that's a really weird one.</p>
20,868
<p>I'm always wondering who should do it. In <a href="http://ruby-lang.org/" rel="nofollow noreferrer">Ruby</a>, we have the <a href="http://daemons.rubyforge.org/" rel="nofollow noreferrer">Daemons</a> library which allows Ruby scripts to daemonize themselves. And then, looking at <a href="http://god.rubyforge.org/" rel="nofollow noreferrer">God</a> (a process monitoring tool, similar to <a href="http://www.tildeslash.com/monit/" rel="nofollow noreferrer">monit</a>) page, I see that God can daemonize processes.</p> <p>Any definitive answer out there?</p>
<p>You probably cannot get a definitive answer, as we generally end up with both: the process has the ability to daemonize itself, and the process monitor has the ability to daemonize its children.</p> <p>Personally I prefer to have the process monitor or script do it, for a few reasons:<br> 1. if the process monitor wishes to closely follow its children to restart them if they die, it can choose not to daemonize them. A SIGCHLD will be delivered to the monitor when one of its child processes exits. In embedded systems we do this a lot.<br> 2. Typically when daemonizing, you also set the euid and egid. I prefer not to encode into every child process a knowledge of system-level policy like uids to use.<br> 3. It allows re-use of the same application as either a command line tool or a daemon (I freely admit that this rarely happens in practice).</p>
<p>I would say it is better for your script to do it. I don't know your process monitoring tool there, but I would think users could potentially use an alternative tool, which means that having the script do it would be preferable.</p> <p>If you can envision the script run in non-daemon fashion, I would add an option to the script to enable or disable daemonization.</p>
15,467
<p>For example if the user is currently running VS2008 then I want the value VS2008.</p>
<p>I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke:</p> <pre><code>// The GetForegroundWindow function returns a handle to the foreground window // (the window with which the user is currently working). [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); // The GetWindowThreadProcessId function retrieves the identifier of the thread // that created the specified window and, optionally, the identifier of the // process that created the window. [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); // Returns the name of the process owning the foreground window. private string GetForegroundProcessName() { IntPtr hwnd = GetForegroundWindow(); // The foreground window can be NULL in certain circumstances, // such as when a window is losing activation. if (hwnd == null) return "Unknown"; uint pid; GetWindowThreadProcessId(hwnd, out pid); foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) { if (p.Id == pid) return p.ProcessName; } return "Unknown"; } </code></pre>
<pre><code>using System; using System.Windows; using System.Windows.Forms; using System.Runtime.InteropServices; namespace FGHook { class ForegroundTracker { // Delegate and imports from pinvoke.net: delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime); [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hWinEventHook); // Constants from winuser.h const uint EVENT_SYSTEM_FOREGROUND = 3; const uint WINEVENT_OUTOFCONTEXT = 0; // Need to ensure delegate is not collected while we're using it, // storing it in a class field is simplest way to do this. static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc); public static void Main() { // Listen for foreground changes across all processes/threads on current desktop... IntPtr hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT); // MessageBox provides the necessary mesage loop that SetWinEventHook requires. MessageBox.Show("Tracking focus, close message box to exit."); UnhookWinEvent(hhook); } static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { Console.WriteLine("Foreground changed to {0:x8}", hwnd.ToInt32()); //Console.WriteLine("ObjectID changed to {0:x8}", idObject); //Console.WriteLine("ChildID changed to {0:x8}", idChild); GetForegroundProcessName(); } static void GetForegroundProcessName() { IntPtr hwnd = GetForegroundWindow(); // The foreground window can be NULL in certain circumstances, // such as when a window is losing activation. if (hwnd == null) return; uint pid; GetWindowThreadProcessId(hwnd, out pid); foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) { if (p.Id == pid) { Console.WriteLine("Pid is: {0}",pid); Console.WriteLine("Process name is {0}",p.ProcessName); return; } //return; } Console.WriteLine("Unknown"); } } } </code></pre>
12,276
<p>I usually, almost without thinking anymore, use forward declarations so that I won't have to include headers. Something along this example:</p> <pre><code>//----------------------- // foo.h //----------------------- class foo { foo(); ~foo(); }; //----------------------- // bar.h //----------------------- class foo; // forward declaration class bar { bar(); ~bar(); foo* foo_pointer; }; </code></pre> <p>Some developers like to use this method to avoid problems with inclusion circles. I rather use it to minimize the overhead in extensive inclusion hierarchies, an important part of physical design (for larger projects in particular).</p> <p>However, in some cases I really like to declare members as normal objects instead of pointers to benefit from the automatic construction/destruction mechanism. This leads to the problem that forward declarations can't be used anymore, since the compiler needs the class definition in such case, eg:</p> <pre><code>//----------------------- // foo.h //----------------------- class foo { foo(); ~foo(); }; //----------------------- // bar.h //----------------------- class foo; // Not enough given the way we declare "foo_object".. #include "foo.h" // ..instead this is required class bar { bar(); ~bar(); foo foo_object; }; </code></pre> <p>So, I would be happy if anyone knows an alternative language construct which can be used here so that I can declare "foo_object" as shown in the example, but without including its header.</p> <p>Regards</p> <p>/Robert</p>
<p>You can't. The compiler needs to know the size of the object when declaring the class.</p> <p>References are an alternative, although they have to be instantiated at construction time, so it's not always feasible.</p> <p>Another alternative are smart pointers, but I suppose that's technically still a pointer.</p> <p>It would be good to know why you don't want to use a pointer to suggest some other construct though...</p>
<p>If you are able to use a reference, you can retain the same use syntax. However, your reference has to be initialised straight away in the constructor, so your ctor absolutely must be defined out-of-line. (You will also need to free the object in the destructor too.)</p> <pre><code>// bar.h class foo; class bar { foo&amp; foo_; public: bar(); ~bar(); }; // bar.cc bar::bar() : foo_(*new foo) { // ... } bar::~bar() { // ... delete &amp;foo_; } </code></pre> <p>Your mileage may vary. :-)</p>
39,346
<p>I have a .Net 2.0/3.5 WebApplication.</p> <p>I want to be able to take money over the internet for my service.</p> <p>Each of my customers will have an AccountNo.</p> <p>I wish to offer several products each of which will have fixed price.</p> <p>I need for my customer to login to my system and elect to pay me money for a product of their choice and for my app to become aware when this is complete so that I may adjust their account to reflect this.</p> <p>What is the simplest (least complicated coding) way to take their money?</p> <p>Paypal, NoChex, Google checkout, Something else ?</p>
<p><a href="https://www.paypal.com/" rel="nofollow noreferrer">Paypal</a> is fairly straight forward and <strong>secure</strong>.</p>
<p>google and yahoo both offer decent service, and they don't require your customers to create an account.</p>
24,040
<p>Whenever I alter (or even just resave without altering) a Perl file, it completely takes down our backend. I have no idea what the problem could be. Permissions are correct. Encoding is correct. Encoding is UTF-8. Transfer mode was ASCII.</p> <p>I might not deal with Perl too much but I have no idea what the problem could be. The network admin hosting our website has no idea what the problem could be. </p> <p>Text editors I tried: Dreamweaver, TextMate, Vim Operating systems I tried: Mac OS X, Linux (Ubuntu) FTP clients I tried: Transmit (Mac), Filezilla (Linux (Ubuntu))</p> <p>It's not that it's bad code, I even tried to open and solely save and my backend still goes down. </p> <p>The network admin told me that he ran the files through a dos2unix converter and it worked immediately. I of course tried this and it did not, more so it wouldn't make any sense, since I tried this in some of the most respected editors and I don't think it would make such drastic changes to the file type without any user input. (when I say respected editors Dreamweaver is not included in that sentiment). </p> <p>I personally think it is some sort of server-side issue because I have crossed my t's and dotted my i's in regards to any possible client side issue but I have tried everything. Any opinions as to what the root of this problem is, and any possible solutions? Thanks in advance.</p>
<p>Try setting binary mode in your FTP client. That will allow you to experiment with different line endings (dos2unix) on the client side, without worrying about them being translated during transfer.</p>
<p>Response to rebra: No frameworks are used, and I don't know what kind of server this is on. This is basically a one man project on a shared host which was pretty horribly maintained and I'm trying to clean house.</p> <p>Yeah that does make sense and I asked the server people about that, one of my first questions actually, but even if that is the case, I can't reboot via Plesk (kind of like cPanel). But thanks for that, you put into technical words/explanation what I was thinking of the whole time. </p>
43,061
<p>Is there any way in SSRS2008 to deploy multiple instances of the ReportServer running separate code sets?</p> <p>I'm developing a very specific deployment of reporting services where I have a number of custom extensions plugged in. But, my company typically deploys multiple versions of a release at once on the same server. I'm at a little bit of a loss of a good way to do this with reporting services.</p> <p>I know that I have a few alternatives:</p> <ul> <li>Run multiple instances of Reporting Services with different code sets</li> </ul> <p>The downside to this is that it's a little bit of a headache to upgrade and I'd rather not have multiple instances of the reporting databases. I'm not sure if they would play well together if they were targeting the same databases.</p> <ul> <li>Invoke/include the version specific DLLs on demand by reading from an HTTPRequest variable. (Assembly.LoadFile)</li> </ul> <p>I have a feeling that this could have performance issues and it also sounds like a potential debugging nightmare. I have also not used Assembly.LoadFile before and I'm unsure of how much code I'd have to write that was unversioned to control the versioning system.</p> <p>Anyone out there have experience with any of this?</p>
<p>You can install multiple RS front ends onto one DB backend.</p> <p>It works well. We use it to have 2 primary RS boxes (load balanced) with 3rd BCP/DR hot standby box. They are all in the farm.</p> <p>You can have multiple instances on the same box too.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms159114(SQL.90).aspx" rel="nofollow noreferrer">How to: Configure a Report Server Scale-Out Deployment (Reporting Services Configuration)</a></p>
<p>FWIW I have been running two separate report server installations against the same databases without issues. The volumes are fairly low.</p>
15,261
<p>I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:</p> <pre><code>WARN( "Danger Will Robinson! There are " + boost::lexical_cast&lt;string&gt;(minutes) + " minutes of oxygen left!" ); </code></pre> <p>I'm using an inline function for WARN, but I'm curious as to how much optimization is going on behind the scenes -- evaluation of the arguments throughout the entire program would be costly. The <code>WARN</code> function goes something like this:</p> <pre><code>bool WARNINGS_ENABLED = false; inline void WARN(const string &amp;message) { if (!WARNINGS_ENABLED) { return; } // ... } </code></pre> <p>Given that constructing the string argument has no side-effects, will the compiler optimize it out? Is a certain level of optimization required (<code>-Ox</code> in <code>g++</code> for some <code>x</code>)?</p>
<p>If you need to be able to selectively enable and disable the warnings at run-time, the compiler will <em>not</em> be able to optimize out the call.</p> <p>What you need is to rename your <em>function</em> to <code>WARN2</code> and add a macro something like:</p> <pre><code>#define WARN(s) do {if (WARNINGS_ENABLED) WARN2(s);} while (false) </code></pre> <p>This will prevent the evaluation of s at run-time unless you have warnings enabled.</p> <p>The do-while stuff is a trick that allows it to be used anywhere in the code (naked statement, statement within a braced if-block, statement within an unbraced if-block, braced and unbraced while statements and so on).</p>
<p>Can't you just define the whole thing out using the preprocessor?</p> <pre><code>void inline void LogWarning(const string &amp;message) { //Warning } #ifdef WARNINGS_ENABLED #define WARN(a) LogWarning(a) #else #define WARN(a) #endif </code></pre> <p>This is just how the ASSERT() macro works. All the code inside the brackets in WARN does not even make it through the preprocessor to the compiler. That means you can do other stuff like</p> <pre><code>#ifdef WARNINGS_ENABLED // Extra setup for warning #endif //.... WARN(uses setup variables) </code></pre> <p>And it will compile both ways. </p> <p>As for getting the optimiser to realise that there are no side-effects in the brackets, you can put some pretty complex statements in there (i.e high level string manipulation) that are hard to prove either way.</p>
35,791
<p>I am connecting to a MySQL DB trough a terminal who only have a program with an ODBC connection to a MySQL DB. I can put querys in the program, but not access MySQL directly.</p> <p>I there a way to query the DB to obtain the list of fields in a table other than</p> <pre><code>select * from table </code></pre> <p>??</p> <p>(don't know why but the select returns a error)</p>
<pre><code>describe *tablename* </code></pre>
<p>This:</p> <pre><code>SHOW COLUMNS FROM Tablename </code></pre> <p>lists the fields in a table and their properties (data type, whether null values are allowed, whether the field is a primary key, the default value if one has been set, etc.)</p>
39,796
<p>We have a weird intermittent problem with saving from Word 2007 to our SharePoint 2007 (MOSS) document libraries that gives a dialog box that never goes away - it is titled "Content Types" and the message "Getting list of available content types..." with a green progress-type bar that keeps scrolling. It happens a lot on our training server (self-contained virtual machine with separate SQL Server) but more worryingly is happening on our live production server (which is in a medium server farm arrangement - web application server, another server for search/indexing and a SQL Server). All servers in the farms are 64 bit.</p> <p>It is strangely random - the user has to kill Word 2007, then they recover their document and try to save to the same document library and it saves without a problem. </p> <p>It happens more on the training server than the live server. The live web application server rarely goes over 20% CPU (usually around 5%) and memory peaks at 2Gb of the available 4Gb (usually at 1.5Gb) so I don't think its a resources issue. </p> <p>The document libraries are customised and deployed using Features in a Solution. The only content type in them is the standard Documents content type. </p> <p><strong>Update</strong> We opened this with Microsoft as a support issue and it is a known issue that is targeted to be addressed in a Cumulative Update hotfix package for SharePoint in February 2009.</p> <p><em>Edit</em> Copied the above response to an answer so this question could be flagged as answered.</p>
<p>sudo vim /etc/php5/apache2/php.ini</p> <h1>Add time zone</h1> <p>date.timezone=&quot;Europe/London&quot;</p> <p>restart apache2 /etc/init.d/apache2 restart</p>
<p>Try and set your timezone explicitly in the <code>httpd.conf</code>:</p> <pre><code>SetEnv TZ GMT+2 </code></pre>
29,958
<p>I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.</p> <p>When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.</p> <p>The script is run just like this:</p> <pre><code>Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s </code></pre> <p>1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?</p> <p>2) Any ideas of how to solve it?</p> <p>Thanks,</p> <p>Luís Fernando</p>
<p>After a while I finally discovered why the session was being terminated. You must wait for something at the end or the script just terminates. But you must be sure that the string you are waiting for is not something that will be printed until the code finishes.</p> <p>So, I've just changed the program to print "Operation finished" only at the end, and then put the line:</p> <pre><code> waitfor "Operation finished" terminate </code></pre> <p>Now the program doesn't get interrupted.</p> <p>Cheers,</p> <p>Luís</p>
<p>Is there a chance it's not a timeout, but some other problem? Possibly a runtime error that's not being trapped/logged?</p> <p>The main difference between running from the interactive console and as a script is that when you run interactively you're in Programmer Mode, but in the script you're in User Mode. I can't think of any reason off-hand why that would matter, but possibly your code is sensitive to that.</p> <p>Here's something to try: Write a very simple script that does nothing except write out a character every now and then. Maybe something like this:</p> <p>F I=1:1:360 H 10 W "." ;Write a dot every 10 seconds for 1 hour</p> <p>If that gets the timeout too then you know it's the terminal, not your code.</p>
24,181
<p>There are (at least) two ways that technical debts make their way into projects. The first is by conscious decision. Some problems just are not worth tackling up front, so they are consciously allowed to accumulate as technical debt. The second is by ignorance. The people working on the project don't know or don't realize that they are incurring a technical debt. This question deals with the second. Are there technical debts that you let into your project that would have been trivial to keep out ("If I had only known...") but once they were embedded in the project, they became dramatically more costly? </p>
<p>One example of this is running a database in a mode that does not support Unicode. It works right up until the time that you are forced to support Unicode strings in your database. The migration path is non-trivial, depending on your database. </p> <p>For example, SQL Server has a fixed maximum row length in bytes, so when you convert your columns to Unicode strings (NCHAR, NVARCHAR, etc.) there may not be enough room in the table to hold the data that you already have. Now, your migration code must make a decision about truncation or you must change your table layout entirely. Either way, it's much more work than just starting with all Unicode strings.</p>
<p>Not having a cohesive design up front tends to lead to it. You can overcome it to a degree if you take the time to refactor frequently, but most people keep bashing away at an overall design that does not match their changing requirements. This may be a more general answer that what your looking for, but does tend to be one of the more popular causes of technical debt.</p>
39,943