input
stringlengths
51
42.3k
output
stringlengths
18
55k
Any Monit like equivalents for windows OS? <p>I've seen the question asked "can you run Monit on Windows?", and unless you want to use a VM, the answer appears to be no.</p> <p>So...are there any small footprint monit-like applications actually for Windows OS's? What I'm looking for is not only monitoring (of which there are hundreds of apps), but also the ability to execute a script or restart a service. For example, monitor a web page, and restart Tomcat if that page becomes unresponsive (can't just watch the service, because the service is still running but not responding properly).</p> <p>This is for a small application, not a large application, so the heavyweight/expensive solutions aren't desired.</p>
<p>I didn't find anything out there that fit my needs, so I learned a little Powershell scripting and rolled a solution that should be useful to others as well. Assuming a Windows platform (otherwise use monit!), Powershell is really powerful and easy. </p> <p><strong>sample-monitor.ps1 script:</strong></p> <pre><code>$webClient = new-object System.Net.WebClient ################################################### # BEGIN USER-EDITABLE VARIABLES # the URL to ping $HeartbeatUrl = "http://someplace.com/somepage/" # the response string to look for that indicates things are working ok $SuccessResponseString = "Some Text" # the name of the windows service to restart (the service name, not the display name) $ServiceName = "Tomcat6" # the log file used for monitoring output $LogFile = "c:\temp\heartbeat.log" # used to indicate that the service has failed since the last time we checked. $FailureLogFile = "c:\temp\failure.log" # END USER-EDITABLE VARIABLES ################################################### # create the log file if it doesn't already exist. if (!(Test-Path $LogFile)) { New-Item $LogFile -type file } $startTime = get-date $output = $webClient.DownloadString($HeartbeatUrl) $endTime = get-date if ($output -like "*" + $SuccessResponseString + "*") { # uncomment the below line if you want positive confirmation #"Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" &gt;&gt; $LogFile # remove the FailureLog if it exists to indicate we're in good shape. if (Test-Path $FailureLogFile) { Remove-Item $FailureLogFile } } else { "Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" &gt;&gt; $LogFile # restart the service if this is the first time it's failed since the last successful check. if (!(Test-Path $FailureLogFile)) { New-Item $FailureLogFile -type file "Initial failure:" + $startTime.DateTime &gt;&gt; $FailureLogFile Restart-Service $ServiceName } } </code></pre> <p>The only logic in this script is that it will only try to restart the service once after an initial failure. This is to prevent a situation where a service takes a while to restart, and while it's restarting, the monitor keeps seeing the failure and restarts again (bad infinite loop). Otherwise you can do just about anything, like add email notifications, or do more than just restart a service.</p> <p>This script will execute once, which means you'll need to control its repetition externally. You could put it in an infinite loop right in the script, but that seems a little flaky. I used windows Task Scheduler, executing it like so: Program: Powershell.exe arguments: -command "C:\projects\foo\scripts\monitor.ps1" -noprofile Start In: C:\projects\foo\scripts</p> <p>You could also use a more robust scheduler like VisualCron, plug it into a windows service, or via an application server scheduler like Quart.NET. In my case the task scheduler works fine. </p>
How do you make configuration-specific C# build events in VS2008 <p>In vs2008, C# build events are configuration-specific. </p> <p>Looking for ideas on how to make my build event run only when doing a Release build.</p> <p>Ideas?</p>
<p>ok, along Brian's line, I'm doing this:</p> <pre><code>if "$(ConfigurationName)" == "Release" do_something </code></pre> <p>and it appears to work</p>
iPhone SDK - UITextField with + Button for Contacts <p><br /> In some applications like Mail, when you have a UITextField, there is a little + button to the right. When you tap it, a modal view controller comes up which you can select a phone number, address, etc from, and it will appear in the text field. I was wondering how to implement this in my own app. Thanks,<br /> Isaac</p>
<p>You can do this by</p> <pre><code>txtFldObj.rightView = [UIButton buttonWithType:UIButtonTypeContactAdd]; txtFldObj.rightViewMode=UITextFieldViewModeAlways; </code></pre> <p>you can also refer to this <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/42926-add-button-right-uitextfield.html" rel="nofollow">trick</a> also</p>
c++ class why need main? <p>Hello I'm writing a little project in c++ where I would like to have some classes that does some work, I wrote the interfaces and the implementation of the classes.</p> <p>The thing that surprises me is that I cannot have a simple class without a main(), I would like to have a class that once instantiated, It's methods can be called, do things, but I don't need (nor want) a main() in the class implementation. Here's an example I have in my head of what I'd like to have:</p> <p>file animal.h:</p> <pre><code>class animal { public: animal(); ~animal(); public: int method1(int arg1); private: int var1; }; </code></pre> <p>file animal.cpp:</p> <pre><code>#include "animal.h" animal::animal(){...} animal::~animal(){...} int animal::method1(int arg1){return var1;} } </code></pre> <p>And I would like to call the animal class form another file and have it work, something like this: file app.cpp:</p> <pre><code>#include &lt;neededlib&gt; #include "animal.h" int main() { animal dog; cout &lt;&lt; dog.method1(42); return 0; } </code></pre> <p>But compiler give me </p> <pre><code>/usr/lib/gcc/i686-pc-linux-gnu/4.3.3/../../../crt1.o: In function _start: "(.text+0x18): undefined reference to `main`" collect2: ld returned 1 exit status </code></pre> <p>for animal.cpp, but I don't need a main there, or do I need it?</p> <p>Where Am I wrong? </p>
<blockquote> <p>but I don't need (nor want) a main() in the class implementation.</p> </blockquote> <p>The function <code>main</code> is your entry-point. That is where execution begins. You need to have one and only one such function.</p> <blockquote> <p>But compiler give me "undefined reference to main" for animal.cpp, but I don't need a main there, or do I need it?</p> </blockquote> <p>Now, your problem looks like you have not <em>linked</em> the compiled forms of <code>app.cpp</code> and <code>animal.cpp</code>. </p> <blockquote> <p>I'm not so strong in Makefiles, I used something like g++ animal.h -o animal and g++ animal.cpp but it gives me the error above</p> </blockquote> <p>You don't compile headers. So don't use: <code>g++ animal.h</code></p> <p>When you compiled the animal.cpp separately, g++ created an object file. You will also need to compile the <code>app.cpp</code> because you <em>do need</em> the <code>main</code>. Once you compile the <code>app.cpp</code> file you will have to link it with the <code>animal</code> object file created earlier. But if these did not get linked in, specially, the file containing the <code>main</code> function you will hit the error you are getting now.</p> <p>However, <code>g++</code> takes care of what I have described above. Try something like this:</p> <pre><code>g++ animal.cpp app.cpp -o test </code></pre> <p>This will create an executable called <code>test</code> and you can run your application using:</p> <pre><code>./test </code></pre>
How to set up Java to use user specific certificates for Eclipse? <p>I can't believe I'm the only person to run up against this problem. I've been googling for hours and have not had any luck. The Java security documentation doesn't seem to address PKCS12 certificates thoroughly.</p> <p>I am trying to setup Java for user specific PKCS12 certificates. Among other things, this will be used so that, in Eclipse, I can access a Trac server that is authenticated via certificates. I am using the Trac Mylyn integration plugin for eclipse.</p> <p>Here is the setup:</p> <ul> <li>user home directories are at /home</li> <li>multiuser mount at /central</li> <li>each user has a personal certificate at: ~/user.p12</li> <li>password for personal certificates is: pass1234</li> <li>the users password is stored in a 0400 file at ~/password.txt</li> <li>a read-only trust store for the ca is at: /central/ca.jks</li> <li>no password for the truststore</li> <li>JDK 1.6 installed at /central/jdk_1.6.0</li> <li>Eclipse 3.4 installed at /central/eclipse_3.4.0</li> <li>JAVA_HOME=/central/jdk_1.6.0</li> <li>JAVA_HOME is set to the JDK location because Eclipse needs this</li> <li>ECLIPSE_HOME=/central/eclipse_3.4.0</li> <li>JRE lives at $JAVA_HOME/jre</li> <li>each user has a ~/.java.policy file</li> <li>there is a trac server running at https://trac.internal/trac</li> <li>the trac server authenticates using certificates</li> </ul> <p>Now, I want to be able to have each user simply modify some file that they own (like the ~/.java.policy file, for example), and be able to launch the central Eclipse application and access the Trac repository. Seems simple enough.</p> <p>Right now, the only way I can get this to work is to edit the $ECLIPSE_HOME/eclipse.ini file and add </p> <pre><code>-Djavax.net.ssl.keyStore="/home/user/user.p12" -Djavax.net.ssl.keyStoreType="PKCS12" -Djavax.net.ssl.keyStorePassword="pass1234" -Djavax.net.ssl.trustStore="/central/ca.jks" </code></pre> <p>Ok, that works, but there are two problems with it:</p> <ul> <li>Each user has to have their own ecipse install. (or can eclipse read that from a user file?)</li> <li>It is Eclipse specific, I'd ultimately like to have this as a Java configuration.</li> </ul> <p>Also, I remember from some time back that you can edit the $JAVA_HOME/jre/lib/security/java.security file and add</p> <pre><code>keystore=/home/user/user.p12 keystore.type=PKCS12 keystore.password=pass1234 truststore=/central/ca.jks </code></pre> <p>But Eclipse doesn't seem to pick that up. Could it be because my JAVA_HOME points to a JDK, and not the JDK's nested JRE?</p> <p>I've seen the <a href="http://download.java.net/jdk7/docs/technotes/guides/security/p11guide.html">Java PKCS#11 Reference</a> that references the following properties: keyStoreURL="NONE" keyStoreType="PKCS11" keyStorePasswordURL=some_pin_url </p> <p>There was another reference I saw that said you could edit the ~/.java.policy file to include:</p> <pre><code>keyStore "file:///home/user/user.p12", "PKCS12", "SunJSSE"; keyStorePasswordUrl "file:///home/user/password.txt"; </code></pre> <p>But that doesn't get picked up either. Maybe it actually does work and its not getting read for the same reason the java.security file doesn't work, or maybe it just doesn't work at all.</p> <p>Some system properties I've seen:</p> <pre><code>javax.net.ssl.keyStore="/home/user/user.p12" javax.net.ssl.keyStoreType="PKCS12" javax.net.ssl.keyStorePassword="password" javax.net.ssl.keyStoreProvider="SunJSSE" javax.net.ssl.trustStore="/home/user/ca.jks" javax.net.ssl.trustStoreType="JKS" javax.net.ssl.trustStorePassword="" javax.net.ssl.trustStoreProvider="Sun" </code></pre> <p>So, right now, I guess I'm stuck with having each user to have their own Eclipse intall. I know it sounds like a complicated setup, but this shouldn't really have anything to do with Eclipse as far as the certificate setup... its really a Java setup for user specific certificates.</p> <p>Any ideas?</p>
<p>Use a <a href="http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/multi_user_installs.html" rel="nofollow">user-specific configuration</a>.</p> <blockquote> <p>Setting the private configuration area location</p> <p>The default location for a private configuration area is:</p> <p>user-home-dir/.eclipse/&lt;product-id&gt;_&lt;product-version&gt;/configuration</p> <p>The user home dir is determined by the user.home Java system property. The product id and version are obtained from the product marker file .eclipseproduct under the Eclipse install.</p> </blockquote>
How to Best Handle Authentication Via the URL in PHP <p>I need to be able to send users a link that contains an encrypted value which is used to authenticate the user when they visit the link. </p> <p>The current process uses a salt and roughly 40 character unique hash which is then encrypted and base64 encoded so that it can be safely be transported via email and in theory come back safely through the URL.</p> <p>However, as this is my first attempt at doing something like this, I failed to consider the effect of slashes in the encrypted value. This causes the value to be truncated when I pull it from the URL which obviously won't work when I try to decrypt it.</p> <p>How is this generally accomplished? Links to tutorials, etc. are always appreciated.</p>
<p>I think your method is good overall, in fact it could probably be considered overkill already. For the issues with slashes (and potentially other problem characters) in the URL, just make sure that you use <a href="http://php.net/urlencode" rel="nofollow"><code>urlencode()</code></a> (and then subsequently <a href="http://php.net/urldecode" rel="nofollow"><code>urldecode()</code></a> in the verification page) on the verification token.</p>
.NET Packing Controls? <p>I'm taskd with developing a packing algorithm for parts bought from our online store. Is there a widget or control that is open-source or for sale that takes in a list of products (with dimensions / weight) and a list of possible packing boxes (with max dimensions and weight) and returns the best possible arrangement? I find it hard to believe that the million of developers before me haven't come up with something, but if not, it's off to the lab to get some work done.</p> <p>Thanks Josh</p>
<p>It seems to me that you're looking for an implementation of the <a href="http://en.wikipedia.org/wiki/Bin%5Fpacking%5Fproblem" rel="nofollow">Bin Packing Problem</a>. It's an NP Hard problem, so you'll not find any fast-and-correct algorithm. I did a quick search and couldn't find any components that even use a heuristic for this, but found plenty of papers describing heuristics for getting approximations of the answer. Good luck!</p>
What would you change in my code for best practices/maintenance? <p>I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.</p> <pre><code>function _setAccountStatus($Username, $AccountStatus) { if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) { // TODO: throw error here. } $c1 = new Criteria(); $c1-&gt;add(UsersPeer::USERNAME,$Username); $rs = UsersPeer::doSelect($c1); if (count($rs) &gt; 0) { $UserRow = array_pop($rs); $UserRow-&gt;setAccountStatus($AccountStatus); try { $UserRow-&gt;save(); } catch ( PropelException $e ) { return false; } return true; } return false; } </code></pre>
<p>I would use the <a href="http://us.php.net/manual/en/function.empty.php" rel="nofollow">empty()</a> instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.</p> <p>$user = userManager->getUser($username); $user->setAccountStatus($accountStatus); $userManager->saveUser($user);</p>
Weird jQuery behavior - slide() <p>if you go to this page and hit one of the left dropdowns - <a href="http://ryancoughlin.com/hp/index.php?c=about" rel="nofollow">http://ryancoughlin.com/hp/index.php?c=about</a> - it almost looks like it is glitching/bumping, once it gets to the bottom or rides back up top.</p> <p>Is it possible to fix this? Or is this how it behaves in jQuery?</p> <p>CODE:</p> <pre><code>$(".menu-header").click(function() { $(this).next().toggle('slow'); return false; }).next().hide(); </code></pre>
<p>In your CSS, change</p> <pre><code>#left ul li{ font-size:.7em; margin:5px 0; } </code></pre> <p>to</p> <pre><code>#left ul li{ font-size:.7em; padding:2px 0 3px 0; } </code></pre> <p>The issue is that your margins are collapsing with the margins of the <code>h2</code> at the beginning and end of the animation, but not during the animation, because <code>overflow</code> of the <code>ul</code> is not <code>visible</code>*, preventing the collapsing. The lack of collapsing increases the effective size of the <code>ul</code>.</p> <p>*<a href="http://www.w3.org/TR/CSS21/box.html#collapsing-margins" rel="nofollow">W3 on the box model and margin collapsing</a>:</p> <blockquote> <p>Vertical margins of elements with 'overflow' other than 'visible' do not collapse with their in-flow children.</p> </blockquote>
Google App Engine on Silverlight <p>are there any good examples on how to use Google App Engine from Silverlight, preferably without writing custom webservices?</p> <p>Cheers</p> <p>Nik</p>
<p>Here is my approach based heavily on <a href="http://www.informit.com/articles/article.aspx?p=1354698" rel="nofollow">Scott Seely's post</a> Simply passes XML around, .xap is also served by GAE. I only just got this working yesterday so it is still work in progress.</p> <p><strong>Google:</strong></p> <p>app.yaml</p> <pre><code> application: wowbosscards version: 1 runtime: python api_version: 1 handlers: - url: /WowBossCards.html static_files: WowBossCards.html upload: WowBossCards.html mime_type: text/html - url: /clientaccesspolicy.xml static_files: clientaccesspolicy.xml upload: clientaccesspolicy.xml mime_type: text/xml - url: /WowBossCards.xap static_files: WowBossCards.xap upload: WowBossCards.xap mime_type: application/x-silverlight-app - url: .* script: wowbosscards.py </code></pre> <p>wowbosscards.py</p> <pre><code>#!/usr/bin/env python import cgi import datetime import wsgiref.handlers import os import logging import string import urllib from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template class Xml(db.Model): xmlContent = db.TextProperty() date = db.DateTimeProperty(auto_now_add=True) class XmlCrud(webapp.RequestHandler): def get(self, xmlType): xmlKey = string.capitalize(xmlType) xml = Xml.get_by_key_name(xmlKey) self.response.headers['Content-Type'] = "application/xml" self.response.out.write(xml.xmlContent) def post(self, xmlType): logging.debug("XmlCrud POST") xmlKey = string.capitalize(xmlType) xml = Xml.get_by_key_name(xmlKey) if len(self.request.get('content')) &gt; 0 : xml.xmlContent = self.request.get('content') else: xml.xmlContent = self.request.body xml.put() self.redirect('/upload/' + xmlType) def main(): Xml.get_or_insert("Bosses", xmlContent="&lt;a&gt;Bosses go here&lt;/a&gt;") Xml.get_or_insert("Dungeons", xmlContent="&lt;a&gt;Dungeons go here&lt;/a&gt;") application = webapp.WSGIApplication([ (r'/xml/(.*)', XmlCrud), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() </code></pre> <p><strong>Silverlight:</strong></p> <pre><code>private class RequestExtended { public VoidCall CallBack; public WebRequest Request; public Uri Host; public RequestExtended(WebRequest request, VoidCall callBack, Uri host) { Request = request; CallBack = callBack; Host = host; } } public static void ImportFromGoogle(Uri host, VoidCall callBack) { try { if (host.Host == "localhost") { host = new Uri(host.Scheme + @"://" + host.Host + ":8080"); } var bossesCrud = new Uri(host, "/xml/bosses"); var bossesRequest = WebRequest.Create(bossesCrud); bossesRequest.BeginGetResponse(BossesResponse, new RequestExtended(bossesRequest, callBack, host)); } catch (Exception ex) { } } public static void BossesResponse(IAsyncResult result) { var requestExtended = result.AsyncState as RequestExtended; try { WebResponse response = requestExtended.Request.EndGetResponse(result); Stream responseStream = response.GetResponseStream(); byte[] bytes = new byte[response.ContentLength]; responseStream.Read(bytes, 0, bytes.Length); responseStream.Close(); var enc = new System.Text.UTF8Encoding(); string xml = enc.GetString(bytes, 0, bytes.Length); bosses = GetCollectionFromXmlString&lt;BossCollection&gt;(xml); if (requestExtended.CallBack != null) requestExtended.CallBack(); } catch (WebException we) { HttpWebResponse response = (HttpWebResponse)we.Response; response.Close(); } catch (Exception e) { } } public static void SaveBossesToGoogle(Uri host) { if (host.Host == "localhost") { host = new Uri(host.Scheme + @"://" + host.Host + ":8080"); } var bossesCrud = new Uri(host, "/xml/bosses"); var request = WebRequest.Create(bossesCrud); request.Method = "POST"; request.ContentType = "text/xml"; //"application/x-www-form-urlencoded"; request.BeginGetRequestStream(GetSaveBossesRequestStreamCallback, new RequestExtended(request, null, host)); } static void GetSaveBossesRequestStreamCallback(IAsyncResult result) { var requestExtended = result.AsyncState as RequestExtended; try { Stream stream = requestExtended.Request.EndGetRequestStream(result); var xmlSerializer = new XmlSerializer(typeof(BossCollection)); var xmlText = new StringBuilder(); using (TextWriter textWriter = new StringWriter(xmlText)) { xmlSerializer.Serialize(textWriter, Store.Bosses); textWriter.Close(); } var enc = new System.Text.UTF8Encoding(); var bytes = enc.GetBytes(xmlText.ToString()); stream.Write(bytes, 0, bytes.Length); stream.Close(); requestExtended.Request.BeginGetResponse(SaveResponse, requestExtended); } catch (WebException we) { HttpWebResponse response = (HttpWebResponse)we.Response; response.Close(); } } static void SaveResponse(IAsyncResult result) { var requestExtended = result.AsyncState as RequestExtended; try { WebResponse response = requestExtended.Request.EndGetResponse(result); if (requestExtended.CallBack != null) requestExtended.CallBack(); } catch (WebException we) { HttpWebResponse response = (HttpWebResponse)we.Response; response.Close(); } } </code></pre>
Can I pass C++ strings into a method in the style of a stream? <p>I'd like to do this:</p> <pre><code>MyClass mc = MyClass("Some string" &lt;&lt; anotherString); </code></pre> <p>Thanks for your answers, I have decided to re-write this question based on what you've told me, as it's gotten a little messy. Eventually, I read <a href="http://stackoverflow.com/questions/303562/c-format-macro-inline-ostringstream">C++ format macro / inline ostringstream</a>, and decided to use a macro, as it's not really possible to do this using a constructor. Some answers my no longer be relevant.</p> <p>Now, what I can actually, do is:</p> <pre><code>MY_CLASS("Some string" &lt;&lt; anotherString &lt;&lt; " more string!"); </code></pre> <p>Using this macro:</p> <pre><code>#include &lt;sstream&gt; #define MY_CLASS(stream) \ MyClass( ( dynamic_cast&lt;std::ostringstream &amp;&gt; ( \ std::ostringstream() . seekp( 0, std::ios_base::cur ) &lt;&lt; stream ) \ ) . str() ) </code></pre> <p>Where the MyClass constructor takes a string:</p> <pre><code>MyClass::MyClass(string s) { /* ... */ } </code></pre>
<p>redesign your solution. if your c-tor needed string it should accept string.<br /> also in this and similar cases will better if your constructor will accept const reference.</p> <pre><code>no matching function for call to ‘MyClass(std::basic_ostream &lt;..&gt;&amp;) </code></pre> <p>error happened because operator&lt;&lt; defined for and returns std::basic_ostream not std::stringstream object. ofcourse you could use </p> <pre><code>dynamic_cast&lt; const std::stringstream&amp; &gt;( s &lt;&lt; "hello" &lt;&lt; "world" ) </code></pre> <p>but your team lead could fire you for this code:)</p> <p><strong>BTW:</strong> </p> <pre><code>MyClass mc = MyClass("Some string" &lt;&lt; anotherString); </code></pre> <p>could be rewriten as</p> <pre><code>MyClass mc("Some string" &lt;&lt; anotherString); </code></pre>
Converting PCL to PDF <p>I am looking to create (as a proof-of-concept) an OCaml (preferably) program that converts PCL code to PDF format. I am not sure where to start. Is there a standardized algorithm for doing so? Is there any other advice available for accomplishing this task?</p> <p>Thanks!</p>
<p>Conversion of PCL to PDF can be incredibly complex (assuming you need it to be generic and not just for simple PCL). We've investaged this many times and in the end always revert to using other tools. We keep investigating as we are a development shop who uses and understands all elements of PCL to great detail. If you are not really familure with PCL it will be daunting task. One of the major issues is that overtime, printers have become, for the most part, tollerent of malformed PCL and as such, creating something that follows the rules to the letter of the law is not always sufficient. If; however, you have control over the PCL, you may be able to work it out with some amount of success.</p> <p>I don't mean to turn you off of this and I realize that you've come here looking for a programming answer but I have to say, this is a far from simple task and there are no 'standarized algorithms' for this (that I'm aware of).</p> <p>If this is designed to be a tool to work alongside of somehting else you are building I'd highly recommend looking at these guys:</p> <p><a href="http://www.pagetech.com" rel="nofollow">PageTech</a></p> <p>This is by far the most complete set of tools (Windows) for handling this. There are a few others but, based on our extensive use of PCL and conversion tools over the years, this is the only one that work all the time.</p> <p><strong>EDIT:</strong> Most recently we've been working with LincPDF (<a href="http://www.lincolnco.com/" rel="nofollow">http://www.lincolnco.com/</a>). This is also an excellent product with has one big benefit, deployment is simple. Some of the other tools have complex software installations. This solution is very easy for us to deploy as a feature in an application. It's also faster then any tools we've tested to date (at least with the PCL that we generate from our apps which is quite complex as they include specialized fonts and macros).</p>
Your favorite Visual Basic 6.0 tools and tips <p>This is somewhat related to a similar <a href="http://stackoverflow.com/questions/147339/visual-studio-6-tips-and-tricks">post</a>, but that post was Visual Studio 6 in general and a lot of the suggestions didn't apply to Visual Basic 6.0.</p> <p>Suggest or vote for tools/tips. Please one tool/tip per post so that everyone can vote on them individually. Include a brief description of what the tools do.</p>
<p>Enable mouse wheel in VB6:</p> <p><a href="http://support.microsoft.com/?id=837910" rel="nofollow">Microsoft:enable the mouse scroll wheel</a></p>
How to handle a massive factory in a cleaner fashion <p>My development team has run into a design issue. I'm hoping someone can help me clean this part of the architecture up a bit.</p> <p>In my system, I have an enum with 250 members [one member represents a distinct drop down]. In order to populate the drop downs on any given window, that form sends in the enum members that relate to the drop downs needed, and the drop down information is returned.</p> <p>In other words, say for example, we have 3 windows. Window A has drop downs X, Y and Z. Window B has drop downs W, X and Y and Window C has drop downs T, U and W. My DropDownType enum would consist of T, U, W, X, Y, Y, and Z. So for a specified window, given the drop downs on that window, I query for the data to appear in those drop downs.</p> <p>This is a simplified example because my application consists of > 250 distinct drop downs.</p> <p>As you can imagine, I have a factory setup to return the data for each drop down. And this factory is called for each drop down requested.</p> <pre><code> switch (dropDownType) { case DropDownType.T: return (from t in dataContext.GetTable&lt;TableOne&gt;() select new DropDownDto { DropDownDisplayName = t.ColumnA, DropDownValue = t.ColumnB }).ToList(); case DropDownType.U: return (from u in dataContext.GetTable&lt;TableTwo&gt;() select new DropDownDto { DropDownDisplayName = u.ColumnC, DropDownValue = u.ColumnD }).ToList(); // etc... } </code></pre> <p>Since I have so many members in this enum, does anyone know of a more elegant way of coding this? Do you think transforming this into factory methods would be helpful (but then we'd have to worry about 250 separate files in our source...)? Is there another pattern out there that is more useful? Just having this HUGE switch statement is getting unmanageable. </p> <p>Any help is greatly appreciated. Thanks in advance!</p>
<p>You could create a <code>Dictionary&lt;DropDownType, DropDownDtoDelegate&gt;</code> with each entry containing an enum entry as a key and a delegate to retrieve the drop down data as the value. This would allow you to keep each method that returns a drop down list separate and out of the huge switch statement. You would then have one method to retrieve the delegate, execute it, and return the drop down list data.</p>
Data-driven state machine application <p>We are currently working on a "data-driven" state machine application. Right now, the state flows are all configured in the database, but none of the decision/business logic is configurable in the DB with our current design. Because of this, the code has to basically "know" the state flow as well, so there's really no point in configuring the flow in the database.</p> <p>I have a design in mind that would allow us to wire together a state pattern using dependency-injection (Spring.NET), but I'm not sure of the best way to make this data-driven. I'm not a big fan of configuring code-like things (like class or method names) in the database, but the design I have in mind would require us to wire up the application in the DB (similar to wiring in a Spring XML file), so that seems bad.</p> <p>We've investigated using Windows WF, but I think we're a little concerned about the future of WF, and whether this is a good time to adopt it. I've never dealt with rules engines, so I'm wondering if that might be of some use here. Does anyone have any suggestions on how to implement this?</p>
<p>Your best bet is probably to decouple the data-stored behaviors from the technology used to implement them.</p> <p>The way to do this is a DSL (domain specific language). Come up with a format that can represent the business logic in the abstract (i.e. a micro language), store strings of that in your tables, and implement an interpreter for it in code. That way, if your underlying technology changes you just have to reimplement the interpreter.</p> <p>I worked on an application that used this technique in the mid 1980's, and it's been ported several times with only minor (and automatible) changes to the business rules required.</p>
Background Worker Event Handling <p>I've been struggling with event handling in backgroundworker threads. </p> <p>All the documentation I've come across make me believe that when a DoWork event handler throws an exception that exception should be dealt with in the RunWorkerCompleted handler and that exception will be available in the Error property of the RunWorkerCompletedEventArgs. </p> <p>This is fine, but during debug time I always see an exception unhandled by user code message. This makes me believe there is a problem with my approach. </p> <p>What steps should I take to resolve this?</p> <p>Regards, Jonathan </p>
<p>I've seen this behavior before, and I've gotten around it by decorating the DoWork handler with the <code>System.Diagnostics.DebuggerNonUserCode</code> attribute:</p> <pre><code>[System.Diagnostics.DebuggerNonUserCode] void bw_DoWork(object sender, DoWorkEventArgs e) { ... } </code></pre> <p>Note that you'll only see this if you're running in the debugger; even without the attribute, all is as it should be when running from the shell.</p> <p>I looked this up again, and I still can't see any good reason why you need to do this. I'm calling it a debugger misfeature.</p>
Calculate a running total in MySQL <p>I have this MySQL query:</p> <pre><code>SELECT DAYOFYEAR(`date`) AS d, COUNT(*) FROM `orders` WHERE `hasPaid` &gt; 0 GROUP BY d ORDER BY d </code></pre> <p>Which returns something like this:</p> <pre><code>d | COUNT(*) | 20 | 5 | 21 | 7 | 22 | 12 | 23 | 4 | </code></pre> <p>What I'd really like is another column on the end to show the running total:</p> <pre><code>d | COUNT(*) | ??? | 20 | 5 | 5 | 21 | 7 | 12 | 22 | 12 | 24 | 23 | 4 | 28 | </code></pre> <p>Is this possible?</p>
<p>Perhaps a simpler solution for you and prevents the database having to do a ton of queries. This executes just one query then does a little math on the results in a single pass.</p> <pre><code>SET @runtot:=0; SELECT q1.d, q1.c, (@runtot := @runtot + q1.c) AS rt FROM (SELECT DAYOFYEAR(`date`) AS d, COUNT(*) AS c FROM `orders` WHERE `hasPaid` &gt; 0 GROUP BY d ORDER BY d) AS q1 </code></pre> <p>This will give you an additional RT (running total) column. Don't miss the SET statement at the top to initialize the running total variable first or you will just get a column of NULL values.</p>
How to Make an Image Uniform Brightness (using Python/PIL) <p>I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.</p> <p>My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?</p> <p>(This is a follow-up to <a href="http://stackoverflow.com/questions/662638/how-to-alter-photographed-document-to-look-scanned">this earlier question</a>.)</p>
<p>As a first attempt, try thresholding the image. Dark areas become black, light areas become white. I haven't used PIL, but I imagine there's any easy way to do it.</p>
UIBarButtonItem with color? <p>Is it possible to have a red UIBarButtonItem?</p>
<p>If anyone is looking for code to exactly duplicate a simple UIBarButtonItem:</p> <pre><code>UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal]; [button setTitle:@"Delete" forState:UIControlStateNormal]; button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f]; [button.layer setCornerRadius:4.0f]; [button.layer setMasksToBounds:YES]; [button.layer setBorderWidth:1.0f]; [button.layer setBorderColor: [[UIColor grayColor] CGColor]]; button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0); [button addTarget:self action:@selector(batchDelete) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem* deleteItem = [[UIBarButtonItem alloc] initWithCustomView:button]; </code></pre> <p>And delete.png is:</p> <p><img src="http://i.stack.imgur.com/P0xJO.png" alt="delete.png"></p>
Datagrid Paging : Invalid CurrentPageIndex value. It must be >= 0 <p>I have a datagrid with paging enabled. I am displaying the results in datagrid based on a filtering condition. I have filtered the data and it has now 2 pages. when i go to 2 nd page. and i am doing the seacrhing function once again to narrow down the results. Then I am getting an error like "Invalid CurrentPageIndex value. It must be >= 0 and &lt; the PageCount+datagrid paging" I am sure that the second search will produce only less number of pages than the previous one. How to solve ths problem ? Thanks in advance</p>
<p>When you make certain changes, you need to reset to page 1. That includes filtering changes. Pretty much, any time you change the number of rows that might be available to your grid, go back to page 1.</p>
Best practice for sending AJAX data via form - retrieving value back <p>I have a small form where I want the values to be updated on change for my select boxes which can be done with:</p> <pre><code>$("form#updateclient select").change(function(){ // use one selector for all 3 selects $.post("inc/process-update.php",{ // data to send completed: $("select#completed").val(), hours: $("select#hours").val(), update_id: $("#u_id").val(), who: $("select#who").val() }, function(data) { // do callback stuff with the server response 'data' here }); }); </code></pre> <p>But I have a input text field, where a user can enter the amount of hours, when they click out of the box THEN send that AJAX request to a PHP page.</p> <p>And the #completed field is now a checkbox, does that pass the same was as an input? How would that work with jQuery, so if you check or uncheck send that info and update database</p> <p>The thing I have been trying to research now is what is the best way to retrieve those values from the server and update them on the page using AJAX. So once i update my dropdown, it will keep that same result.</p> <p>Any ideas?</p>
<blockquote> <p>And the #completed field is now a checkbox, does that pass the same was as an input?</p> </blockquote> <p>No. A checkbox's .value (as used by jQuery's val() method) is always the string in the value="..." attribute (defaulting to “on” if omitted), regardless of whether it is ticked or not. To get the effective value of a checkbox you need to look at the ‘.checked’ property. eg.</p> <pre><code>var v= element.checked? element.value : ''; </code></pre> <p>Also, you can't use an onchange handler to detect when a checkbox is changed, as IE doesn't fire that event. Instead, you have to use onclick for that element.</p>
How do we specify the client area size of a form in design mode? <p>I am designing a form in c#. I want to specify the "Client-Area" of the form in the designer.</p> <p>The Size property sets the size of the complete form, including the NC area. Is there any way to set the client area size?</p>
<p>Have you looked at the ClientSize property? This property allows you to modify the size of the client area of the control. Seems to be what you're looking for.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.clientsize.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.form.clientsize.aspx</a></p>
Why is make complaining about circular dependencies? <p>I have built a make file for my project, and it works (everything compiles) but it gives these irritating error messages:</p> <pre><code>make: Circular zpr.c &lt;- zpr.o dependency dropped. gcc -Wall -c -o zpr.o zpr.c make: Circular readjpeg.c &lt;- readjpeg.o dependency dropped. gcc -Wall -c -o readjpeg.o readjpeg.c make: Circular readppm.c &lt;- readppm.o dependency dropped. gcc -Wall -c -o readppm.o readppm.c make: Circular SceneNode.cpp &lt;- SceneNode.o dependency dropped. g++ -c -o SceneNode.o SceneNode.cpp make: Circular BoundingBoxNode.cpp &lt;- BoundingBoxNode.o dependency dropped. g++ -c -o BoundingBoxNode.o BoundingBoxNode.cpp make: Circular GeometryNode.cpp &lt;- GeometryNode.o dependency dropped. g++ -c -o GeometryNode.o GeometryNode.cpp make: Circular SceneGraph.cpp &lt;- SceneGraph.o dependency dropped. g++ -c -o SceneGraph.o SceneGraph.cpp make: Circular testgraph.cpp &lt;- testgraph.o dependency dropped. g++ -c -o testgraph.o testgraph.cpp </code></pre> <p>My makefile is not complicated at all so hopefully someone can spot the error.</p> <pre><code>GXX=g++ CC=gcc CFLAGS=-Wall LIBS=-lGL -lglut -ljpeg OBJS=helpers.o loadobj.o zpr.o readjpeg.o readppm.o SceneNode.o BoundingBoxNode.o GeometryNode.o SceneGraph.o testgraph.o OBJS2=testgraph.o SceneGraph.o GeometryNode.o BoundingBox.o SceneNode.o readppm.o readjpeg.o zpr.o loadobj.o helpers.o SRCS=testgraph.cpp SceneGraph.cpp SceneNode.cpp .o.cpp: $(GXX) $(CFLAGS) -c $&lt; .o.c: $(CC) $(CFLAGS) -c $&lt; testgraph: $(OBJS) $(GXX) $(LIBS) $(OBJS) -o testgraph clean: rm *.o </code></pre>
<p>Your implicit rules are the culprit. They have the extensions listed in the reverse order of how they are understood by make.</p> <pre><code>.o.c: </code></pre> <p>tells make that .c files are created from .o files. Since there is already a rule that says that .o files are created from .c files, you have a circular dependencies and therefore the errors.</p> <p>The solution is (or should be, assuming a reasonably configured make) simple. </p> <p>You don't (usually) need to specify your own rules for compilation in really common cases, such as C++ sources. It would be simpler to just specify something like:</p> <pre><code>CFLAGS=-Wall LOADLIBES=-lGL -lglut -ljpeg OBJS=helpers.o loadobj.o zpr.o readjpeg.o readppm.o SceneNode.o \ BoundingBoxNode.o GeometryNode.o SceneGraph.o testgraph.o all: testgraph testgraph: $(OBJS) </code></pre> <p>This is likely to also help you avoid two errors.</p> <ol> <li><p>The rules you wrote say that .o files are created from .c files, which is backwards. But the correct rules already exist in nearly all versions of make.</p></li> <li><p>You have listed the libraries ahead of the object files. This works by accident on some platforms that use ELF format objects. But it is still wrong. List libraries after objects because libraries are only loaded to satisfy undefined externals. </p></li> </ol>
Container a=new getContentPane() <p>What is mean 'Container a=new getContentPane()" ?</p>
<p>Container a=new getContentPane()" wouldn't compile... </p> <p>getContentPane() is a method of javax.swing.RootPaneContainer. </p> <p>Container a = getContentPane() would get the contentPane of the component.</p> <p><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html" rel="nofollow">This part</a> of the Swing tutorial talks about panes a bit.</p>
RMI: What change needs a recompiled impl class <p>I have two application which communicates by using RMI objects. I do have an interface, an implementation class and the generated stub class.</p> <p>I recognized, that some changes in the impl class take me to create a new stub class.</p> <p>My question is, what changes i can make without re-compiling the stub again?</p> <p>As far as What i know:</p> <ul> <li>I can not change the method structure (add,remove,change methods)</li> <li>Can i add serialVersionUID to classes the impl class is using?</li> <li>Can i change classes the impl class is using?</li> <li>Can i document the impl and all used classes?</li> </ul> <p>I ask this question, because i did a change at the beginning of this week and now, the RMI connection is broken. But i only add comments and updated my checkstyle. So i add serial version UIDs and changed some classes to be final.</p>
<p>You only need to rerun rmic and generate your deployment classes if you change any method signature, including adding and deleting. The generated code simply links a remote invocation object to the actual implementation via the defined methods for the class.</p> <p>This means you can change the impl code (except method signatures) and the code of any class used by the impl class without issue. If those classes used by the implementation are also part of your method signature, then proper versions will be required on the client side to match the remote implementation, but this is nothing RMI specific.</p>
Can there be more than one AWT event queue? <p>I've got a thread dump of an applet running on JVM 1.6.0_12 in Opera 9.64 Build 10487 - and it shows three event queues! As far as I know the Java Swing event handling is single threaded - did this change in any recent update?</p> <p>My problem is, that multiple event queues will tend to cause deadlocks since I've got some more locks than only the GUI TreeLock.</p>
<p>There can be more than one, and it depends on the browser. <a href="http://java.sun.com/javase/6/docs/api/java/awt/EventQueue.html">EventQueue documentation</a> says:</p> <p>Some browsers partition applets in different code bases into separate contexts, and establish walls between these contexts. In such a scenario, there will be one EventQueue per context. Other browsers place all applets into the same context, implying that there will be only a single, global EventQueue for all applets. This behavior is implementation-dependent.</p>
how to add tag suggestion functionality to my blogware? <p>I am creating a blogging functionality to my website running on a cms.</p> <p>My requirement is this:</p> <p>When a person has written an article, he must automatically provided with 'suggested tags'. These words must come from the article. How can I implement this functionality?</p> <p>I thought some ideas. Like:</p> <ol> <li>Suggest words which are the longest. Using this, I can filter out 'a', 'of', 'my' etc but not 'because'.</li> <li>Create a blacklist of words. But I couldn't find any such ready-made list and creating such a list will take a very long time.</li> </ol> <p>So, any other ideas?</p>
<p>You could do <a href="http://en.wikipedia.org/wiki/Naive%5FBayesian%5Fclassification" rel="nofollow">Bayesian classification</a> and see what happens. Here's some <a href="http://jtauber.com/blog/2008/11/29/bayesian%5Fclassification%5Fof%5Fpages%5Fon%5Fthis%5Fsite/" rel="nofollow">example code</a>.</p> <p>UPDATE: This presupposes that you have some tags for the classifier to choose from. Here is a <a href="http://www.find-keyword.com/keyword%5Frelevancy/" rel="nofollow">simple algorithm</a> for extracting keywords from text if you need to initialize your list of tags.</p>
How to not submit a form if validation is false <p>How can I make sure the form won't submit if one of the validations is false?</p> <pre><code>$('#form').submit(function(){ validateForm1(); validateForm(document.forms['dpart2']); validateForm(document.forms['dpart3']); }); </code></pre>
<pre><code>$('#form').submit(function(){ return (validateForm1() &amp;&amp; validateForm(document.forms['dpart2']) &amp;&amp; validateForm(document.forms['dpart3'])) }); </code></pre> <p>Basically, you return false in the event handler function.</p>
Selecting a rows in the standard .net 2.0 GridView Using VB.net & JavaScript <p>Does anyone know how i can get the grid to select a row by clicking on any cell in the row? </p> <p>The only way i can do this at the moment is by setting the AutoGenerateSelectButton property to True, but this adds a column to the grid with a crude "select" hyperlink and only selects the row if the word "Select" is cliked on.</p> <p>Surely there has to be a better way!?!?</p> <p>NOTE - I do not use C#</p>
<p>You need to add some javascript to the row in <code>RowDataBound</code></p> <pre><code> e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink (this.GridView1, "Select$" + e.Row.RowIndex); </code></pre> <p>There's a CodeProject article about it <a href="http://www.codeproject.com/KB/webforms/JavaRowSelect.aspx" rel="nofollow">here</a>, which goes into much more detail.</p>
How can I get Emacs to revert all unchanged buffers when switching branches in git? <p>Often, when I switch branches in git, if the files are open in emacs, then emacs asks if I want to revert them (as it thinks they've changed on disk) even though the contents are identical.</p> <p>Firstly I'd like to find a way for emacs to not ask me about it at all if the contents on disk are identical to those in the buffer.</p> <p>Secondly I'd like a command that reverted (without query) all my open buffers that have no unsaved changes, and queried me about those that do have unsaved changes.</p> <p>Alternatively, I'd be open to suggestions about other solutions, ways of working, etc I could try. I'm fairly happy writing emacs-lisp if people can give me pointers on where to start.</p> <p>PS I'm using Aquamacs on OSX if that matters.</p> <p>Edit:</p> <p>Well, I've found the revbuffs package to be pretty much what I need. Certainly enough to stop me wanting to try and write anything new myself. (I mapped revbuffs to Cmd-R which works quite nicely. Kind of similar to Cmd-R in other Mac apps).</p> <p>Global-auto-revert mode would have been a perfectly fine solution, and I wish I could choose two answers. I prefer revbuffs simply because of a, possibly irrational, feeling of wanting to be in control of what happens.</p> <p>I'd kind of guessed that if I accessed git from within emacs, then it could probably be handled easier, but I currently prefer accessing git through the commandline. (I haven't quite been using emacs long enough to make it my operating system). I will investigate magit a little more thoroughly though.</p> <p>Edit2:</p> <p>I've been using magit for a year now and can highly recommend it for dealing with git from within emacs. However I still use revbuffs whenever I do a rebase outside of emacs.</p>
<p>Perhaps you'd like the global auto-revert mode. Try running <code>global-auto-revert-mode</code> and if you like it you can add <code>(global-auto-revert-mode)</code> to your ~/.emacs file.</p>
Can OAuth work with mobile phone applications? <p>Can we make OAuth work from applications on mobile phones where there is no browser available?</p> <p>Without a browser, is it still possible for a user to approve the token requests (so that the consumer can proceed to fetch the protected resources from the service provider)?</p>
<p><a href="http://getsatisfaction.com/oauth/topics/can%5Fwe%5Fmake%5Foauth%5Fwork%5Ffrom%5Fapplications%5Fon%5Fmobile%5Fphones%5Fwhere%5Fthere%5Fis%5Fno%5Fbrowser%5Favailable?utm%5Fmedium=widget&amp;utm%5Fsource=widget%5Foauth" rel="nofollow">Chris Messina answered this question</a> referring to <a href="http://www.hueniverse.com/hueniverse/2009/02/beyond-the-oauth-web-redirection-flow.html" rel="nofollow">this blog post</a> that explains the possibilities.</p>
jquery validation plugin not working in modalbox <p>i am trying to validate fields in modalbox however its not working below is my validation code</p> <pre><code>$("#formapplication").validate({ rules: { tb_name:{ required: true }, tb_url: {required: true}, tb_tag: {required: true}, tb_desc: {required: true}, tb_catg: {required: true} }, messages:{ tb_name:{ required: "Please Enter Full name" }, tb_url: {required: "Please Enter URL"}, tb_tag: {required: "Please Enter Tag."}, tb_desc: {required: "Please Enter Description."}, tb_catg: {required: "Please Select Category."} } }); </code></pre> <p>jquery validation plugin support modalbox but its simple html i write on same page not calling using ajax any idea pelase help.</p> <p>below is xhtml</p> <pre><code>&lt;div id="submitapplication" style="display:none"&gt; &lt;form action="" id="formapplication" name="formapplication" method="post"&gt; &lt;div class="submitapplicationbox"&gt; &lt;label&gt;Name&lt;input type="text" name="tb_name" id="tb_name" /&gt;&lt;/label&gt; &lt;label&gt;Url&lt;input type="text" name="tb_url" id="tb_url" /&gt;&lt;/label&gt; &lt;label&gt;Tags&lt;input type="text" name="tb_tag" id="tb_tag" /&gt;&lt;/label&gt; &lt;label&gt;Category&lt;select name="select" id="tb_catg"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;/select&gt;&lt;/label&gt; &lt;label&gt;Description &lt;textarea cols="" rows="" name="tb_desc" id="tb_desc" &gt;&lt;/textarea&gt;&lt;/label&gt; &lt;/div&gt; &lt;div class="twiteraccountinfobox"&gt; &lt;label&gt;Name&lt;input type="text" name="tb_twaccount" id="tb_twaccount" /&gt;&lt;/label&gt; &lt;div style="margin-top:20px;"&gt;&lt;input type="button" id="submitapp" value="Submit Application" /&gt;&lt;/div&gt; &lt;div id="response" style="display:none;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p> </p>
<p>i was missting class required on all my inputs that i am using for validation</p> <pre><code>&lt;input type="text" id="tb_name" class="required" /&gt; </code></pre>
Zend Framework form with jquery <p>Any one a idea how to simply create a form with Zend_Form and jquery? I want to use Zend_Form to validate the form so I don't have to dual script the form in JavaScript and PHP.</p> <p>Thank you,</p> <p>Ivo Trompert </p>
<p>No problem there.</p> <p>Add ZendX_JQuery to your library if you use autoload.</p> <p>Then extend ZendX_JQuery_Form to your needs. Do your stuff in the init() method of your class.</p> <p>For example, I was able to create an AutoComplete field which has regular Zend_Form validation plus JQuery behavior like this:</p> <pre><code>$elem = new ZendX_JQuery_Form_Element_AutoComplete( 'query', array('Label' =&gt; 'Search', 'required'=&gt;true, 'filters'=&gt;array('StripTags'), 'validators'=&gt;array( array('validator'=&gt;'StringLength', 'options'=&gt;array('min'=&gt;'3'), 'breakChainOnFailure'=&gt;true ), array('Alnum') ) ) ); $elem-&gt;setJQueryParams(array('data' =&gt; array(), 'url' =&gt; 'my_autocomplete_callback.php', 'minChars' =&gt; 1, 'onChangeInterval' =&gt; 500, ) ); </code></pre> <p>Then I even changed the default decorators like this:</p> <pre><code>$elementDecorators = array( array('UiWidgetElement', array('tag' =&gt; '')), array('Errors', array('tag' =&gt; 'div', 'class'=&gt;'error')), array('Label'), array('HtmlTag', array('tag' =&gt; 'div')), ); $elem-&gt;setDecorators($elementDecorators); </code></pre> <p>And finally add to my form (remember I'm in the init() so I'll address it via $this):</p> <pre><code>$this-&gt;addElement($elem); </code></pre> <p>There you are, the magic is done.</p> <p>PS: don't forget to add the following in your bootstrap:</p> <pre><code>$view-&gt;addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper'); </code></pre>
How to use Web parts in asp.net C#? <p>How can i use web parts for performing drag and drops ?</p>
<p>Here is the official <a href="http://msdn.microsoft.com/en-us/library/e0s9t4ck.aspx" rel="nofollow">MSDN documentation</a> for ASP.NET WebParts. This is the opening article containing all the links to subsequent chapters to help you further understand and implement the WebParts into an ASP.NET application.</p>
Errors in the Windows Forms Editor <p>I'm currently using Microsoft Visual C# Express Edition (with SP1) for a Project. I'm getting some strange errors in the Forms editor when editing one particular form, the message reads:</p> <blockquote> <p>Type 'System.Windows.Forms.Control' in assembly 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.</p> </blockquote> <p>and it apperars on trying to save the form. It mostly appears 3 to 5 times consecutively but sometimes also pops up every few seconds nonstop, until I kill the application.</p> <p>I believe it starts when I tried to add some Application-Settings, but I can't seem to reproduce it.</p> <p>Any ideas how to spot the error would be appreciated, thank you.</p> <p><hr /></p> <p>Edit: Saving the form means clicking the "Save" Button in Visual C# Express. I am not trying to serialize it manually, the error pops up while editing the form in the IDE.</p> <p>Edit: Here is a screenshot - This pops up when I save the form.<br /> <a href="http://img10.imageshack.us/my.php?image=notserializable.png" rel="nofollow">http://img10.imageshack.us/my.php?image=notserializable.png</a></p>
<p>The Windows Forms designer serializes your form as you edit it, inside the <code>.Designer.cs</code>. That's why you often see the error as your edit your form.</p> <p>Usually, you edit classes deriving from <code>UserControl</code> or <code>Form</code> in the designer. Your error seems to indicate it's trying to serialize a Control. Did you change the base class of MainForm to Control?</p> <p>Or did you edit the MainForm.Designer.cs file manually? I strongly recommend not editing the .Designer.cs file directly because if you do, it's really easy to break the Windows Forms Designer support. </p>
In Firefox, how do I force a cursor to stick to the last typed character? <p>I have an input field in which a serial number will be typed. The number of characters allowed is set.</p> <p>Problem is that because of the letter-spacing, on typing a char in firefox, the cursor will jump ahead to where you would type the next char (even with maxlength set), which has the chars break break out of the little boxes they are supposed to sit in, like so: <a href="http://www.bryonykernick.com/dropboxofdeath/ff-form-cursor.png" rel="nofollow">firefox cursor jump</a><br/> <img src="http://www.bryonykernick.com/dropboxofdeath/ff-form-cursor.png" alt="firefox cursor jump" /></p> <p>IE displays it 'correctly': <a href="http://www.bryonykernick.com/dropboxofdeath/ie-form-cursor.png" rel="nofollow">ie no cursor jump</a><br/><img src="http://www.bryonykernick.com/dropboxofdeath/ie-form-cursor.png" alt="ie no cursor jump" /></p> <p>How can I force firefox to <em>not</em> place the cursor <em>after</em> the letter-spacing? (jQuery would be nice, if JS is possible/needed)</p> <p>Here's my code:</p> <pre> #serial { background:transparent url(../images/bg_serial.gif) no-repeat scroll 0 50%; border:0 none; color:#FFFFFF; font:bold 16px Courier New; height:22px; letter-spacing:14px; line-height:normal; padding:4px 0 0 6px; text-transform:uppercase; width:208px; } </pre> <pre><code>&lt;form id="serialForm"&gt; &lt;label for="serial"&gt;Serial:&lt;/label&gt; &lt;input id="serial" type="text" name="serial" maxlength="9" /&gt; &lt;/form&gt; </code></pre>
<p>FireFox handles <code>letter-spacing</code> differently than Internet Explorer and the rest of the browsers, it seems.</p> <p>If you change the <code>width</code> of the input element to 220 pixels, you won't cause any text-overflow. And since you are effectively hiding the input, the extra width won't matter. <br /> <br /> <br /> I've tested this solution in Chrome build 1.0.154.53, FireFox 3.0.7 and Internext Explorer 8.0.6001. 18372.</p>
Assignment problem <pre><code>ag = logss_EventAnalyzer.tabEventsString[0]; </code></pre> <p><strong>ag</strong> is a static string,</p> <p><strong>logss_EventAnalyzer</strong> is a class,</p> <p><strong>tabEventString</strong> is a static string array.</p> <p>During debugging, I saw that logss_EventAnalyzer.tabEventsString[0] contains some string, but it is not assigning into ag. It's value is null.</p> <p>What is the problem here and what is the solution ?</p> <p>Thanks !</p>
<p>You say "during debugging"; does <code>logss_EventAnalyzer.tabEventsString[0]</code> contain a (non-null) string <em>when you assign ag</em>?</p> <p>Note that the assignment doesn't mean that changes to <code>tabEventsString[0]</code> will be reflected in <code>ag</code>, since <code>string</code> is immutable, and any changes to <code>tabEventsString[0]</code> are actually creating <em>new</em> strings. If you want this type of behaviour, you'll need to use a member of some class:</p> <pre><code>public class Foo { public string Bar {get;set;} } static Foo ag; static Foo[] tabEventsString; ... ag = logss_EventAnalyzer.tabEventsString[0]; ... </code></pre> <p>now <code>ag.Bar</code> will always be the same as <code>tabEventsString[0].Bar</code></p> <p><hr /></p> <p>Also - do you perhaps have a local variable called <code>ag</code>? This would take precedence.</p> <p>Can you post code that demonstrates this problem happening?</p> <p>As an aside; note that both static fields and arrays have various associated complexities if your app gets complex... you might want to consider re-factoring them.</p> <p>The following works fine:</p> <pre><code>static class logss_EventAnalyzer { static string[] tabEventsString = {"abc","def","ghi"}; static string ag; static void Main() { ag = logss_EventAnalyzer.tabEventsString[0]; System.Console.WriteLine(ag); } } </code></pre> <p>If you are doing something radically different, you're going to have to give us a clue...</p>
The immediate place where an uploaded file is stored <p>When I upload a file, where is the immediate place the file will go to on the webserver? Is there anyway to configure this place?</p>
<p>In case of PHP they go to <a href="http://www.php.net/manual/en/ini.core.php#ini.upload-tmp-dir" rel="nofollow"><code>upload_tmp_dir</code></a> or system default (usually /tmp).</p> <p>See <a href="http://www.php.net/manual/en/features.file-upload.post-method.php" rel="nofollow">http://www.php.net/manual/en/features.file-upload.post-method.php</a></p>
Decent JavaScript IDE <p>What is a decent IDE for developing JavaScript, I'll be writing both client side stuff and writing for Rhino. Ideally It needs to run on Mac OSX, although something that runs on Windows too would be nice.</p> <p><strong>ADDITIONAL:</strong></p> <p>Having had a play with both js2 and Aptana, I think I'll be continuing to use Aptana. Mainly because I find emacs a bit hard to get my head round, although I did think that the error hi-lighting in js2 was better than that in Aptana.</p> <p>I'm still looking for a way to visually debug my js code that is running atop Rhino...</p>
<p>Aptana IDE, absolutely. Stable, great syntax support for all the major javascript libraries, very good css and html editors. Also good support for php, air, ruby on rails and iPhone app development (I never tested this one). Aptana can also connect to remote site via ftp (sftp in the pro edition) and to svn and cvs repositories. It's based on Eclipse, so it's not exactly a lightweight application. But it's really, really good. You can also use it as an Eclipse plugin if you develop java wab app, but when I tested it in this version, about 1 year ago, it was not stable. Much better to use the standalone version.</p>
Imported Java applet project into netbeans won't work, Netbeans refuses to identify or even find main class even when manually set <p>I'm trying to set the main class in netbeans to be the main class it was in the last environment it was in, however the program insists it can't find the main class itself and when I set it as the name of the main class in project properties it says the class does not exist (even though it does).</p> <p>When I right click on the source file with the main class and hit 'run [file]' it works (albeit with errors related to assets which I can fix later on, has nothing to do with the code itself.</p> <p>All I did as of now is simply copy and paste the code into netbeans from the last project, so would I be overlooking anything here?</p> <p>Thanks for any help.</p>
<p>The way applets work in Netbeans is annoying to me. The suggested usage from the help is to run the applet as you indicate you did (Run File). NetBeans will produce an HTML file under build/classes that references the applet. You then copy the HTML file to src where your class is. You can then tweak the HTML and in subsequent runs NetBeans will use your HTML file instead of generating it. Every time you run the file NetBeans opens the applet viewer program that ships with Java. You cannot control any of the arguments passed to the applet viewer. It ignores the run-time parameters you configure in the project. To change the parameters passed to the applet you must edit the HTML file manually.</p> <p>A better way is to use the AppletWindow classes created over at the BlueJ project. It lets you host an applet on a JFrame, which means you can make a small standalone Swing app which calls your applet. The program then has a main method, you can launch an extra Swing window with buttons and text controls to simulate javascript calls to the applet and you can tweak the attributes that get passed to the applet at runtime. It's very nice for trying out new things in your code.</p> <p>Links:</p> <ul> <li><a href="http://www.bluej.org/resources/classes/appletwn.jar" rel="nofollow">AppletWindow Download</a>: This jar contains the compiled .class files and the source.</li> <li><a href="http://www.bluej.org/resources/classes.html" rel="nofollow">More info about BlueJ and other resources</a></li> </ul>
Access SQL many to many query <p>I have three tables: </p> <pre><code>Author(AID, Name) Title(TID, Name) AuthorOfTitle(ID, AID, TID) </code></pre> <p>My question is how do can I see only Authors that are connected to no titles, that is Authors where there is no record in AuthorOfTitle. How to do this in SQL. Btw am using MS Access 2007.</p>
<p>This ought to do it:</p> <pre><code>SELECT A.* FROM Author A LEFT JOIN AuthorOfTitle T ON A.AID = T.AID WHERE T.ID IS NULL </code></pre>
Deep clone utility recomendation <p>Is there any utility for deep cloning for java collections:</p> <ul> <li>Arrays</li> <li>Lists</li> <li>Maps</li> </ul> <p>NOTE: prefer some solution without usage of serialization, but with use of Object.clone() method. I can be sure that my custom object will implement clone() method and will use only java-standard classes that are cloneable...</p>
<p><strong>I think the previous green answer was bad</strong> , why you might ask?</p> <ul> <li>It adds a lot of code</li> <li>It requires you to list all fields to be copied and do this</li> <li>This will not work for Lists when using clone() (This is what clone() for HashMap says: Returns a shallow copy of this HashMap instance: the keys and valuesthemselves are not cloned.) so you end up doing it manually (this makes me cry)</li> </ul> <p>Oh and by the way serialization is also bad, you might have to add Serializable all over the place (this also makes me cry).</p> <p><strong>So what is the solution:</strong></p> <p>Java Deep-Cloning library <em>The cloning library</em> is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects. </p> <pre><code>Cloner cloner=new Cloner(); XX clone = cloner.deepClone(someObjectOfTypeXX); </code></pre> <p>Check it out at <a href="https://github.com/kostaskougios/cloning">https://github.com/kostaskougios/cloning</a></p>
In an Eclipse RCP editor, what is the best way to handle missing mandatory fields? <p>On an Eclipse RCP application, I'm building an Editor in which some fields are mandatory.</p> <p>If the user saves the editor with theses fields not filled, what is the best way/practice to handle this ?</p> <p>(my first guess is to show an error dialog if theses fields are empty in doSave() method but I'm not sure it's the "eclipse" way to deal with this kind of problem)</p>
<p>If you consider some dialog box like "Create a New Java Project", </p> <ul> <li><p>you simply cannot do any action (like "Next" or "Finish" until you fill the one mandatory field ("Project name")<br /> So it is different than checking on the <code>doSave()</code> event.</p></li> <li><p>If that field is invalid (like if the project name already exist), a warning is displayed in the zone at the top.</p></li> <li><p>If the field is correctly filled, <em>then</em> you can save.</p></li> </ul> <p>(Note: I know this is not an Editor, but it can give you an idea about the mandatory fields management in eclipse)</p> <p><img src="http://ds.informatik.uni-marburg.de/MAGE/gdt/images/tutorial/NewJavaProject.png" alt="alt text" /></p>
Round UIButton <p>I want to know whether drawing a round UIButton(not rounded rect) is possible.</p> <p>When I add a round image in a UIButton of type custom, then it looks like a round button. But at the moment the button is clicked the boundary of the button becomes visible, so that it looks like a square button, then again when the click ends it looks like a round button.<br /> I want the button to look like a round button even at the moment the click happens. is this possible? </p>
<p><strong>Tested Code:</strong></p> <p>.h</p> <pre><code> -(void)vijayWithApple; </code></pre> <p>.m</p> <pre><code> -(void)vijayWithApple{ NSLog(@"vijayWithApple Called"); } UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"Micky.png"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(vijayWithApple) forControlEvents:UIControlEventTouchUpInside]; [button setTitle:@"Show View" forState:UIControlStateNormal]; button.frame = CGRectMake(135.0, 180.0, 40.0, 40.0);//width and height should be same value button.clipsToBounds = YES; button.layer.cornerRadius = 20;//half of the width button.layer.borderColor=[UIColor redColor].CGColor; button.layer.borderWidth=2.0f; [self.view addSubview:button]; </code></pre> <p><strong>Result</strong></p> <p><img src="http://i.stack.imgur.com/OOWJm.png" alt="enter image description here"></p>
What is your company's stance regarding (technological) 'innovation'? <p>.NET 3.5, .NET 4.0, WPF, Silverlight, ASP.NET MVC - there's really a lot of new Microsoft technology released / on the horizon to try out these days. (The examples I gave is all Microsoft technology but this can apply to any language or platform). I am curious how this is handled in the company you work for. A few examples:</p> <ul> <li>Do you have a CTO that determines what technology the company uses?</li> <li>Are development teams free to choose what technology they use? For example: framework version, classic ASP.NET vs ASP.NET MVC, ADO.NET Entity Framework vs Linq2Sql or NHibernate? Or a mix of these?</li> <li>What new technologies does the company you work for try out and <em>why</em>?</li> <li>Does your company have dedicated resources (time) to try out WPF or whatever technology, just for research, or do you try things out in your spare time and try to introduce them to your company?</li> </ul> <p>These are just examples to make my question clearer. To summarize, I'd like to know what this process looks likes, who is responsible, who makes the decisions. Does your company jump on the bandwagon, or is it reluctant to try new technologies? And are you comfortable with this situation?</p> <p>At the company I work for, we still use .NET 2.0 (although we are now slowly switching to .NET 3.5), haven't seriously looked into ASP.NET MVC, haven't tried out WPF at all, etcetera. And, some find it pretty hard to convince people to do. Is it fair to expect otherwise?</p>
<p>At my company, we have an architecture group that determines which technologies are used. People are welcome to read up on alternative technologies and make suggestions, but at the end of the day, it's the architecture group that makes the decisions.</p> <p>While this may seem restrictive, it does ensure that all of the development groups are using the same or similar technologies, and moving from one group to the next is fairly easy. As well, by having one group do all the research, you ensure that you don't waste time by having multiple groups duplicate the research effort.</p>
Workflows -Conditional Branches <p>I'm creating a workflow for a form.</p> <p>Form is an approval form that requires 4 approvers or rejected.</p> <p>I can get the approvals to work but not the rejections.</p> <p>I'm using Designer 2007.</p> <p>My work flow looks like this:</p> <p>Step 1: Condition: If Created equals created Action:Email to notify all approvers.</p> <p>Step 2:<br /> Condition: Else If TomR equals yes if TomA equals yes Action: Send an email to creator then send an email to...</p> <p>From here I have created conditional branches for the other 3 approvers using the same steps as above.</p> <p>I don't believe I'm understanding what I'm doing obviously.</p>
<p>The out of the box approval workflow should cater for this? Is there a reason that it does not and you need to build your own?</p>
What is the purpose of the Build Configuration Manager in VS2008? <p>I am struggling with the purpose of the build configuration manager in Visual Studio 2008. Specifically I am interested in knowing what it does when developing a console application and also a web application (web application project). Does setting it to Debug or Release mode make any difference when you are developing and running the application in the context of VS2008? What does it to when you want to build the solution?</p>
<p>The Build Configuration Manager allows you to set different combinations of project build options for a solution. For example, say you have a solution with 4 projects, log4net, a DAL, a Business layer and the Website. Most times you'll want to run the website and business layer in debug, but the DAL and log4net in release mode. Sometimes you'll want to run the DAL in debug too, but only on a rare occurrence will you want to run everything in debug. The config manager lets you define configurations like that.</p> <p>Additionally, you could define a x64 build that had some projects target x64 and others target AnyCPU depending on need. Or even a build target that excluded specific projects and included others depending on need. </p> <p>So in short, the config manager lets you control the inter-process build relations at a level beyond the simplistic debug-all or release-all. </p> <p>I'd also guess, that 99% of the time you won't need to mess w/the config manager anyway. :-)</p>
Problem with dereference operator and functions <p>I have a function A(), that returns a pointer to an object. In function B() I try to change a member of that object in the following way:</p> <pre><code>void B() { ObjType o = *getObj(); o.set("abc"); } </code></pre> <p>Object o is stored in an array, and when I print the value of the member, it seems nothing happened, and the member still has the old value;</p> <p>The solution is quite simple:</p> <pre><code>void B() { ObjType * o = getObj(); o-&gt;set("abc"); } </code></pre> <p>This does work. But to me, this is quite the same as the first sample. Can anyone explain this?</p>
<p>The following line is most likely copying the object:</p> <pre><code>ObjType o = *getObj(); </code></pre> <p>That's why nothing happens. If you don't want to use a pointer as shown in your second snippet, you can use a reference like this:</p> <pre><code>ObjType&amp; o = *getObj(); o.set("abc"); </code></pre>
Fetching page source <p>I have the following code in my page</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;testpage&lt;/title&gt; &lt;script language = 'javascript'&gt;function fchange(){alert(document.getElementById("ifrm").value);&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe id = 'ifrm' src = 'http://www.google.com' width = '700' height='500'&gt;&lt;/iframe&gt;&lt;input type='button' onclick = 'fchange()' value = 'clickhere'&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>From this I click the button and an alert box dispalys <code>undefined</code>. But I need the content or the source of the page ('<a href="http://www.google.com" rel="nofollow">http://www.google.com</a>'). Please help me to do this.</p> <p>Thanks in advance...</p>
<p>If you want the source of the iframe, you would need to access the document object of the iframe.</p> <pre><code>function fchange() { alert(document.getElementById("ifrm").contentWindow.document.body.innerHTML); } </code></pre> <p>As mentioned by others, you cannot get the source of an iframe which points to a page outside your domain.</p>
Accessing public class memory from C++ using C <p>Greetings Everyone.</p> <p>I'm currently writing a multi-language programe in C, C++ and fortran on UNIX, unfortunatly I run into "Segmentation Error" when I try and execute after compiling. </p> <p>I've narrowed down the problem to the interface between the C++ and C sections of my program. The first section consists of main.ccp and SA.cpp, and the second CFE.c. </p> <p>A class called 'SimAnneal' exsists in SA.cpp, with public vectors DensityArray and ElementArray. The order of the program follows:</p> <ol> <li><p>Create SimAnneal Object 'Obj1' and call function ObjFunction()</p></li> <li><p>That function initializes the vector sizes</p></li> <li><p>Call CFE(...) with pointers to both vectors and their length.</p></li> <li><p>CFE.c edits the data elements of the vectors directly via use of the pointers</p></li> <li><p>ObjFunction() uses EnergyArray (and possible DensityArray) data.</p></li> </ol> <p>The relevant script is below for all sources:</p> <p>main.cpp</p> <pre><code>#include "SA.h" int main() { SimAnneal Obj1; Obj1.ObjFunction(); return 0; } </code></pre> <p>SA.h</p> <pre><code>class SimAnneal { void Initialize (); ... public std::vector&lt;float&gt; DensityArray; std::vector&lt;float&gt; EnergyArray; double ObjFunction (); ... } </code></pre> <p>SA.cpp</p> <pre><code>#include "CFE.h" void SimAnneal::Initialize () { int length = 15; EnergyArray.resize(length); DensityArray.resize(length); } double SimAnneal::ObjFunction () { Initialize (); CFE(&amp;DensityArray[0], &amp;EnergyArray[0], DensityArray.size()); // sends pointers of both arrays to CFE.c, which will then // directly modify the array double SumStrainEnergy = 0; for (int i = 0; i &lt; EnergyArray.size(); i++) { SumStrainEnergy += EnergyArray[i]; //Effectively sum of array //engy[] from CFE.c } return SumStrainEnergy; } </code></pre> <p>CFE.h</p> <pre><code>#ifdef __cplusplus extern "C" { #endif void CFE(float density[], float energy[], int NumElem); #ifdef __cplusplus } #endif </code></pre> <p>CFE.c</p> <pre><code>void CFE(float density[], float energy[], int NumElem) { ... float * dens; dens = density; //pass pointer of array density[0] in SA.cpp to CFE.c for(n=0; n&lt;NumElem; n++) { ... modify dens (e.g. DensityArray from SA.cpp) ... } float * engy; engy = energy; //pass pointer of array energy[0] in SA.cpp to CFE.c for(n=0; n&lt;NumElem; n++) { ... modify engy (e.g. EnergyArray from SA.cpp) ... } } </code></pre> <p>Am I causing an illegal memory access by trying to access the vector elements from the C portion of my program? Is there any sure way to allow this?</p> <p>Any help would be much appriciated.</p>
<p>Provided you stay within the bounds of the vector, what you are doing would seem to be OK.</p> <p><strong>You can treat a std::vector exactly as if it were a C array by doing what you are doing - taking the address of the first element. The C++ Standard has been changed to specifically allow this kind of usage.</strong></p> <p>Can't find a copy of C++ the Technical Corrigendum 2003 at present, but apparently the relevant section ref is 23.2.4, </p>
Is there any reason to write terse code in Java/C#/C++? <p>Did you ever find yourself writing terse code in Java, C# or C++?</p> <p>If so, why? Do you think there are any situations in which this should be acceptable, given the situations in which these languages are used?</p>
<p>It depends on your definition of 'terse'. </p> <p>If you mean 'short and to the point', it closely matches my vision for <em>good</em> code. </p> <p>If you mean 'cryptic', then there's a problem.</p>
Under what conditions with NSLOOKUP and PING return different IP addresses on windows XP? <p>Inside our firewall at work, my machine frequently resolves to the wrong IP for some of our domains. We have a DNS server that is our primary DNS to resolve external domains to internal IP addresses (192.X.X.X instead of the public IP).</p> <p>Sometimes I will get resolved to the public IP, which won't route correctly through our firewall. When this happens, I run:</p> <pre><code>ipconfig /flushdns nslookup code.mydomain.com - I get the right DNS server and the right internal IP ping code.mydomain.com - I get the wrong external IP address. </code></pre> <p>Firefox also resolves to the wrong IP when this is happening. This will happen intermittently throughout the day.</p>
<p>nslookup uses only DNS, while ping will first look in <a href="http://en.wikipedia.org/wiki/Hosts%5Ffile"><code>hosts</code></a> file.</p> <p>Example:</p> <pre><code>nslookup localhost Server: 208.67.220.220 Address: 208.67.220.220#53 Non-authoritative answer: Name: localhost.local.lan Address: 67.215.65.132 </code></pre> <p>67.215.65.132 means non-existent domain OpenDNS (hit-nxdomain.opendns.com)</p> <pre><code>ping localhost PING localhost (127.0.0.1) 56(84) bytes of data. ... </code></pre>
Interface Builder "Simulate Interface" not working <p>I am using Interface Builder to play around with some ideas. I never noticed that there is a "Simulate Interface" feature which apparently will render the nib in the iPhone simulator. So, I created a view, put one component in there (a Segmented Control), saved it, selected "Simulate Interface", the simulator launched but... nothing rendered in the simulator. Just a black screen. </p> <p>I thought maybe my nib wasn't complete enough, so I've tried it with all of my old nibs and I'm having the same problem with all of them. None of them render in the simulator at all. Is there some trick that I'm missing?</p>
<p>I think this is essentially the same as doing "build and go" from xcode, your interface needs to be hooked up to a working application for it to "simulate"</p>
Ruby Web Services <p>I'm contemplating creating a web application using a Ruby on Rails/MySQL stack and I am wondering what capabilities are available around web services and SOAP. Is there a capability within the framework or does it require an extension and if so what?</p>
<p>Rails opted for <a href="http://weblog.rubyonrails.org/2007/12/7/rails-2-0-it-s-done" rel="nofollow">REST over SOAP</a>:</p> <blockquote> <p>It’ll probably come as no surprise that Rails has picked a side in the SOAP vs REST debate. Unless you absolutely have to use SOAP for integration purposes, we strongly discourage you from doing so. As a naturally extension of that, we’ve pulled ActionWebService from the default bundle. It’s only a gem install actionwebservice away, but it sends an important message none the less.</p> </blockquote> <p>Still, if you must use SOAP, there's always <a href="http://dev.ctor.org/soap4r" rel="nofollow">soap4r</a>, but it only supports SOAP 1.1. A better option might be <a href="https://wso2.org/project/wsf/ruby/1.0.0/docs/index.html" rel="nofollow">WSF/Ruby</a>. Mark Thomas has an <a href="http://markthomas.org/2008/01/14/industrial-strength-web-services-for-ruby/" rel="nofollow">example controller</a> to help you get up and running.</p>
Adding JMS Info breaks EhCache <p>I want to distribute my EhCache via a JMS Topic. This is documented here <a href="http://ehcache.sourceforge.net/documentation/distributed%5Fcaching%5Fwith%5Fjms.html" rel="nofollow">on EhCache's site</a></p> <p>I'm using:</p> <ul> <li>ehcache-1.6.0-beta3</li> <li>ehcache-jmsreplication-0.3</li> <li>spring-2.5</li> <li>spring-modules-0.9</li> </ul> <p>My Spring config looks like this:</p> <blockquote> <pre><code>&lt;bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&gt; &lt;/bean&gt; &lt;bean id="cacheProvider" class="org.springmodules.cache.provider.ehcache.EhCacheFacade"&gt; &lt;property name="cacheManager" ref="cacheManager" /&gt; &lt;/bean&gt; &lt;ehcache:proxy id="pocDaoCache" refId="pocDao"&gt; &lt;ehcache:caching methodName="fetch" cacheName="pocCache" /&gt; &lt;/ehcache:proxy&gt; </code></pre> </blockquote> <p>And, pre-JMS config, my ehcache.xml looks like this:</p> <blockquote> <pre><code> &lt;diskStore path="c:/projects/cache/demo" /&gt; &lt;defaultCache maxElementsInMemory="50" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /&gt; &lt;cache name="pocCache" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" / &gt; </code></pre> </blockquote> <p>And this works fine. So I add my Topic information:</p> <blockquote> <pre><code> &lt;cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jms.JMSCacheManagerPeerProviderFactory" properties="initialContextFactoryName=JmsInitialContextFactory, userName=myuser,password=mypass, providerURL=tcp://jmsdev1-jndi,tcp://jmsdev2-jndi topicConnectionFactoryBindingName=TCF-00, topicBindingName=MyTopiceName" propertySeparator="," /&gt; </code></pre> </blockquote> <p>And I get a NullPointer when I get an application context. Here is the stack trace:</p> <blockquote> <pre><code> org.springframework.beans.factory.BeanCreationException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheManager' defined in class path resource [cache-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBean Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1336) at org.springframework.beans.factory.support.AbstractAutowireCapableBean Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:471) at org.springframework.beans.factory.support.AbstractAutowireCapableBean Factory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBean Factory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb ject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr y.getSingleton(DefaultSingletonBeanRegistry.java:217) [snip] </code></pre> </blockquote> <p>Any ideas from anyone?</p>
<p>The real problem is that Ehcache's documentation isn't right -- not even close -- to how it is really implemented. Through logging and looking through the code in the jmsreplication module, I was able to get it working.</p> <pre><code> &lt;cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jms.JMSCacheManagerPeerProviderFactory" properties="initialContextFactoryName=com.InitialContextFactory; userName=uname;password=passwd; replicationTopicConnectionFactoryBindingName=TCF; replicationTopicBindingName=CACHE; providerURL=tcp://server1:7222,tcp://server2:7222; getQueueConnectionFactoryBindingName=QCF; getQueueBindingName=CACHE_LOAD " propertySeparator=";" /&gt; </code></pre> <p>Another thing that tripped me up was simple, once I realized it -- you have to implement your own key generator to ensure that Ehcache saves the objects with the same keys on each JVM. That makes perfect sense, when you think about it.</p> <p>Yes, you have to put in the loader queue information into the cacheManagerPeerProviderFactory. That is because, if you start up a process after one has been running, the new process can pre-load the cache from the existing process.</p> <p>You configure the loader requester (cacheLoaderFactory) with the exact same settings:</p> <pre><code> &lt;cacheLoaderFactory class="net.sf.ehcache.distribution.jms.JMSCacheLoaderFactory" properties="initialContextFactoryName=com.InitialContextFactory; userName=uname;password=passwd; replicationTopicConnectionFactoryBindingName=TCF; replicationTopicBindingName=CACHE; providerURL=tcp://server1:7222,tcp://server2:7222; getQueueConnectionFactoryBindingName=QCF; getQueueBindingName=CACHE_LOAD " propertySeparator=";" /&gt; </code></pre>
How to call a function just before returning in C? <p>I'm trying to execute something at the end of a function just before it returns to the caller. To Do so, I would like to override return in a certain context. The behavior should be the same as __cyg_profile_func_exit, but I would like to activate it only for some functions.</p> <p>I don't know if it's possible using gcc builtins or this kind of thing.</p> <p>Thanks.</p>
<p>GCC has an attribute for this, which calls a function when an automatic variable goes out of scope, passing it the address of that variable</p> <pre><code>void cleanup_fn(int *p) { puts("cleanup called..."); } void f(void) { int p __attribute__((cleanup(cleanup_fn))); puts("in f..."); } int main(void) { puts("calling f..."); f(); puts("out of it..."); return 0; } </code></pre> <p>Output:</p> <pre><code>calling f... in f... cleanup called... out of it... </code></pre>
.Net, cobol, copybook <p>I have a project that is requiring extensive use of a data source that only exists as what appears to be a copy book. For instance, </p> <pre><code> 01 CMT-COMM-MSTR-EXTRACT-RECORD. 05 CMT-FIXED-AREA-1. 10 CMT-COMMUNITY-RECORD-KEY. 15 CMT-ALTERNATE-KEY. 20 CMT-ALTERNATE-KEY-STATE PIC X(02). 20 CMT-ALTERNATE-KEY-COMM PIC X(08). 15 CMT-COMMUN-NBR. </code></pre> <p>The question is whether or not I have to write a crude parser for this stuff or if someone knows of some tools that will handle this nicely for me. I am basically interested in either stuffing it in sql, oracle, or even just xml using .Net. Seeing as I know nothing about this stuff, I just get worried I am going to handle something incorrectly. Any input would be fantastic. Thanks</p>
<p>There are lots of tools out there for this purpose:</p> <p><a href="http://sourceforge.net/projects/cb2xml/" rel="nofollow">COBOL copybook to XML</a></p> <p><a href="http://www.dnzone.com/go?1068" rel="nofollow">Another COBOL copybook to XML with some .NET specific notes:</a></p>
xajax and select <p>I have a bit of simple created with XAJAX, which replaces the innner HTML of a select control with some options created by a php script.</p> <p>This is fine and dandy in Firefox, but it does not work in IE7.</p> <p>Looking on the XAJAX forums i found <a href="http://community.xajaxproject.org/post/27727/#p27727" rel="nofollow">this</a> which basically says " doesnt really work in IE, use a div and replace the inner HTML of that with the full select statement"</p> <p>Did this, and it's fine, except that i had a jQuery selector working on the select control, which now no longer works.</p> <p>Anyone got any ideas, or can anyone point me to a good jQuery example of how to do the ajax bit using jQuery, so I can ditch the XAJAX altogether?</p> <p><hr /></p> <h3>EDIT:</h3> <pre><code>&lt;div id=imgselect&gt; &lt;select id="images"&gt; &lt;option value=""&gt;Then select an image&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; Picture Preview:&lt;br&gt;&lt;br&gt; &lt;div class="img-preview" id='preview'&gt;&lt;/div&gt; &lt;script type='text/javascript'&gt; $('#images').change(function() { var image = $(this).val(); var img = $('&lt;img/&gt;').attr('src', image); $('#preview').html(img); document.getElementById('picsmall').value = image; }); &lt;/script&gt; </code></pre> <p>The problem comes when the contents of the <code>imgselect</code> <code>div</code> is replaced by the AJAX call</p>
<p>These might be helpful:</p> <p><a href="http://stackoverflow.com/questions/47824/using-core-jquery-how-do-you-remove-all-the-options-of-a-select-box-then-add-on">http://stackoverflow.com/questions/47824/using-core-jquery-how-do-you-remove-all-the-options-of-a-select-box-then-add-on</a></p> <p><a href="http://stackoverflow.com/questions/623976/jquery-live-search-with-quicksilver-style-in-a-multi-select-list-box/624094#624094">http://stackoverflow.com/questions/623976/jquery-live-search-with-quicksilver-style-in-a-multi-select-list-box/624094#624094</a></p>
Selecting a good dictionary key <p>I have an object that I want to use to look up other objects. I will be using a <code>Dictionary&lt;TKey, TValue&gt;()</code>. </p> <p>The key object has two strings that uniquely identify it, say <code>KeyObj.Str1</code> and <code>KeyObj.Str2</code>.</p> <p>What do you recommend that I use as the key for the dictionary?</p> <p>1: The concatenation of the strings. </p> <pre><code>Dictionary&lt;String, TValue&gt;(); Key = KeyObj.Str1:KeyObj.Str2; ("somestring:anotherstring") </code></pre> <p>2: A unique integer for each object to identify it?</p> <pre><code>Dictionary&lt;int, TValue&gt;(); KeyObj.ID = _nextID++; Key = KeyObj.ID; </code></pre> <p>3: A reference to the object.</p> <pre><code>Dictionary&lt;KeyObj, TValue&gt;(); Key = KeyObj; </code></pre> <p>Option 3 would be the easiest, but it seems like it would be inefficient to index a dictionary based on reference values. </p> <p>If the key object contained a single unique string, the obvious choice would be use that, but having two strings that are only unique in combination makes it more difficult.</p>
<p>Concatenated strings should work best.</p> <p>IF you know that their combination is unique, then that is what you should choose -- remember that Hash code is <strong>usually</strong> unique, but not always.</p>
What's wrong with this algorithm? <p>This is an abstracted form of the bug that led me into the code that formed the basis of <a href="http://stackoverflow.com/questions/659117/whats-a-good-way-to-structure-variable-nested-loops">my prior question</a>. It's obvious once you see it, but several professional programmers familiar with the original problem and original language looked over the code and overlooked the bug before we caught it (admittedly, in its native environment it was closer to three pages long).</p> <p><strong>Please <a href="http://www.rot13.com/index.php" rel="nofollow">obfuscate your responses</a> so latecomers can have some fun too.</strong></p> <pre><code>most_bang_for_buck_score = 0.0 most_bang_for_buck_order = [] for appetizer in appetizers total_cost = appetizer.cost total_calories = appetizer.calories for salad in salads total_cost = total_cost + salad.cost total_calories = total_calories + salad.calories for entree in entrees total_cost = total_cost + entree.cost total_calories = total_calories + entree.calories for desert in deserts total_cost = total_cost + desert.cost total_calories = total_calories + desert.calories if total_calories/total_cost &gt; most_bang_for_buck_score most_bang_for_buck_score = total_calories/total_cost most_bang_for_buck_order = [appetizer,salad,entree,desert] print "You'll get the most food energy for your money ordering ",most_bang_for_buck_order,"\n" </code></pre>
<p><a href="http://www.rot13.com/index.php" rel="nofollow" title="I don't think you're resetting total_cost/total_calories on each pass. You ought to just be summing everything up once in the innermost loop. By the way you save the order as one of each item, I'm assuming you're only supposed to be having one of each food category."><strong>ROT13 (or hover on this link to see the non-obfuscated answer as a tooltip)</strong></a></p> <p>V qba'g guvax lbh'er erfrggvat gbgny_pbfg/gbgny_pnybevrf ba rnpu cnff. Lbh bhtug gb whfg or fhzzvat rirelguvat hc bapr va gur vaarezbfg ybbc.</p> <p>Ol gur jnl lbh fnir gur beqre nf bar bs rnpu vgrz, V'z nffhzvat lbh'er bayl fhccbfrq gb or univat bar bs rnpu sbbq pngrtbel.</p>
NHibernate paging and Binding to Gridview <p>I have a Gridview, which is bound to an IList. I'd like to have paging " the safer way" (only fetching the Items I Need), so I created a metod on my repository like this</p> <pre><code>public Ilist&lt;Item&gt; GetItems(int from, int number){ ... } </code></pre> <p>The thing is that wheen I bind it, it only shows me the n items, and doesn't show the paging controls. I tried to find the way to tell the gridview how many elements I have on my resultset with </p> <pre><code>public int CountItems{ get{ ... } } </code></pre> <p>but I didnt find a place to tell the GV this value.</p> <p>What is the strategy here? Is it necessary to have an ObjectDS? I refuse to belive so!</p> <p>What can I do to have Paging?</p>
<p>NHibernate has a native class that converts IQueryable to DataTable You need to create an ObjectDataSource and feed it from your DAO in NHybernate. ObjectDataSource requires a DataTable to do paging, filtering, editing.</p>
How to obtain the macros defined in an Excel workbook <p>Is there any way, in either VBA or C# code, to get a list of the existing macros defined in a workbook? </p> <p>Ideally, this list would have a method definition signatures, but just getting a list of the available macros would be great. </p> <p>Is this possible?</p>
<p>I haven't done vba for Excel in a long time, but if I remember well, the object model for the code was inaccessible through scripting. </p> <p>When you try to access it, you receive the following error.</p> <blockquote> <pre><code>Run-time error '1004': Programmatic access to Visual Basic Project is not trusted </code></pre> </blockquote> <p>Try:</p> <blockquote> <pre><code>Tools | Macro | Security |Trusted Publisher Tab [x] Trust access to Visual Basic Project </code></pre> </blockquote> <p>Now that you have access to the VB IDE, you could probably export the modules and make a text search in them, using vba / c#, using regular expressions to find sub and function declarations, then delete the exported modules. </p> <p>I'm not sure if there is an other way to do this, but this should work.</p> <p>You can take a look the following link, to get started with exporting the modules. <a href="http://www.developersdex.com/vb/message.asp?p=2677&amp;ID=%3C4FCD0AE9-5DCB-4A96-8B3C-F19C63CD3635%40microsoft.com%3E" rel="nofollow">http://www.developersdex.com/vb/message.asp?p=2677&amp;ID=%3C4FCD0AE9-5DCB-4A96-8B3C-F19C63CD3635%40microsoft.com%3E</a></p> <p>This is where I got the information about giving thrusted access to the VB IDE.</p>
GWT Textbox Encoding and RPC <p>Let's say I have a TextBox and the user puts some data in it. I then send the data over RPC, with something like this (synchronous version of interface)</p> <pre><code>public void submitText(String userData) { dao.saveText(userData); } </code></pre> <p>My questions are:</p> <ul> <li>What is the encoding of the userData? This is a trick question, since Strings in java are stored in UTF-16, what I want to know is if my text box sends funny characters like <strong>ã</strong> or <strong>Í</strong> or <strong>€</strong>, and if I later feed that chars to a xml document, what should be the xml encoding?</li> <li>Do I need to care about encoding when submitting data this way? Or GWT assures me that the chars within the userData are properly converted from the http request?</li> </ul>
<p>2 issues:</p> <ol> <li>The "Serialization" or "Marshalling" of data built into RPC handles binary conversions such as machine byte order differences.</li> <li>the "xml document" you refer to should use <a href="http://www.w3schools.com/XML/xml%5Fencoding.asp" rel="nofollow">"UTF-16" encoding</a> if you plan on writing Java Strings as "binary characters" to it. </li> <li>another approach is to use 8-bit encoding and translate all the 16-bit characters to markup as in non-breaking-space "</li> </ol> <blockquote> <p><code>&amp;nbsp;</code></p> </blockquote> <p>" </p>
Sorting dropdown list using Javascript <p>i want to sort the drop down items using javascript,can anyone tell me how to do this.</p>
<p>You could use jQuery and something like this:</p> <pre><code>$("#id").html($("#id option").sort(function (a, b) { return a.text == b.text ? 0 : a.text &lt; b.text ? -1 : 1 })) </code></pre> <p>But it's probably better to ask why and what you're trying to accomplish.</p>
Using Delegates AND Declaring Events <p>I'm developing a class library to be used for other developers and will be allowing them to either declare an instance of my class using WithEvents (or similar in other languages) as well as allow them to use Delegates defined in the class. Am I just being redundant here by doing it like this?</p> <pre><code>Public Delegate Sub TimerElapsedDelegate(ByVal sender As Object, ByVal e As System.EventArgs) Public Event TimerElapsed(ByVal sender As Object, ByVal e As System.EventArgs) Private _TimerElapsed As TimerElapsedDelegate = Nothing </code></pre> <p>Or should I just declare the events and let them do the AddHandler, etc., ?</p> <p>Thanks for any advice on this ... I think I'm being redundant and don't want pointless code, not to mention avoiding the DRY principle.</p> <p>{edit}Just wanted to post the remainder of the code, and stress that the "work" an instance of this class performs is done on a separate thread.{/edit}</p> <pre><code>#Region "Delegates" Public Delegate Sub TimerElapsedDelegate(ByVal sender As Object, ByVal e As System.EventArgs) Public Event TimerElapsed(ByVal sender As Object, ByVal e As System.EventArgs) Private _TimerElapsed As TimerElapsedDelegate = Nothing Public Property OnTimerElapsed() As TimerElapsedDelegate Get Return _TimerElapsed End Get Set(ByVal value As TimerElapsedDelegate) If value Is Nothing Then _TimerElapsed = Nothing Else If _TimerElapsed Is Nothing Then _TimerElapsed = value Else _TimerElapsed = System.Delegate.Combine(_TimerElapsed, value) End If End If End Set End Property Private Sub TriggerTimerElapsed() If OnTimerElapsed IsNot Nothing Then OnTimerElapsed.Invoke(Me, New System.EventArgs) End If RaiseEvent TimerElapsed(Me, New System.EventArgs) End Sub Public Delegate Sub ItemReadyForQueueDelegate(ByVal sender As Object, ByVal e As System.EventArgs) Public Event ItemReadyForQueue(ByVal sender As Object, ByVal e As System.EventArgs) Private _ItemReadyForQueue As ItemReadyForQueueDelegate = Nothing Public Property OnItemReadyForQueue() As ItemReadyForQueueDelegate Get Return _ItemReadyForQueue End Get Set(ByVal value As ItemReadyForQueueDelegate) If value Is Nothing Then _ItemReadyForQueue = Nothing Else If _ItemReadyForQueue Is Nothing Then _ItemReadyForQueue = value Else _ItemReadyForQueue = System.Delegate.Combine(_ItemReadyForQueue, value) End If End If End Set End Property Private Sub TriggerItemReadyForQueue(ByVal oItem As h3Budgeteer.FileSystem.ReportTemplateFile.ReportTemplate) If OnItemReadyForQueue IsNot Nothing Then OnItemReadyForQueue.Invoke(Me, New ItemReadyForQueueEventArgs(oItem)) End If RaiseEvent ItemReadyForQueue(Me, New ItemReadyForQueueEventArgs(oItem)) End Sub Public Class ItemReadyForQueueEventArgs Inherits System.EventArgs Private _ReportTemplate As h3Budgeteer.FileSystem.ReportTemplateFile.ReportTemplate = Nothing Public ReadOnly Property ReportTemplate() As h3Budgeteer.FileSystem.ReportTemplateFile.ReportTemplate Get Return _ReportTemplate End Get End Property Public Sub New(ByVal oReportTemplate As h3Budgeteer.FileSystem.ReportTemplateFile.ReportTemplate) _ReportTemplate = oReportTemplate End Sub End Class </code></pre> <h1>End Region</h1>
<p>I would say just completely remove your delegate entirely.</p> <p>Your delegate is doing exactly the same thing as the event. You are pretty much writing your own event plumbing instead of using the framework's Event call. An Event is pretty much exactly what you've written, except that it's easier to use, and also makes it easier to unsubscribe from the event.</p> <p>There is no advantage to providing both - The event does everything that your "delegate" does, and is much more clear.</p> <p>(Previously:)</p> <blockquote> <p>If you're developing this as a class library, I would suggest just making your class not be sealed, and following the more standard approach. The normal approach for allowing logic to be overridden or inserted into your code and allowing events would be to provide hooks for subclassing.</p> <p>Delegates could be used in a situation like this to allow the user to plug in their own logic. However, in many cases, having protected virtual functions makes this more clear, and much easier to accomplish.</p> <p>Events should be exactly that, an event that notifies the user of some "event". These should be hooks where the user attaches their delegate.</p> <p>For example, instead of providing delegates and events, the base Windows Forms controls use a protected method (ie: OnMouseDown) and an event that's triggered by default (MouseDown).</p> <p>This allows a user to subclass your class and override the logic (which is probably why you'd want delegates) as well as handle the event.</p> <p>The one place where I would provide delegates is in rare cases where your class or method REQUIRES logic to be added by a user. In this case, you can either provide an abstract base class, or have a delegate that is passed in for that logic. A good example of this is the .Where() method in LINQ. Where is useless without the predicate used for filtering, so passing in a delegate makes sense in this case. Note, though, that there is no event associated with this - it's really there to provide a different function.</p> </blockquote>
How can I remove unused, nested HTML span tags with a Perl regex? <p>I'm trying to remove unused spans (i.e. those with no attribute) from HTML files, having already cleaned up all the attributes I didn't want with other regular expressions.</p> <p>I'm having a problem with my regex not picking the correct pair of start and end tags to remove.</p> <pre><code>my $a = 'a &lt;span&gt;b &lt;span style="color:red;"&gt;c&lt;/span&gt; d&lt;/span&gt;e'; $a =~ s/&lt;span\s*&gt;(.*?)&lt;\/span&gt;/$1/g; print "$a\ </code></pre> <p>returns</p> <pre><code>a b &lt;span style="color:red;"&gt;c d&lt;/span&gt;e </code></pre> <p>but I want it to return</p> <pre><code>a b &lt;span style="color:red;"&gt;c&lt;/span&gt; de </code></pre> <p>Help appreciated.</p>
<p>Try <a href="http://search.cpan.org/perldoc?HTML::Parser">HTML::Parser</a>:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use HTML::Parser; my @print_span; my $p = HTML::Parser-&gt;new( start_h =&gt; [ sub { my ($text, $name, $attr) = @_; if ( $name eq 'span' ) { my $print_tag = %$attr; push @print_span, $print_tag; return if !$print_tag; } print $text; }, 'text,tagname,attr'], end_h =&gt; [ sub { my ($text, $name) = @_; if ( $name eq 'span' ) { return if !pop @print_span; } print $text; }, 'text,tagname'], default_h =&gt; [ sub { print shift }, 'text'], ); $p-&gt;parse_file(\*DATA) or die "Err: $!"; $p-&gt;eof; __END__ &lt;html&gt; &lt;head&gt; &lt;title&gt;This is a title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;This is a header&lt;/h1&gt; a &lt;span&gt;b &lt;span style="color:red;"&gt;c&lt;/span&gt; d&lt;/span&gt;e &lt;/body&gt; &lt;/html&gt; </code></pre>
Databound DataGridView Empty Despite Full DataSource <p>I have a base form class that contains a method that returns a DataTable:</p> <pre><code>protected DataTable GetTableData(string sql, OracleConnection connection) { DataTable table = null; OracleDataAdapter adapter = null; try { table = new DataTable(); adapter = new OracleDataAdapter(sql, connection); table.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.Fill(table); } catch (Exception e) { MessageBox.Show("An error occurred while trying to process your request:\n\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (null != adapter) { adapter.Dispose(); } } return table; } </code></pre> <p>Another window is a subclass of it, and invokes it as follows:</p> <pre><code>private void LoadViewData(OracleConnection connection) { DataTable table = null; try { var sql = "SELECT * FROM " + this.ObjectName; table = GetTableData(sql, connection); this.resultBindingSource.DataSource = table; } catch (Exception e) { MessageBox.Show("An error occurred while trying to process your request:\n\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { this.sqlEditor.Focus(); } } </code></pre> <p><code>resultBindingSource</code> is a <code>System.Windows.Forms.BindingSource</code>. It is set as the <code>DataSource</code> property of a <code>System.Windows.Forms.DataGridView</code>. (The expression, <code>this.ObjectName</code>, evaluates to the name of a table or view in the database.)</p> <p>When I run through the code in the debugger, I can see that the SQL executes just fine. I can see that the <code>DataTable</code> contains data. I can see that the <code>DataGridView</code> control is properly bound to the data source, and that I can see the data in the data table through its <code>DataSource</code> property. However, no data is displayed in the control itself. There are no row or column headers, and no data is displayed whatsoever.</p> <p>I have tried everything I can think of to pin down the cause of this problem. This code works exactly as shown on another form. I tried deleting the controls in question and recreating them, to no avail. I consulted the articles on MSDN on how to properly databind to a <code>DataGridView</code> control. I tried it with and without an <code>OracleCommandBuilder</code> (which doesn't seem necessary to me, since this is a read-only view of the data).</p> <p>I'm frankly out of ideas. It's likely something fairly obvious that I've overlooked. I know that databinding works, because I've done it before with great success.</p> <p>Any pointers in the right direction would be greatly appreciated.</p>
<p>I tried recreating your program using the pieces you mentioned here. I didn't actually get data from a datatable but that's irrelevant. Here's what I did:</p> <pre><code>public partial class Form1 : BaseForm { BindingSource source = new BindingSource(); public Form1() { InitializeComponent(); this.dataGridView1.DataSource = source; } private void button1_Click(object sender, EventArgs e) { DataTable table = GetDataTable(); this.source.DataSource = table; } } public class BaseForm : Form { protected DataTable GetDataTable() { DataTable result = new DataTable(); result.Columns.Add("Name"); result.Columns.Add("Age", typeof(int)); result.Rows.Add("Alex", 27); return result; } } </code></pre> <p>Is this roughly the same thing you have? I had no issues at all. Based on what you're posting this SHOULD work. Are you sure you're binding everything to each other correctly? Post more of your binding code if possible...</p>
Absolute value for floats in core OCaml <p>I am in need of an absolute value function for floats in OCaml and the core language doesn't seem to possess one, so I wrote the following:</p> <pre><code>let absF (f:float) = if f &gt; 0.0 then f else (f *. -1.0);; </code></pre> <p>which seems to work for positives but not for negatives, citing: </p> <p>This expression has type float -> float but is here used with type int</p> <p>What is the error in my logic?</p>
<p>The core language does have one, <code>abs_float</code>.</p> <p>Also, you can use <code>~-.</code> to denote unary negation, and this applies to integers as well with the <code>~-</code> operator. You can define such an operator (even though it already exists) like this:</p> <pre><code>let (~-) a : int = 0 - a let (~-.) a : float = 0.0 -. a </code></pre>
Specifying Tab-Width? <p>Is it possible to define the tab-width when whitespace is displayed (say within a &lt;pre&gt; tag or something)? I can't find anything to do this with CSS, but this seems like it would be a pretty common thing to want to do.</p> <p>In my case, the tab width is so wide that it causes some of my code snippets on a page to be too wide. If I could somehow shorten the tab-width to make it fit without scrollbars it would make things much easier. (I suppose I could just replace the tabs with spaces, but ideally I would love to find a way to do this without doing that)</p>
<p>Use the <a href="http://www.w3.org/TR/css3-text/#tab-size">tab-size property</a>. You’ll need vendor prefixes currently. Example:</p> <pre><code>pre { -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; } </code></pre> <p>See also the article on developer.mozilla.org: <a href="https://developer.mozilla.org/en-US/docs/CSS/tab-size">tab-size</a>.</p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.tabstop { -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>Unstyled tabs (browser default) &lt;pre&gt; one tab two tabs three tabs &lt;/pre&gt; Styled tabs (4em) &lt;pre class="tabstop"&gt; one tab two tabs three tabs &lt;/pre&gt;</code></pre> </div> </div> </p>
strptime in windows? <p>I wrote this really nice app that works just fine in Linux.</p> <p>It uses strptime(). Windows doesn't have this.</p> <p>Is there a Windows alternative for this?</p> <p>My coworker needs to use this app.</p> <p>(I tried googling it already to no avail)</p>
<p>I have written a strptime which I use on Windows to make up for it's absence in the Microsoft C runtime library. Here it is:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;ctype.h&gt; #ifdef _MSC_VER const char * strp_weekdays[] = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; const char * strp_monthnames[] = { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}; bool strp_atoi(const char * &amp; s, int &amp; result, int low, int high, int offset) { bool worked = false; char * end; unsigned long num = strtoul(s, &amp; end, 10); if (num &gt;= (unsigned long)low &amp;&amp; num &lt;= (unsigned long)high) { result = (int)(num + offset); s = end; worked = true; } return worked; } char * strptime(const char *s, const char *format, struct tm *tm) { bool working = true; while (working &amp;&amp; *format &amp;&amp; *s) { switch (*format) { case '%': { ++format; switch (*format) { case 'a': case 'A': // weekday name tm-&gt;tm_wday = -1; working = false; for (size_t i = 0; i &lt; 7; ++ i) { size_t len = strlen(strp_weekdays[i]); if (!strnicmp(strp_weekdays[i], s, len)) { tm-&gt;tm_wday = i; s += len; working = true; break; } else if (!strnicmp(strp_weekdays[i], s, 3)) { tm-&gt;tm_wday = i; s += 3; working = true; break; } } break; case 'b': case 'B': case 'h': // month name tm-&gt;tm_mon = -1; working = false; for (size_t i = 0; i &lt; 12; ++ i) { size_t len = strlen(strp_monthnames[i]); if (!strnicmp(strp_monthnames[i], s, len)) { tm-&gt;tm_mon = i; s += len; working = true; break; } else if (!strnicmp(strp_monthnames[i], s, 3)) { tm-&gt;tm_mon = i; s += 3; working = true; break; } } break; case 'd': case 'e': // day of month number working = strp_atoi(s, tm-&gt;tm_mday, 1, 31, 0); break; case 'D': // %m/%d/%y { const char * s_save = s; working = strp_atoi(s, tm-&gt;tm_mon, 1, 12, -1); if (working &amp;&amp; *s == '/') { ++ s; working = strp_atoi(s, tm-&gt;tm_mday, 1, 31, 0); if (working &amp;&amp; *s == '/') { ++ s; working = strp_atoi(s, tm-&gt;tm_year, 0, 99, 0); if (working &amp;&amp; tm-&gt;tm_year &lt; 69) tm-&gt;tm_year += 100; } } if (!working) s = s_save; } break; case 'H': // hour working = strp_atoi(s, tm-&gt;tm_hour, 0, 23, 0); break; case 'I': // hour 12-hour clock working = strp_atoi(s, tm-&gt;tm_hour, 1, 12, 0); break; case 'j': // day number of year working = strp_atoi(s, tm-&gt;tm_yday, 1, 366, -1); break; case 'm': // month number working = strp_atoi(s, tm-&gt;tm_mon, 1, 12, -1); break; case 'M': // minute working = strp_atoi(s, tm-&gt;tm_min, 0, 59, 0); break; case 'n': // arbitrary whitespace case 't': while (isspace((int)*s)) ++s; break; case 'p': // am / pm if (!strnicmp(s, "am", 2)) { // the hour will be 1 -&gt; 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm if (tm-&gt;tm_hour == 12) // 12 am == 00 hours tm-&gt;tm_hour = 0; s += 2; } else if (!strnicmp(s, "pm", 2)) { if (tm-&gt;tm_hour &lt; 12) // 12 pm == 12 hours tm-&gt;tm_hour += 12; // 1 pm -&gt; 13 hours, 11 pm -&gt; 23 hours s += 2; } else working = false; break; case 'r': // 12 hour clock %I:%M:%S %p { const char * s_save = s; working = strp_atoi(s, tm-&gt;tm_hour, 1, 12, 0); if (working &amp;&amp; *s == ':') { ++ s; working = strp_atoi(s, tm-&gt;tm_min, 0, 59, 0); if (working &amp;&amp; *s == ':') { ++ s; working = strp_atoi(s, tm-&gt;tm_sec, 0, 60, 0); if (working &amp;&amp; isspace((int)*s)) { ++ s; while (isspace((int)*s)) ++s; if (!strnicmp(s, "am", 2)) { // the hour will be 1 -&gt; 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm if (tm-&gt;tm_hour == 12) // 12 am == 00 hours tm-&gt;tm_hour = 0; } else if (!strnicmp(s, "pm", 2)) { if (tm-&gt;tm_hour &lt; 12) // 12 pm == 12 hours tm-&gt;tm_hour += 12; // 1 pm -&gt; 13 hours, 11 pm -&gt; 23 hours } else working = false; } } } if (!working) s = s_save; } break; case 'R': // %H:%M { const char * s_save = s; working = strp_atoi(s, tm-&gt;tm_hour, 0, 23, 0); if (working &amp;&amp; *s == ':') { ++ s; working = strp_atoi(s, tm-&gt;tm_min, 0, 59, 0); } if (!working) s = s_save; } break; case 'S': // seconds working = strp_atoi(s, tm-&gt;tm_sec, 0, 60, 0); break; case 'T': // %H:%M:%S { const char * s_save = s; working = strp_atoi(s, tm-&gt;tm_hour, 0, 23, 0); if (working &amp;&amp; *s == ':') { ++ s; working = strp_atoi(s, tm-&gt;tm_min, 0, 59, 0); if (working &amp;&amp; *s == ':') { ++ s; working = strp_atoi(s, tm-&gt;tm_sec, 0, 60, 0); } } if (!working) s = s_save; } break; case 'w': // weekday number 0-&gt;6 sunday-&gt;saturday working = strp_atoi(s, tm-&gt;tm_wday, 0, 6, 0); break; case 'Y': // year working = strp_atoi(s, tm-&gt;tm_year, 1900, 65535, -1900); break; case 'y': // 2-digit year working = strp_atoi(s, tm-&gt;tm_year, 0, 99, 0); if (working &amp;&amp; tm-&gt;tm_year &lt; 69) tm-&gt;tm_year += 100; break; case '%': // escaped if (*s != '%') working = false; ++s; break; default: working = false; } } break; case ' ': case '\t': case '\r': case '\n': case '\f': case '\v': // zero or more whitespaces: while (isspace((int)*s)) ++ s; break; default: // match character if (*s != *format) working = false; else ++s; break; } ++format; } return (working?(char *)s:0); } #endif // _MSC_VER </code></pre> <p>I referred to the online man page <a href="http://linux.die.net/man/3/strptime" rel="nofollow" title="man strptime&#40;3&#41;">man strptime(3)</a> when writing this function.</p>
Signalling Initialization Failure from Service.OnStart <p>We have a case where during Service startup (OnStart), a worker thread is started. The worker thread connects to a SQL database. If the database is unavailable, the worker thread can signal the main thread of the failure. The question is; How to signal the Service Control Manager that startup has failed.</p>
<p>This is how we handled this situation. This code was added to our main service class and then at the point where we wanted to return startup as failed, made a call to SetServiceFail(1065) followed by a return from OnStart. In this case 1065 returns a database does not exist status.</p> <p>I would also note that in SetServiceFail I hard-coded the serviceType since in our case all of our services are stand-alone so I kept it simple.</p> <pre><code>private void SetServiceFail (int ErrorCode) { SERVICE_STATUS _ServiceStatus = new SERVICE_STATUS (); _ServiceStatus.currentState = (int) State.SERVICE_STOPPED; _ServiceStatus.serviceType = 16; //SERVICE_WIN32_OWN_PROCESS _ServiceStatus.waitHint = 0; _ServiceStatus.win32ExitCode = ErrorCode; _ServiceStatus.serviceSpecificExitCode = 0; _ServiceStatus.checkPoint = 0; _ServiceStatus.controlsAccepted = 0 | (this.CanStop ? (int) ControlsAccepted.ACCEPT_STOP : 0) | (this.CanShutdown ? (int) ControlsAccepted.ACCEPT_SHUTDOWN : 0) | (this.CanPauseAndContinue ? (int) ControlsAccepted.ACCEPT_PAUSE_CONTINUE : 0) | (this.CanHandleSessionChangeEvent ? (int) ControlsAccepted.ACCEPT_SESSION_CHANGE : 0) | (this.CanHandlePowerEvent ? (int) ControlsAccepted.ACCEPT_POWER_EVENT : 0); SetServiceStatus (this.ServiceHandle, ref _ServiceStatus); } public enum State { SERVICE_STOPPED = 1, SERVICE_START_PENDING = 2, SERVICE_STOP_PENDING = 3, SERVICE_RUNNING = 4, SERVICE_CONTINUE_PENDING = 5, SERVICE_PAUSE_PENDING = 6, SERVICE_PAUSED = 7 } public enum ControlsAccepted { ACCEPT_STOP = 1, ACCEPT_PAUSE_CONTINUE = 2, ACCEPT_SHUTDOWN = 4, ACCEPT_POWER_EVENT = 64, ACCEPT_SESSION_CHANGE = 128 } [StructLayout (LayoutKind.Sequential)] private struct SERVICE_STATUS { public int serviceType; public int currentState; public int controlsAccepted; public int win32ExitCode; public int serviceSpecificExitCode; public int checkPoint; public int waitHint; } [DllImport ("advapi32.dll")] private static extern bool SetServiceStatus (IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus); </code></pre>
SQLite database - cannot see updates <p>I have a sqlite database and I am adding to it new words. The problem is that I can see them added to a table only after restarting application. The "SELECT" statement doesn't "see" newly added elements before restarting application.</p> <p>Why may this happen?</p> <p>I am creating some kind of a dictionary. Here is how I add new items:</p> <pre><code>const char *sql_query = "INSERT INTO words(word) VALUES(?)"; if(sqlite3_prepare_v2(database, sql_query, -1, &amp;addWordsStmt, NULL) != SQLITE_OK) { return FALSE; } sqlite3_bind_text(addWordsStmt, 1, [ word UTF8String], -1, SQLITE_TRANSIENT); if( sqlite3_step(addWordsStmt) != SQLITE_DONE) NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); sqlite3_reset(addWordsStmt); sqlite3_finalize(addWordsStmt); </code></pre> <p>And here is my retrieval code:</p> <pre><code>const char *sql_query = "SELECT word FROM words WHERE id=?"; if(sqlite3_prepare_v2(database, sql_query, -1, &amp;getWordsStmt, NULL) != SQLITE_OK) { return; } sqlite3_bind_int(getWordsStmt, 1, wordid); if( sqlite3_step(getWordsStmt) != SQLITE_ROW) { NSLog(@"Error while getting data. '%s'", sqlite3_errmsg(database)); sqlite3_reset(getWordsStmt); return; } NSString *word = [NSString stringWithUTF8String:(char *)sqlite3_column_text(getWordsStmt, 0)]; sqlite3_reset(getWordsStmt); sqlite3_finalize(getWordsStmt); </code></pre>
<p>There's your problem:</p> <pre><code>const char *sql_query = "SELECT word FROM words WHERE id=?"; </code></pre> <p>This isn't how you use SQL. Instead, you should be using <code>SELECT word FROM words;</code> and stepping to get each row as long as you're getting <code>SQLITE_ROW</code> until you get <code>SQLITE_DONE</code>. That will get you all your words. How are you going to find a word by id when you don't know the id of newly added words?</p>
Browser Java Plugin Detection <p>What is the preferred method to determine if the Sun Java Plugin is installed in the browser?</p>
<p><a href="http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment%5Fadvice.html#deplToolkit" rel="nofollow">java deployment toolkit</a></p> <pre> script src="http://java.com/js/deployJava.js" if (deployJava.versionCheck('1.6')) { alert("1.6 installed") } </pre>
The Benefits of Using Function Pointers <p>I have been programming for a few years now and have used function pointers in certain cases. What I would like to know is when is it appropriate or not to use them for performance reasons and I mean in the context of games, not business software.</p> <p>Function pointers are fast, John Carmack used them to the extent of abuse in the Quake and Doom source code and because he is a genius :)</p> <p>I would like to use function pointers more but I want to use them where they are most appropriate. </p> <p>These days what are the best and most practical uses of function pointers in modern c-style languages such as C, C++, C# and Java, etc?</p>
<p>There is nothing especially "fast" about function pointers. They allow you to call a function which is specified at runtime. But you have exactly the same overhead as you'd get from any other function call (plus the additional pointer indirection). Further, since the function to call is determined at runtime, the compiler can typically not inline the function call as it could anywhere else. As such, function pointers may in some cases add up to be significantly slower than a regular function call.</p> <p>Function pointers have nothing to do with performance, and should never be used to gain performance.</p> <p>Instead, they are a very slight nod to the functional programming paradigm, in that they allow you to pass a function around as parameter or return value in another function.</p> <p>A simple example is a generic sorting function. It has to have some way to compare two elements in order to determine how they should be sorted. This could be a function pointer passed to the sort function, and in fact c++'s std::sort() can be used exactly like that. If you ask it to sort sequences of a type that does not define the less than operator, you have to pass in a function pointer it can call to perform the comparison.</p> <p>And this leads us nicely to a superior alternative. In C++, you're not limited to function pointers. You often use functors instead - that is, classes that overload the operator(), so that they can be "called" as if they were functions. Functors have a couple of big advantages over function pointers: </p> <ul> <li>They offer more flexibility: they're full-fledged classes, with constructor, destructor and member variables. They can maintain state, and they may expose other member functions that the surrounding code can call.</li> <li>They are faster: unlike function pointers, whose type only encode the signature of the function (a variable of type <code>void (*)(int)</code> may be <em>any</em> function which takes an int and returns void. We can't know which one), a functor's type encodes the precise function that should be called (Since a functor is a class, call it C, we know that the function to call is, and will always be, C::operator()). And this means the compiler can inline the function call. That's the magic that makes the generic std::sort just as fast as your hand-coded sorting function designed specifically for your datatype. The compiler can eliminate all the overhead of calling a user-defined function.</li> <li>They are safer: There's very little type safety in a function pointer. You have no guarantee that it points to a valid function. It could be NULL. And most of the problems with pointers apply to function pointers as well. They're dangerous and error-prone.</li> </ul> <p>Function pointers (in C) or functors (in C++) or delegates (in C#) all solve the same problem, with different levels of elegance and flexibility: They allow you to treat functions as first-class values, passing them around as you would any other variable. You can pass a function to another function, and it will call your function at specified times (when a timer expires, when the window needs redrawing, or when it needs to compare two elements in your array)</p> <p>As far as I know (and I could be wrong, because I haven't worked with Java for ages), Java doesn't have a direct equivalent. Instead, you have to create a class, which implements an interface, and defines a function (call it Execute(), for example). And then instead of calling the user-supplied function (in the shape of a function pointer, functor or delegate), you call foo.Execute(). Similar to the C++ implementation in principle, but without the generality of C++ templates, and without the function syntax that allows you to treat function pointers and functors the same way.</p> <p>So that is where you use function pointers: When more sophisticated alternatives are not available (ie. you are stuck in C), and you need to pass one function to another. The most common scenario is a callback. You define a function F that you want the system to call when X happens. So you create a function pointer pointing to F, and pass that to the system in question.</p> <p>So really, forget about John Carmack and don't assume that anything you sees in his code will magically make your code better if you copy it. He used function pointers because the games you mention were written in C, where superior alternatives are not available, and not because they are some magical ingredient whose mere existence makes code run faster.</p>
How to debug a weird threaded open fifo issue? <p>A web service is configured to expose some of its data when receiving a USR1 signal. The signal will be sent by a xinetd server when it receives a request from a remote client, e.g. nc myserver 50666. When the web server receives USR1 signal, it opens a dedicated fifo pipe, writes its data to the pipe, and then close the pipe. In the meantime, the xinetd server reads the pipe and feeds to the remote client.</p> <p>In most of times, they work nicely but occasionally, for some reason, the client will receive dup records. From the log, it seems like the pipe did not get closed properly and the cache is leftover, so when next time it serves, both previous and current are sent to the client. The problem is its not constantly happening when trying to reproduce, unluckily, I wasn't able to reproduce once. </p> <p>The following are the simple snippets to demonstrate the process:</p> <p>The web server: (webserver.py)</p> <pre><code>def SendStream(data, pipe): try: for i in data: pipe.write(i + '\n') pipe.flush() finally: pipe.close() def Serve(): threading.Thread(target=SendStream, args=(data, pipe)).start() </code></pre> <p>The xinetd.d server: (spitter.py)</p> <pre><code>def Serve(): if not os.path.exists(PIPE_FILE): os.mkfifo(PIPE_FILE) os.kill(server_pid, signal.SIGUSR1) for i in open(PIPE_FILE): print i, </code></pre> <p>So what exactly happened to cause the dup? How to trigger it? The current fix I unlink the pipe file and recreate it every time to avoid any leftovers but I don't know if that's a proper solution.</p>
<p>If you get two copies of splitter.py running at the same time, there will be trouble and almost anything that happens to you is legal. Try adding a process id value to webserver.py, ie:</p> <p>pipe.write(str(os.getpid()) + i + '\n')</p> <p>That might be illuminating.</p>
Is there a way to manually register a user with a py-transport server-side? <p>I'm trying to write some scripts to migrate my users to ejabberd, but the only way that's been suggested for me to register a user with a transport is to have them use their client and discover the service. Certainly there is a way, right? </p>
<ol> <li>Go through once for each transport and register yourself. Capture the XMPP packets. </li> <li>Dump the transport registration data from your current system into a csv file, xml file, or something else you can know the structure.</li> <li>Write a script using jabberpy, xmpppy, pyxmpp, or whatever, and emulate each of your users registering with the transports.</li> </ol> <p>One issue is you may have to be connected to the Internet for the transports to come online. Then you're going live with someone else's account. If you can't get their current password data for your jabber server, set it all to a default and then migrate it back after your transport registration.</p>
Full command line as it was typed <p>I want to get the full command line as it was typed. </p> <p>This: </p> <p><code>" ".join(sys.argv[:])</code> </p> <p>doesn't work here (deletes double quotes). Also I prefer not to rejoin something that was parsed and splited.</p> <p>Any ideas? </p> <p>Thank you in advance.</p>
<p>You're too late. By the time that the typed command gets to Python your shell has already worked its magic. For example, quotes get consumed (as you've noticed), variables get interpolated, etc.</p>
How to tell if a connection is dead in python <p>I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this?</p>
<p>It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.</p>
Truly multi-lingual programming languages? <p>I realize most languages support multiple languages, but every language I've seen has always been more-or-less US-centric. By that, I mean the keywords, standard library functions, etc. all have english names. So, as a programmer, you still really need to know at least some english to make sense of it.</p> <p>Are there any truly "multi-lingual" languages out there with support for language keywords and such in multiple languages?</p>
<p>This is generally a horrible idea, as anyone who's worked in a localized IDE can attest to. Programmers rely heavily on having one common vocabulary. When the compiler gives me the error "missing type specifier - int assumed", I can share this exact error message with others, for example here on SO, and it will be <em>familiar</em> to those others so they can tell me what it means. If the compiler instead generated error messages in Danish, I'd be limited to getting help from the relatively few programmers who speak Danish.</p> <p>Suddenly my vocabulary is no longer the same as someone in the same position in Germany, France or Japan. We can no longer exchange code, bugs, bug fixes or ideas.</p> <p>A developer in Spain wouldn't be able to use my code because it was literally written in another language. And if I had trouble with my code, others would be helpless to debug it, because it wouldn't even compile under their localization settings (and if it did, it'd still be unreadable to them).</p> <p>Ultimately, a programming language is <em>a language</em>. It may have borrowed some words from English, but it <em>is</em> not English, and you do not need to understand English to program in it, any more than I need to understand latin in order to speak English (English borrows latin words as well).</p> <p>You might as well ask for a multi-lingual English. <em>What would be the point</em>? Yes, it would in theory allow people who didn't speak English to... speak English. It just wouldn't be the same English as every other English-speaker speaks, so it wouldn't actually enable communication between them.</p> <p>The keyword <code>if</code> in a programming language is <em>not</em> the same as if in the English language. They mean different things, even though one was obviously inspired by the other.</p> <p>The <code>delegate</code> keyword in C# does not mean the same thing as "delegate" in English. Nor does <code>while</code>, <code>return</code> or "constructor". They are not english words, they are keywords or concepts in C++, Java, C#, Python or any other programming language.</p>
Passing information back from a UserControl <p>I am just getting to grips with the concept of a UserControl.</p> <p>I've created a UserControl to group together a number of controls that were being duplicated on individual pages of a TabControl.</p> <p>Some of these controls are text fields that require validation, and when validation is unsuccessful I need to display an error message. However the place where I want to display the error message is on the status bar on the main form.</p> <p>What is the best way to handle validation/error display in this situation?</p>
<p><strong>To handle validation do one of these:</strong></p> <ul> <li>Validate with a method inside the user control</li> <li><p>Have your user control have a <a href="http://msdn.microsoft.com/en-us/library/ms173171%28VS.80%29.aspx" rel="nofollow"><code>delegate</code></a> property (e.g. <code>ValidationHandler</code>) that can handle the validation (this would allow you to have a class with a bunch of validators that you could assign to your controls)</p> <p><code>public delegate void Validator(...)</code></p> <p><code>public Validator ValidationHandler { get; set; }</code></p></li> <li><p>Have your user control generate a validation request <a href="http://msdn.microsoft.com/en-us/library/awbftdfh.aspx" rel="nofollow"><code>event</code></a> (e.g. <code>ValidationRequested</code>)</p> <p><code>public event EventHandler&lt;ValidationEventArgs&gt; ValidationRequested</code></p></li> </ul> <p><strong>To notify the system that an error has occurred do one of these:</strong></p> <ul> <li><p>Use an <a href="http://msdn.microsoft.com/en-us/library/awbftdfh.aspx" rel="nofollow"><code>event</code></a> that interested parties can subscribe to (e.g. <code>ValidationFailed</code>)</p></li> <li><p>If the object that performs the validation (via the <code>delegate</code> or <code>event</code>) is also the one that you want to generate the error message from, it can raise the error message itself.</p></li> </ul> <p><strong>EDIT:</strong></p> <p>Since you've said you would validate inside your control, the code for a ValidationFailed event might look like:</p> <pre><code>// In your user control public class ValidationFailedEventArgs : EventArgs { public ValidationFailedEventArgs(string message) { this.Message = message; } public string Message { get; set; } } private EventHandler&lt;ValidationFailedEventArgs&gt; _validationFailed; public event EventHandler&lt;ValidationFailedEventArgs&gt; ValidationFailed { add { _validationFailed += value; } remove { _validationFailed -= value; } } protected void OnValidationFailed(ValidationFailedEventArgs e) { if(_validationFailed != null) _validationFailed(this, e); } private void YourValidator() { if(!valid) { ValidationFailedEventArgs args = new ValidationFailedEventArgs("Your Message"); OnValidationFailed(args); } } // In your main form: userControl.ValidationFailed += new EventHandler&lt;ValidationFailedEventArgs&gt;(userControl_ValidationFailed); // ... private void userControl_ValidationFailed(object sender, ValidationFailedEventArgs e) { statusBar.Text = e.Message; } </code></pre>
How do I create a D-Bus service that dynamically creates multiple objects? <p>I'm new to D-Bus (and to Python, double whammy!) and I am trying to figure out the best way to do something that was discussed in the tutorial.</p> <blockquote> <p>However, a text editor application could as easily own multiple bus names (for example, org.kde.KWrite in addition to generic TextEditor), have multiple objects (maybe /org/kde/documents/4352 where the number changes according to the document), and each object could implement multiple interfaces, such as org.freedesktop.DBus.Introspectable, org.freedesktop.BasicTextField, org.kde.RichTextDocument.</p> </blockquote> <p>For example, say I want to create a wrapper around <code>flickrapi</code> such that the service can expose a handful of Flickr API methods (say, <code>urls_lookupGroup()</code>). This is relatively straightforward if I want to assume that the service will always be specifying the same API key and that the auth information will be the same for everyone using the service.</p> <p>Especially in the latter case, I cannot really assume this will be true.</p> <p>Based on the documentation quoted above, I am assuming there should be something like this:</p> <pre><code># Get the connection proxy object. flickrConnectionService = bus.get_object("com.example.FlickrService", "/Connection") # Ask the connection object to connect, the return value would be # maybe something like "/connection/5512" ... flickrObjectPath = flickrConnectionService.connect("MY_APP_API_KEY", "MY_APP_API_SECRET", flickrUsername) # Get the service proxy object. flickrService = bus.get_object("com.example.FlickrService", flickrObjectPath); # As the flickr service object to get group information. groupInfo = flickrService.getFlickrGroupInfo('s3a-belltown') </code></pre> <p>So, my questions:</p> <p>1) Is this how this should be handled?</p> <p>2) If so, how will the service know when the client is done? Is there a way to detect if the current client has broken connection so that the service can cleanup its dynamically created objects? Also, how would I create the individual objects in the first place?</p> <p>3) If this is not how this should be handled, what are some other suggestions for accomplishing something similar?</p> <p>I've read through a number of D-Bus tutorials and various documentation and about the closest I've come to seeing what I am looking for is what I quoted above. However, none of the examples look to actually do anything like this so I am not sure how to proceed.</p>
<p>1) Mostly yes, I would only change one thing in the connect method as I explain in 2). </p> <p>2) D-Bus connections are not persistent, everything is done with request/response messages, no connection state is stored unless you implement this in third objects as you do with your <code>flickerObject</code>. The d-bus objects in python bindings are mostly proxies that abstract the remote objects as if you were "connected" to them, but what it really does is to build messages based on the information you give to D-Bus object instantiation (object path, interface and so). So the service cannot know when the client is done if client doesn't announce it with other explicit call.</p> <p>To handle unexpected client finalization you can create a D-Bus object in the client and send the object path to the service when connecting, change your <code>connect</code> method to accept also an <code>ObjectPath</code> parameter. The service can listen to <strong><code>NameOwnerChanged</code></strong> signal to know if a client has died.</p> <p>To create the individual object you only have to instantiate an object in the same service as you do with your "/Connection", but you have to be sure that you are using an unexisting name. You could have a "/Connection/Manager", and various "/Connection/1", "/Connection/2"...</p> <p>3) If you need to store the connection state, you have to do something like that.</p>
Simple recursion problem <p>I'm taking my first steps into recursion and dynamic programming and have a question about forming subproblems to model the recursion. </p> <p>Problem:</p> <blockquote> <p>How many different ways are there to flip a fair coin 5 times and not have three or more heads in a row?</p> </blockquote> <p>If some could put up some heavily commented code (Ruby preferred but not essential) to help me get there. I am not a student if that matters, this is a modification of a <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problem to make it very simple for me to grasp. I just need to get the hang of writing recursion formulas.</p> <p>If you would like to abstract the problem into how many different ways are there to flip a fair coin Y times and not have Z or more heads in a row, that may be beneficial as well. Thanks again, this website rocks. </p>
<p>You can simply create a formula for that:</p> <p>The number of ways to flip a coin 5 times without having 3 heads in a row is equal to the number of combinations of 5 coin flips minus the combinations with at least three heads in a row. In this case:</p> <pre><code>HHH-- (4 combinations) THHH- (2 combinations) TTHHH (1 combination) </code></pre> <p>The total number of combinations = 2^5 = 32. And 32 - 7 = 25.</p> <p>If we flip a coin N times without Q heads in a row, the total amount is 2^N and the amount with at least Q heads is 2^(N-Q+1)-1. So the general answer is:</p> <pre><code>Flip(N,Q) = 2^N - 2^(N-Q+1) +1 </code></pre> <p>Of course you can use recursion to simulate the total amount:</p> <pre><code>flipme: N x N -&gt; N flipme(flipsleft, maxhead) = flip(flipsleft, maxhead, 0) flip: N x N x N -&gt; N flip(flipsleft, maxhead, headcount) == if flipsleft &lt;= 0 then 0 else if maxhead&lt;=headcount then 0 else flip(flipsleft - 1, maxhead, headcount+1) + // head flip(flipsleft - 1, maxhead, maxhead) // tail </code></pre>
Getting stored procedure usage data on SQL Server 2000 <p>What is the best way to get stored procedure useage data on a specific database out of SQL Server 2000?</p> <p>The data I need is:</p> <ol> <li>Total of all stored procedure calls over X time</li> <li>Total of each specific stored procedure call over X time.</li> <li>Total time spent processing all stored procedures over X time.</li> <li>Total time spent processing specific stored procedures over X time.</li> </ol> <p>My first hunch was to setup SQL Profiler wiht a bunch of filters to gather this data. What I don't like about this solution is that the data will have to be written to a file or table somewhere and I will have to do the number crunching to figure out the results I need. I would also like get these results ober the course of many days as I apply changes to see how the changes are impacting the database.</p> <p>I do not have direct access to the server to run SQL Profiler so I would need to create the trace template file and submit it to my DBA and have them run it over X time and get back to me with the results.</p> <p>Are there any better solutions to get the data I need? I would like to get even more data if possible but the above data is sufficient for my current needs and I don't have a lot of time to spend on this.</p> <p>Edit: Maybe there are some recommended tools out there that can work on the trace file that profile creates to give me the stats I want?</p>
<p>Two options I see:</p> <ol> <li><p>Re-script and recompile your sprocs to call a logging sproc. That sproc would be called by all your sprocs that want to have perf tracking. Write it to a table with the sproc name, current datetime, and anything else you'd like. <strong>Pro</strong>: easily reversible, as you'd have a copy of your sprocs in a script that you could easily back out. Easily queryable! <strong>Con</strong>: performance hit on each run of the sprocs that you are trying to gauge.</p></li> <li><p>Recompile your data access layer with code that will write to a log text file at the start and end of each sproc call. Are you inheriting your DAL from a single class where you can insert this logging code in one place? <strong>Pro</strong>: No DB messiness, and you can switch in and out over an assembly when you want to stop this perf measurement. Could even be tweaked with on/off in app.config. <strong>Con</strong>: disk I/O.</p></li> </ol>
Simple tool to download all imported/included WSDLs and Schemas <p>WSDLs often import other WSDLs and XML schema. </p> <p>Given a URL to a WSDL, is there a tool that will download the WSDL and all other referenced WSDLs and schemas?</p> <p>Ideally, this tool would be either Java or Perl friendly.</p>
<p>soapUI has a WSDL content viewer, as the website describes</p> <p>The Interface viewer allows relatively easy navigation and inspection of the entire contract for an imported WSDL, including all imported and included WSDL and XSD files and their contained types, definitions, etc.</p> <p><a href="http://www.soapui.org/userguide/interfaces/interfaceeditor.html">http://www.soapui.org/userguide/interfaces/interfaceeditor.html</a></p>
Are there any good online tutorials for making iPhone apps? <p>I am kind of new to making iPhone apps. I have already made a few small ones. But the best way I learn is by completing tutorials (not just broad/general topics, manuals, class definitions, etc). </p> <p>Are there any good tutorials that just walk through making an iPhone app?</p>
<p>As stefpet said, the Apple sample code and documentation is the best source. The iPhone Dev Center is certainly the place to begin. </p> <p>You should closely read... <a href="http://cocoadevcentral.com/d/learn_objectivec/" rel="nofollow">http://cocoadevcentral.com/d/learn_objectivec/</a></p> <p>I also recommend watching how Nick Myers puts his apps together... <a href="http://vimeo.com/1655681" rel="nofollow">http://vimeo.com/1655681</a></p> <p>In addition, use Google Code Search to review how specific pieces of code are implemented in different ways. <em>Tip: use advanced search to narrow your results to objective-c</em> <a href="http://www.google.com/codesearch/advanced_code_search?hl=en" rel="nofollow">http://www.google.com/codesearch/advanced_code_search?hl=en</a></p> <p>Erica Sadun's book is key...<a href="http://rads.stackoverflow.com/amzn/click/0321555457" rel="nofollow">http://www.amazon.com/iPhone-Developers-Cookbook-Building-Applications/dp/0321555457</a></p> <p>You might also be interested in this... <a href="http://appsamuck.com/" rel="nofollow">http://appsamuck.com/</a></p>
Silverlight: Create image from silverlight controls <p>Is it possible to generate an image from a silverlight control so that the control would render itself and its contents to an image so that I can do sime pixel manipulation on the image?</p>
<p>There is no way to achieve this in Silverlight 2. I have seen people work around this limitation by posting XAML to a server which would use WPF to render it to a bitmap (using RenderTargetBitmap) and return an image.</p> <p>However, the just released Silverlight 3 Beta includes a WritableBitmap class which can be used to render a Silverlight UIElement into pixels. In the beta there is however a limitation; once you render an element into the bitmap you cannot access its pixels. This restriction should be eased somewhat in the final release.</p> <p>Silverlight 3 Beta also includes pixel shaders, so you can write a custom shader in HLSL and apply it to any UIElement - this might be the best solution for you. This tutorial video should get you started on writing and using pixel shaders in Silverlight 3 Beta. <a href="http://silverlight.net/learn/learnvideo.aspx?video=187303" rel="nofollow">http://silverlight.net/learn/learnvideo.aspx?video=187303</a></p>
Is there a way to specify a super-type sub-type relationship in Oracle Designer? <p>I was wondering if it is possible to create a super-type sub-type relationship in Oracle Designer. I would like to create something like this:</p> <p><img src="http://ww2.cis.temple.edu/cis109friedman/CIS%20109%20-%20Lecture%20Set%20III%20-%20ERD%20and%20EERDs%20and%20Modeling/Emp-super.gif" alt="alt text" /></p> <p>Thanks.</p>
<p>In entity relationship diagrams subtypes are created by creating a new entity inside an existing entity like this example from <a href="http://www.informit.com/articles/article.aspx?p=101586&amp;seqNum=7" rel="nofollow">InformIT.com</a>:</p> <p><img src="http://www.informit.com/content/images/chap3%5F0130282286/elementLinks/03fig28.gif" alt="ERD Diagram" /></p> <p>This shows that ORDER has subtypes PURCHASE ORDER and SALES ORDER, i.e. every ORDER is <strong>either</strong> a PURCHASE ORDER <strong>or</strong> a SALES ORDER.</p> <p>Subtypes can be nested to any depth. </p> <p>Although this example doesn't show any, subtypes can also have their own attributes and relationships.</p>
Let Apache serve multiple directories through single <Location> <p>OK. I'm pretty much an apache HTTPD noob so please bare with me.</p> <p>I have an issue with serving a large amount of VirtualHosts and I was wondering if there is a more efficient way of doing things.</p> <p>I'm currently using the Location directive to serve a large amount projects from different departments, over 300 projects from 19 departments in total. The structures is the same for every Location directive except for the directories the files are served from. What I currently have is a large file that looks something like this:</p> <pre><code>&lt;VirtualHost *&gt; ServerName www.myserver.com &lt;Location /departmentA/project1&gt; AuthType Basic AuthName "By Invitation Only" AuthUserFile /usr/local/departmentA/project1/passwords Require valid-user &lt;/Location&gt; &lt;Location /departmentA/project2&gt; AuthType Basic AuthName "By Invitation Only" AuthUserFile /usr/local/departmentA/project2/passwords Require valid-user &lt;/Location&gt; &lt;Location /departmentB/project1&gt; AuthType Basic AuthName "By Invitation Only" AuthUserFile /usr/local/departmentA/project1/passwords Require valid-user &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>As you can see all these structures are the same except for the paths. What I would like is of course something where I can use variables for the department and project names and just maintain a single Location directive. I assume that this is also less heavy on the server and memory.</p> <pre><code>&lt;VirtualHost *&gt; ServerName www.myserver.com &lt;Location /$1/$2&gt; AuthType Basic AuthName "By Invitation Only" AuthUserFile /usr/local/$1/$2/passwords Require valid-user &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>Any help is very much appreciated.</p>
<p>Have you tried the <a href="http://httpd.apache.org/docs/2.2/mod/core.html#locationmatch" rel="nofollow">&lt;LocationMatch&gt; directive</a>?</p> <p>It takes a regular expression instead of a path. Depending on your paths and their associated sub-options, you may be able to reduce the hundreds of directives down to a more manageable handful of them.</p>
MySQL Syntax and 'OR' Performance <p>This MySQL query works just fine</p> <pre><code>SELECT o.id FROM descriptions_programs d, titles_programs t, programs o WHERE (d.object_id=o.id AND MATCH (d.text) AGAINST ('+china' IN BOOLEAN MODE) AND d.current=1) AND (t.object_id=o.id AND MATCH (t.text) AGAINST ('+china' IN BOOLEAN MODE) AND t.current=1) </code></pre> <p>But if I replace one AND with an OR, the query runs a very long time. (I have to kill it.):</p> <pre><code>SELECT o.id FROM descriptions_programs d, titles_programs t, programs o WHERE (d.object_id=o.id AND MATCH (d.text) AGAINST ('+china' IN BOOLEAN MODE) AND d.current=1) OR (t.object_id=o.id AND MATCH (t.text) AGAINST ('+china' IN BOOLEAN MODE) AND t.current=1) </code></pre> <p>Why is this? Don't get hung up on the simplicity of +china. I've just simplified this for the sake of debugging. Also, if I run with just one of the MATCH AGAINST tests, it works fine, so both are okay by themselves. I get the sense that I'm inadvertently causing a huge join by USING OR, but I just don't get it. I was previously using a n IN test on a UNION of two subselects an that worked, but this should work, too. Right?</p> <p><strong>Update:</strong> per bobince's request. It's not super slow, but at ~500ms, it's not nearly as fast as using a UNION as <a href="http://stackoverflow.com/questions/668371/mysql-fulltext-search-across-1-table">discussed here</a>.</p> <pre><code>mysql&gt; explain SELECT o.id -&gt; FROM programs o -&gt; JOIN titles_programs t ON t.object_id=o.id -&gt; JOIN descriptions_programs d ON d.object_id=o.id -&gt; WHERE MATCH (d.text) AGAINST ('+china' IN BOOLEAN MODE) AND d.current=1 -&gt; OR MATCH (t.text) AGAINST ('+china' IN BOOLEAN MODE) AND t.current=1 -&gt; ; +----+-------------+-------+-------+ ----------------+----------------+---------+----------------------+--------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+----------------+----------------+---------+----------------------+--------+-------------+ | 1 | SIMPLE | o | index | PRIMARY | PRIMARY | 4 | NULL | 148666 | Using index | | 1 | SIMPLE | d | ref | object_current | object_current | 4 | haystack.o.id | 1 | | | 1 | SIMPLE | t | ref | object_current | object_current | 4 | haystack.d.object_id | 1 | Using where | +----+-------------+-------+-------+----------------+----------------+---------+----------------------+--------+-------------+ </code></pre>
<p>Jason's answer is spot on. Additionally I'd try to use the more modern ANSI join syntax to take the load off the WHERE clause so relieve the confusion there:</p> <pre><code>SELECT o.id FROM programs o JOIN titles_programs t ON t.object_id=o.id JOIN descriptions_programs d ON d.object_id=o.id WHERE MATCH (d.text) AGAINST ('+china' IN BOOLEAN MODE) AND d.current=1 OR MATCH (t.text) AGAINST ('+china' IN BOOLEAN MODE) AND t.current=1 </code></pre> <p>This will stop the inadvertant cross-join causing a combinatorial explosion; I'd expect it to operate in reasonable time unless the database was really huge.</p> <p>If not, can you post the results of an EXPLAIN SELECT of the above? Presumably one or both of the fulltext indexes is not being used. I could certainly imagine the query optimiser failing to use the second fulltext index, by doing something like trying to ‘fill in’ the rows that didn't match the first fulltext query instead of going straight to the index, or something.</p> <p>Normally when you want to fulltext index over two columns in combination, you create one index over both columns. This would in any case be much faster. However it would mean you have to put titles and descriptions in the same table. This may not be such a hardship: since fulltext only works on MyISAM tables (and you don't typically want your canonical data in MyISAM tables) you can keep the definitive copy of your data in properly normalised InnoDB tables, with an additional MyISAM table containing only stripped and stemmed search-bait.</p> <p>If none of that is any good... well, I guess I'd go back to the UNIONing you mentioned, coupled with an application-level filter to remove duplicate IDs.</p>
Alternatives to ffmpeg as a cli tools for video still extraction? <p>I need to extract stills from video files. Currently I am using ffmpeg, but I am looking for a simpler tool and for a tool that my collegues can just install. No need to compile it from a svn checkout.</p> <p>Any hints? A python interface would be nice.</p>
<p>Your requirements "cli tool" and "python interface" aren't entirely compatible. Which do you want?</p> <p>The following media libraries all have Python bindings: <a href="http://www.gstreamer.org/" rel="nofollow">GStreamer</a>, <a href="http://www.videolan.org/" rel="nofollow">libVLC</a> (<a href="http://code.google.com/p/pyvlc/" rel="nofollow">pyvlc</a> provides w32 binaries), <a href="http://www.xine-project.org/" rel="nofollow">Xine</a> (via <a href="http://pyxine.sourceforge.net/" rel="nofollow">Pyxine</a>). I'm pretty sure none of them will be easier than using the <a href="http://www.ffmpeg.org/" rel="nofollow">ffmpeg</a> or <a href="http://www.mplayerhq.hu/" rel="nofollow">mplayer</a> command-line tools, though.</p> <p>Regarding ffmpeg: why would more than one person need to compile from a svn checkout (or tarball, as they've recently had their <a href="http://www.ffmpeg.org/releases/ffmpeg-0.5.tar.bz2" rel="nofollow">0.5</a> release)? Grab or make a binary package and have everybody use it.</p>
What's the most efficient way to make bitwise operations in a C array <p>I have a C array like:</p> <pre><code>char byte_array[10]; </code></pre> <p>And another one that acts as a mask:</p> <pre><code>char byte_mask[10]; </code></pre> <p>I would like to do get another array that is the result from the first one plus the second one using a bitwise operation, on each byte.</p> <p>What's the most efficient way to do this?</p> <p>thanks for your answers.</p>
<pre><code>for ( i = 10 ; i-- &gt; 0 ; ) result_array[i] = byte_array[i] &amp; byte_mask[i]; </code></pre> <ul> <li>Going backwards pre-loads processor cache-lines.</li> <li>Including the decrement in the compare can save some instructions.</li> </ul> <p>This will work for all arrays and processors. However, if you know your arrays are word-aligned, a faster method is to cast to a larger type and do the same calculation.</p> <p>For example, let's say <code>n=16</code> instead of <code>n=10</code>. Then this would be much faster:</p> <pre><code>uint32_t* input32 = (uint32_t*)byte_array; uint32_t* mask32 = (uint32_t*)byte_mask; uint32_t* result32 = (uint32_t*)result_array; for ( i = 4 ; i-- &gt; 0 ; ) result32[i] = input32[i] &amp; mask32[i]; </code></pre> <p>(Of course you need a proper type for <code>uint32_t</code>, and if <code>n</code> is not a power of 2 you need to clean up the beginning and/or ending so that the 32-bit stuff is aligned.)</p> <p>Variation: The question specifically calls for the results to be placed in a separate array, however it would almost certainly be faster to modify the input array in-place.</p>
Programmatic login and use of non-api-supported Google services <p>Google provides APIs for a number of their services and bindings for several languages. However, not everything is supported. So this question comes from my incomplete understanding of things like wget, curl, and the various web programming libraries.</p> <ol> <li><p>How can I authenticate programmatically to Google?</p></li> <li><p>Is it possible to leverage the existing APIs to gain access to the unsupported parts of Google?</p></li> </ol> <p>Once I have authenticated, how do I use that to access my restricted pages? It seems like the API could be used do the login and get a token, but I don't understand <i>what I'm supposed to do next</i> to fetch a restricted webpage.</p> <p>Specifically, I am playing around with Android and want to write a script to grab my app usage stats from the Android Market once or twice a day so I can make pretty charts. My most likely target is python, but code in any language illustrating non-API use of Google's services would be helpful. Thanks folks.</p>
<p>You can use something like mechanize, or even urllib to achieve this sort of thing. As a tutorial, you can check out my article <a href="http://ssscripting.wordpress.com/2009/03/17/how-to-submit-a-form-programmatically/" rel="nofollow">here</a> about programmatically submitting a form . Once you authenticate, you can use the cookie to access restricted pages.</p>
How to get max allowed filesize in .Net? <p>Does anyone know how to (natively) get the max allowed file size for a given drive/folder/directory? As in for Fat16 it is ~2gb, Fat32 it was 4gb as far as I remember and for the newer NTFS versions it is something way beyond that.. let alone Mono and the underlying OSes.</p> <p>Is there anything I can read out / retrieve that might give me a hint on that? Basically I -know- may app will produce bigger, single files than 2gb and I want to check for that when the user sets the corresponding output path(s)...</p> <p>Cheers &amp; thanks, -J</p>
<p>How about using System.Info.DriveInfo.DriveFormat to retrieve the drive's file system (NTFS, FAT, ect.)? That ought to give you at least some idea of the supported file sizes. </p>
DOM libraries in .Net for building SQL statements <h2>Are there any libraries for .Net for building sql statements?</h2> <p>(BTW I know about ADO.NET SqlCommand, SqlParameter classes already)</p> <p>I'm currently developing a library to do this but am now wondering if there is already something out there which might be better.</p> <p><b>Edit:</b><br/></p> <p> At this point I'm only interested in returning a DataTable object as I'm developing a reporting feature, hence why I'm not too interested in LINQ (please correct me on this if you think I am misguided). </p> <p> My main aim is to enable users to select field names for a report from a CheckBoxList and to be able to add/remove filtering expressions (i.e. edit the WHERE clause). Adding fields could mean including sub-selects, not just including a field name in the select clause. </p>
<p>You're looking for <a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" rel="nofollow">LINQtoSQL</a> which is an <strong>relational mapping implementation</strong> that ships in the .NET Framework 3.5 and allows you to model a relational database using .NET classes.</p> <p><strong>Edit-</strong></p> <p>Since you're using .NET 2.0 With <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow">LINQBridge</a>, you'll be able to write local <strong>LINQ to Objects queries</strong> using the full power of the C# 3.0 compiler and yet your programs will require only .NET 2.0.</p>
Handling ObjectDisposedException correctly in an IDisposable class hierarchy <p>When implementing IDisposable correctly, most implementations, including the framework guidelines, suggest including a <code>private bool disposed;</code> member in order to safely allow multiple calls to <code>Dispose()</code>, <code>Dispose(bool)</code> as well as to throw <a href="http://msdn.microsoft.com/en-us/library/system.objectdisposedexception.aspx">ObjectDisposedException</a> when appropriate.</p> <p>This works fine for a single class. However, when you subclass from your disposable resource, and a subclass contains its own native resources and unique methods, things get a little bit tricky. Most samples show how to override <code>Dipose(bool disposing)</code> correctly, but do not go beyond that to handling <code>ObjectDisposedException</code>.</p> <p>There are two questions that I have in this situation.</p> <p><hr /></p> <p>First:</p> <p>The subclass and the base class both need to be able to track the state of disposal. There are a couple of main options I know of -</p> <ul> <li><p>1) Declare private bool disposed; in both classes. Each class tracks its own this.disposed, and throws as needed.</p></li> <li><p>2) Use protected bool Disposed { get; private set; } instead of a field. This would let the subclass check the disposed state.</p></li> <li><p>3) Provide some protected helper method to check the disposed state, and throw by pulling the current type name via reflection if the object is disposed.</p></li> </ul> <p>The advantages as disadvantages I see to each by option are:</p> <ul> <li><p>1) This "smells" to me since it contains duplicated booleans, but seems to work fine. I often use this when subclassing other code.</p></li> <li><p>2) This takes out the duplicated booleans, but is not the way the design guidelines books are written, etc. This is what I typically use, though, since it keeps it a single point for state.</p></li> <li><p>3) This seems like the cleanest option to me, but doesn't appear in standard guidelines. It may be a little less expected of an approach than others from users of the class.</p></li> </ul> <p>I, at one point or another, have tried using all three of these approaches. I would like to know advantages and disadvantages to the three approaches, as well as any other ideas for a cleaner, better way to handle this. What choice would you make in handling this, and why?</p> <p><hr /></p> <p>Second:</p> <p>When throwing the <code>ObjectDisposedException</code>, what do you use for the name argument? I know the "typical" method call is:</p> <p><code><pre> throw new ObjectDisposedException(GetType().FullName); </pre></code></p> <p>There is a comment <a href="http://msdn.microsoft.com/en-us/library/system.objectdisposedexception.aspx">on this page</a> from a Microsoft employee suggesting that implementing the concrete class's full name is the appropriate usage.</p> <p>In the third option above, this would be the only meaningful choice. However, if the class implements the throwing itself, you could potentially return the name of the class that defines the method that was called. (ie: the base class could return the base class's name, not the concrete subclass)</p> <p>I don't think this is a good idea - but I ran into this on some code written by somebody else. Are there advantages or disadvantages to having the name of the class implementing the method returned?</p>
<p>I typically implement the first option. Indeed, it seems to be what the design guidelines recommend. The reason isn't immediately apparent, but I consider it a good one nonetheless: any implementer of the class should have the same sort of protection against the case where the object is disposed as general consumers. In other words, it's best not to <em>assume</em> that whoever is implementing a derived class knows precisely when they can call a certain method, whose successful execution may or may not depend on whether the object has already been disposed or not (though ideally this should be documented via XML comments anyway).</p> <p>Regarding your second question, I would again stick with the recommended practice of passing <code>GetType().FullName</code>, especially since it's used in the core .NET framework. Even if you think alternative methods are more appropiate, I think it's best to stick to the method used in the .NET framework for the sake of consistency.</p> <p>To conclude: as with all guidelines, it's clearly up to you how you want to implement a certain design feature, though unless you have a particularly good reason it's highly advisable just to stick with them. In both these situations, it probably wouldn't do a great deal of harm to utilise some of the alternatives you suggested in your post, so long as they are used consistently and preferably documented to the user.</p>
How to reload a crashed process on Windows <p>How to reload a crashed process on Windows? Of course, I can run a custom monitoring Win service process. But, for example, Firefox: it doesn't seem to install such a thing, but still it can restart itself when it crashes.</p>
<p>On Vista and above, you can use the <a href="http://msdn.microsoft.com/en-us/library/aa373347.aspx" rel="nofollow">RegisterApplicationRestart API</a> to automatically restart when it crashes or hangs.</p> <p>Before Vista, you need to have a top level exception filter which will do the restart, but be aware that running code inside of a compromised process isn't entirely secure or reliable.</p>
How do I get a button instead of a Submit <p>Here I am again with another seemingly simple question I just cannot find the answer to. I would like to use an input type="button" but asp:Button always gives me a type="submit."</p> <pre><code>&lt;asp:Button runat="server" bla bla bla /&gt; </code></pre> <p>Thanks in advance.</p>
<p>Use the following</p> <pre><code>&lt;asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="False" /&gt; </code></pre> <p>I tested it and it renders an <code>&lt;input type="button" /&gt;</code></p>
Would you consider Terracotta to be a mature product? <p>I just don't know. I mean, there are a few topics that point me away from believing such.</p> <p>For example, the latest stable version (3.0.0-stable), has a broken eclipse plugin that simply doesn't work at all. Furthermore, attempting to upgrade between revisions is an enormous hassle, as all servers are incompatible with all clients not of the exact same revision number.</p> <p>I've yet to fully profile, but it seems like Terracotta could quickly become an easy bottleneck.</p> <p>What are your thoughts, StackOverflow? Have you used Terracotta with success, or do you also find it a bit....immature?</p>
<p>Just an FYI,</p> <p>The release you refer to - 3.0.0-stable0 - is the first milestone release of the 3.0 line. This is the current, in progress version that has not yet been released. The current stable release line is 2.7 (current version: 2.7.3).</p> <p>If you are looking for a stable, mature product, you should base your opinions on 2.7.x, not 3.0. The practice is quite commonplace to have a "bleeding edge" product and a stable release product. It may be the terminology that has misled you. For more information on release naming in use by Terracotta, please have a look at the <a href="http://www.terracotta.org/web/display/orgsite/Buildology" rel="nofollow">Buildology</a> page.</p> <p>Regarding version numbers, this is regrettable, but necessary. In order for the product to improve, changes to the network protocol and underlying storage format happen from time to time. When these changes occur, the product is incompatible with prior versions. Rather than promise something that is not possible (backward compatibility) the Terracotta team has chosen instead to prohibit different versions from talking to one another.</p> <p>In the 3.0 line forward, the notion of a Stable Terracotta API has been introduced, which will lay the groundwork for some amount of compatibility between dot releases, e.g. 3.0.0 -> 3.0.1.</p> <p>HTH.</p> <p>Regards,</p> <p>Taylor Gautier Product Manager, Terracotta</p>
Where to place functional code in WinForms app <p>I'm new to C# and I am using VS08, I have created a form but where should I be placing my functional code?</p> <p>Right now I have 2 files:<br /> program.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } </code></pre> <p>form1.cs - which contains my form.</p>
<p>Your code should be contained in the classes that make up your domain functionality. Program.cs creates an instance of your form (suggest you rename from <code>form1</code> to something more descriptive), and your form in turn should instantiate the classes it requires.</p> <p>If you are using databinding, add one or more binding sources to your form, set their datasources and bind during form load.</p>
How do I shift the visible text in a narrow input element to see the cursor at the end? <p>The problem I am having is that given an input element with a maxlength that is much wider than the element's width (as set in its style), and, given a value that is wider than the element's width, how can I get the element to "scroll" to the end of the text. In IE it is easy, I create a textRange object, put its start and end position at the end of the text, call select on that range, and bam, the cursor is placed at the end of the text AND the text is shifted so that the end is shown. In Firefox, Chrome, Safari, trying to use the input element's setSelectionRange sets the cursor in the right position, but the text is not shifted so that I see its end, but instead the beginning. Does anybody know of a way I could go about placing the cursor at the end of the text AND shifting the text so that I can see the cursor?</p> <p>Thank you!</p> <p>Shane</p> <p><hr /></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;input cursor position&lt;/title&gt; &lt;script language='javascript'&gt; function setCursor() { var objInput = document.getElementById( 'testinputbox' ); var nLength = objInput.value.length; objInput.focus(); objInput.setSelectionRange( nLength, nLength ); } &lt;/script&gt; &lt;/head&gt; &lt;body onload='setCursor();'&gt; &lt;input id='testinputbox' maxlength='200' value='some very very very very very long text' style='width: 100px;'&gt;&lt;/input&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>I doubt this is a great cross-browser solution, however it does seem to be a work around in Firefox. I originally tried it by simulating the right arrow-key press, but didn't have any luck.</p> <pre><code>function setCursor(id) { var elem = document.getElementById(id); elem.focus(); elem.setSelectionRange(elem.value.length, elem.value.length); // Trigger a "space" keypress. var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32); elem.dispatchEvent(evt); // Trigger a "backspace" keypress. evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0); elem.dispatchEvent(evt); } </code></pre> <p>More info on initKeyEvent <a href="https://developer.mozilla.org/en/DOM/event.initKeyEvent" rel="nofollow">here</a>.</p>