instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.</p> <p>I am talking about interfaces in a context of interfaces vs. abstract classes.</p>
<p>Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software. </p> <p>Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.</p> <p>In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:</p> <pre><code>public void Paint(Car car, System.Drawing.Color color)... </code></pre> <p>This would work until your client said "now I want to paint trucks" so you could do this:</p> <pre><code>public void Paint (Vehicle vehicle, System.Drawing.Color color)... </code></pre> <p>this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:</p> <pre><code>public interface IPaintable{ void Paint(System.Drawing.Color color); } </code></pre> <p>...and passed that to your routine:</p> <pre><code>public void Paint(IPaintable item, System.Drawing.Color color){ item.Paint(color); } </code></pre> <p>Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.</p>
<p>Interfaces require any class that implements them to contain the methods defined in the interface.</p> <p>The purpose is so that, without having to see the code in a class, you can know if it can be used for a certain task. For example, the Integer class in Java implements the comparable interface, so, if you only saw the method header (public class String implements Comparable), you would know that it contains a compareTo() method.</p>
14,956
<p>I got my Ender 3 a couple weeks ago. Within a couple days of test prints, I was able to get it working pretty well. Prints looked great. However, I installed <a href="https://www.thingiverse.com/thing:2959991" rel="noreferrer">a more permanent solution to my X-Gantry binding issues</a> and now print quality is down again.</p> <p><a href="https://i.stack.imgur.com/P5yjv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/P5yjv.jpg" alt="Layer separation issues"></a></p> <p>The bottom .25" of the calibration part looks absolutely terrible, with hideous layer separation issues, while the upper .75" looks flawless. I have little idea what could be causing this issue.</p> <p><a href="https://i.stack.imgur.com/G5lab.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/G5lab.jpg" alt="Macro closeup on layer separation"></a></p> <p>The only possible failure mode I can think of is that the bed isn't the right distance from the print head, but even fiddling with the knobs doesn't yield any better print quality than the print on the right of the first image. What can I do?</p> <p>I slice with Cura and can make my profile available if it would be useful.</p>
<p>The answer now seems brain-dead obvious now. <em>Hindsight is 20/20, amirite?</em></p> <p>I had a decent filament clog in the extruder past the end of the Bowden tube. This was resolved by sticking a <a href="https://smile.amazon.com/dp/B078HXTLX8" rel="nofollow noreferrer">nozzle cleaner rod</a> up and down the filament path from the top of the extruder block several times and clearing the filament jam from the bottom of the Bowden tube. The printer works flawlessly now.</p>
<p>I had a real problem with what I was poor bed adhesion and layer separation on my 6month old Ender 3 pro. this problem started all at once, I checked the bed height several times and layer height, temperatures etc still the problem was there. Then I noticed the filament guide pinch roller was at a slight angle and on further inspection the plastic arm on removal was fractured so instead of holding the filament against the toothed drive it was metal to metal causing a slip on the nozzle feed. I ordered a replacement aluminium feed roller kit at Β£6.99 the machine is working as it did when I first got it. So it’s worth removing the pinch arm and inspecting.</p>
1,005
<pre><code>(define (repeated f n) if (= n 0) f ((compose repeated f) (lambda (x) (- n 1)))) </code></pre> <p>I wrote this function, but how would I express this more clearly, using simple recursion with repeated?</p> <p>I'm sorry, I forgot to define my compose function.</p> <pre><code>(define (compose f g) (lambda (x) (f (g x)))) </code></pre> <p>And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.</p>
<p>I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated can be written as follows:</p> <pre><code>(define (repeated f n) (lambda (x) (if (= n 0) x ((repeated f (- n 1)) (f x))))) (define (square x) (* x x)) (define y (repeated square 3)) (y 2) ; returns 256, which is (square (square (square 2))) </code></pre>
<p>What <em>is</em> your function trying to do, just out of curiosity? Is it to run <code>f</code>, <code>n</code> times? If so, you can do this.</p> <pre><code>(define (repeated f n) (for-each (lambda (i) (f)) (iota n))) </code></pre>
34,910
<p>I sadly have a big problem since a couple of weeks and I cant fix it myself. For over 20 prints, I had the same problems: At the <strong>start, everything goes well</strong> but at some point of time, my Creality CR-10 starts <strong>under extruding and</strong> after like 1 minute, <strong>NO filament is extruded anymore</strong> and the 3D printer moves over the printing bed without extruding anything. After that, I have to pull out the filament and the feeder always grinds into it.</p> <p>Some problem with the hotend (so the feeder works well but it cant push the filament through somehow - I cleaned the nozzle and couldn't find anything wrong there. When I push the filament through by hand it gets extruded but after a failed print, it is <strong>VERY hard to pull it back</strong> (because of the filament being slightly bigger at the nozzle - hard to remove! - </p> <p><strong>That could be the problem:</strong></p> <p><strong>I just tried to remove the filament from the printer (another failed print) I had to use two tongs because the filament was so hard to pull back. I noticed that the diameter of the PLA close to the hotend was a lot bigger (way over 1.75&nbsp;mm) <em>For about 5&nbsp;cm</em> that's a very long distance - that's the reason why it's hard to pull back (and also push through?) But I don't know why that happens... If I get an answer for that, I think that I have solved my problem</strong></p> <p>I already tried printing at 50&nbsp;% which didn't work.</p> <ul> <li>Creality CR-10 with 0.4&nbsp;mm nozzle, </li> <li>1.75&nbsp;mm PLA filament used (white)</li> <li>0.27&nbsp;mm layer height</li> <li>45&nbsp;mm/s printing speed at 220Β° (I can easily push the filament through at 200Β° by hand)</li> <li>60Β° bed temp</li> </ul> <p>And here some pictures of the failed prints:</p> <p><a href="https://i.stack.imgur.com/ZPB2n.jpg" rel="nofollow noreferrer" title="Failed print"><img src="https://i.stack.imgur.com/ZPB2n.jpg" alt="Failed print" title="Failed print"></a></p> <p><a href="https://i.stack.imgur.com/Mrw3I.jpg" rel="nofollow noreferrer" title="Filament grinding"><img src="https://i.stack.imgur.com/Mrw3I.jpg" alt="Filament grinding" title="Filament grinding"></a></p> <p><a href="https://i.stack.imgur.com/xKJTQ.jpg" rel="nofollow noreferrer" title="Sorry for the bad resolution"><img src="https://i.stack.imgur.com/xKJTQ.jpg" alt="Sorry for the bad resolution" title="Sorry for the bad resolution"></a></p> <p><a href="https://i.stack.imgur.com/54vPw.jpg" rel="nofollow noreferrer" title="Failed print #2"><img src="https://i.stack.imgur.com/54vPw.jpg" alt="Failed print #2" title="Failed print #2"></a></p> <p><strong>I think I can exclude these:</strong></p> <p>It could be: (the things I can imagine but don't have a solution for)</p> <ul> <li>The feeder being too strong/my new PLA filament being too soft</li> <li>Maybe a software problem? I'm using the newest Cura version and I don't know what could be wrong there.</li> </ul> <p>The filament seems to run out of the hotend. Something is really broken here. I tried to lower the print temperature and don't have an issue (at least not that big) with pulling out the filament but instead, the feeder started grinding into the filament again.</p> <p><a href="https://i.stack.imgur.com/tHT78.jpg" rel="nofollow noreferrer" title="Filament exiting nozzle"><img src="https://i.stack.imgur.com/tHT78.jpg" alt="Filament exiting nozzle" title="Filament exiting nozzle"></a></p> <p>I'm very happy for any answer and possible solutions. </p>
<p>Grinding is due to attempts to advance filament faster than it can be melted and dispensed. Try one or more of the following:</p> <ul> <li>Raise the head temperature (to meet current throughput demand)</li> <li>Lower the print speed (to reduce throughput demand)</li> <li>Slice for thinner layers (to reduce throughput demand)</li> </ul>
<p>A 0.27Β mm layer height is not correct for any printer, any nozzle/hotend, any file, and should never be used as a layer height variable for any FDM printer.</p> <p>Layer height should be a factor of the diameter of your nozzle size. i.e. Your nozzle is 0.4Β mm, so depending on your printer, your range of resolutions/layer heights could start as low as 0.04Β mm, but is monumentally more likely to begin at 0.08 or 0.12Β mm, with a maximum value being 0.28Β mm, and maybe 0.32Β mm if you're doing some risky/experimental spiralized vase printing.</p>
1,015
<p>I really hate using STL containers because they make the debug version of my code run really slowly. What do other people use instead of STL that has reasonable performance for debug builds?</p> <p>I'm a game programmer and this has been a problem on many of the projects I've worked on. It's pretty hard to get 60 fps when you use STL container for everything.</p> <p>I use MSVC for most of my work.</p>
<p>EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html</a></p> <p>Some of these adjustments to are being reviewed for inclusion in the C++ standard.</p> <p>And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like:</p> <pre><code> debug release STL 100 10 EASTL 10 3 array[i] 3 1 </code></pre> <p>The most success I've had was rolling my own containers. You can get those down to near array[x] performance.</p>
<p>STL containers should not run "really slowly" in debug or anywhere else. Perhaps you're misusing them. You're not running against something like ElectricFence or Valgrind in debug are you? They slow anything down that does lots of allocations.</p> <p>All the containers can use custom allocators, which some people use to improve performance - but I've never needed to use them myself.</p>
11,259
<p>I know this might be a no-brainer, but please read on.</p> <p>I also know it's generally not considered a good idea, maybe the worst, to let a browser run and interact with local apps, even in an intranet context.</p> <p>We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion. These folks are not particularly tech savvy; I don't even consider thinking that they could understand the difference between remote delivered applications and local ones.</p> <p>So, I've been asked if it's possible. Of course, it is, with IE's good ol' ActiveX controls. And I even made a working prototype (that's where it hurts).</p> <p>But now, I doubt. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the '<em>local intranet</em>' zone? People will use the same browser to surf the web, can I fully trust IE? Isn't there a risk that Microsoft would just disable those controls in future updates/versions? What if a website, or any kind of malware, just put another site on the trust list? With that extent of control, you could as well uninstall every protection and just run amok 'till you got hanged by the IT dept.</p> <p>I'm about to confront my superiors with the fact that, even if they saw it is doable, it would be a very bad thing. So I'm desperately in need of good and strong arguments, because "<em>let's don't</em>" won't do it.</p> <p>Of course, if there is nothing to be scared of, that'll be nice too. But I strongly doubt that.</p>
<blockquote> <p><i>We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion</i></p> </blockquote> <p>I haven't used Citrix very many times, but what's it got to do with executing local applications? I don't see how "People like Citrix" and "browser executing local applications" relate at all?</p> <p>If the people are accessing your Citrix server from home, and want the same experience in the office, then buy a cheap PC, and run the exact same Citrix software they run on their home computers. Put this computer in the corner and tell them to go use it. They'll be overjoyed.</p> <blockquote> <p><i>Isn't it madness to allow such 'dangerous' ActiveX controls, even in the 'local intranet' zone ? People will use the same browser to surf the web, can I fully trust IE ?</i></p> </blockquote> <p>Put it this way. IE has built-in support for AX controls. It uses it's security mechanisms to prevent them from running unless in a trusted site. By default, no sites are trusted at all.</p> <p>If you use IE <em>at all</em> then you're putting yourself at the mercy of these security mechanisms. Whether or not you tell it to trust the local intranet is beside the point, and isn't going to affect the operation of any other zones. </p> <p>The good old security holes that require you to reboot your computer every few weeks when MS issues a patch will continue to exist and cause problems, regardless of whether you allow ActiveX in your local intranet.</p> <blockquote> <p><i>Isn't there a risk that Microsoft would just disable those controls in future updates / versions ?</i></p> </blockquote> <p>Since XP-SP2, Microsoft has been making it increasingly difficult to use ActiveX controls. I don't know how many scary looking warning messages and "This might destroy your computer" dialogs you have to click through these days to get them to run, but it's quite a few. This will only get worse over time.</p>
<blockquote> <p><i>The standard citrix homepage (or how we use it) is a simple web page with program icons. Click on it, and the application get's delivered to you. People want the same thing, at work, with their applications/folders/documents. And because I'm a web developer, and they asked me, I do it with a web page... Perhaps I should pass the whole thing over to the VB guy..</i></p> </blockquote> <p>Ahh... I know of 2 ways to accomplish this:</p> <p>You can embed internet explorer into an application, and hook into it and intercept certain kinds of URL's and so on</p> <p>I saw this done a few years ago - a telephony application embedded internet explorer in itself, and loaded some specially formatted webpages.</p> <p>In the webpage there was this:</p> <pre><code>&lt;a href="dial#1800-234-567"&gt;Call John Smith&lt;/a&gt; </code></pre> <p>Normally this would be a broken URL, but when the user clicked on this link, the application containing the embedded IE got notified, and proceeded to execute it's own custom code to dial the number from the URL.</p> <p>You could get your VB guy to write an application which basically just wraps IE, and has handlers for executing applications. You could then code normal webpages with links to just open applications, and the VB app would launch them. This allows you to write your own security stuff (like, only launch applications in a preset list, or so on) into the VB app, and because VB is launching them, not IE, none of the IE security issues will be involved.</p> <p>The second way is with browser plug-ins.</p> <p>For example, skype comes with a Firefox plug-in, which looks for phone-numbers in web-pages, and attaches special links to them. When you click on these links it invokes skype - you could conceivably do something similar for launching your citrix apps.</p> <p>You'd then be tied to firefox though. Writing plugins for IE is <em>much</em> harder than for FF, I wouldn't go down that path unless forced to.</p>
5,177
<p>When using Maven to build an executable JAR, how do I specify the JVM arguments that are used when the JAR is executed?</p> <p>I can specify the main class using <code>&lt;mainClass&gt;</code>. I suspect there's a similar attribute for JVM arguments. Specially I need to specify the maximum memory (example -Xmx500m).</p> <p>Here's my assembly plugin:</p> <pre><code> &lt;plugin&gt; &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;descriptorRefs&gt; &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt; &lt;/descriptorRefs&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;com.me.myApplication&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>Edit/Follow-up: It seems that it might not be possible to specify JVM arguments for an executable JAR according to <a href="http://forums.sun.com/thread.jspa?threadID=633125&amp;messageID=3667132" rel="noreferrer">this</a> and <a href="http://www.javalobby.org/forums/thread.jspa?threadID=15486&amp;tstart=0#91817576" rel="noreferrer">this</a> post.</p>
<p>I don't know of any such mechanism. The JVM configuration is specified by the calling java command. </p> <p>Here's the jar file specification which conspicuously doesn't mention any attribute other than Main-Class for stand-alone execution:</p> <p><a href="http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html" rel="noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html</a></p>
<p>Ancient question but came up on my Google search for this exact problem so I'm answering it.</p> <p>Try </p> <pre><code>&lt;configuation&gt; ... &lt;argLine&gt; -Xmx500m &lt;/argLine&gt; ... &lt;/configuation&gt; </code></pre>
23,517
<p>How would I go about dynamically allocating a multi-dimensional array?</p>
<p>If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:</p> <pre><code>typedef int dimensions[3][4]; dimensions * dim = new dimensions[10]; dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42; delete [] dim; </code></pre> <p>instead of <code>10</code>, a runtime determined value can be passed. Since it's not part of the type operator new returns, that's allowed. This is nice if you know the number of columns, but want to keep the number of rows variable, for example. The typedef makes it easier to read the code.</p>
<p>You can index a one dimensional as a 2, 3, or N dimensional one if you just space over the correct amount of elements. For example, if I've got 10 rows and 10 columns, I know that if I'm on row 3 I will have to go over at least 30 elements to get to it. </p> <p>Somehow I prefer this notation for simple 2D arrays since I don't need to worry about nested levels of pointers. The downside is the messier index notation. Here's an example with a 2D array with n rows and m columns:</p> <pre><code>int *matrix = new int[n*m]; //set element (3,7) to 10 matrix[3*m+7] = 10; //print the matrix for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; m; j++) { cout &lt;&lt; matrix[i*m+j] &lt;&lt; ' '; } cout &lt;&lt; '\n'; } </code></pre>
44,293
<p>I've switch from VB.NET to C# several months ago, while there are a lot of features I <strong>really</strong> like in C#, believe it or not, there are some features that I <strong>really</strong> miss from VB.NET.</p> <p>One of those features is whenever I implemented an interface in VB.NET the stub properties and methods were automatically added for me. </p> <p>Is there any way to do this in C#?</p>
<p>Right click on the name of the interface in the class that implements it, click 'Implement Interface' then click on either of the following two:</p> <p>Implement Interface: Implements stub props and methods for you.</p> <p>Implement Interface Explicitly: Implements stub props and methods for you, but also explicitly names the interface the stub is for.</p>
<p>Also you can use the shortkey <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>F10</kbd> and then hit <kbd>ENTER</kbd>. Or you use <kbd>CTRL</kbd> + <kbd>></kbd> :-)</p>
40,187
<p>I wrote code to set permission of the folder. Function I developed was</p> <pre><code>public void SetPermission(string user,FileSystemRights rights) { DirectoryInfo dInfo = new DirectoryInfo(folderPath); DirectorySecurity oDirectorySecurity = new DirectorySecurity(); oDirectorySecurity.AddAccessRule(new FileSystemAccessRule(user, rights, AccessControlType.Allow)); dInfo.SetAccessControl(oDirectorySecurity); } </code></pre> <p>This function is working fine to set permission for the user. But when I check folder Properties -> Security , user added. But no permission is checked in checkbox Open Advanced dialogbox. In this box I can see permission , which i set for the user.</p> <p>So my question is Why there is no checkbox seleced on security tab, but it is there in advanced tab?</p> <p>Please HELP me!!!!!!</p>
<p>I ran into this as well. It seems to be a Service Patch thing.</p> <p>You can read how I fixed it at <a href="http://jspot.jerryhanel.com/2009/01/08/c-filedirectory-permissions/" rel="nofollow noreferrer">http://jspot.jerryhanel.com/2009/01/08/c-filedirectory-permissions/</a></p> <p>The short version: You have to set a flag for all of the ACLs for all users. Yes... it's ugly. And when you add Service Pack 3, the checkmarks go away again. If anyone has a cleaner solution than this, PLEASE let me know.</p> <p>I have code for that on my site.</p> <p><strong>UPDATE</strong>: The URL now points to the new site.</p>
<p>It might help to use dInfo.GetAccessControl to initialize oDirectorySecurity. You could also try calling oDirectorySecurity.SetOwner.</p> <p>Sometimes permissions only show up in advanced if they are not applied to to correct objects. Try setting the Inheritance/Propigation flags on your FileSystemAccessRule object.</p>
41,449
<p>I'm using Spring's dependency injection but I'm running into difficulty loading a resource in my Spring config file. </p> <p>The resource is an XML file and is in a JAR file on my classpath. I try to access it as follows:</p> <pre><code>&lt;import resource="classpath:com/config/resources.xml" /&gt; </code></pre> <p>however I keep getting encountering the following error:</p> <blockquote> <p>Failed to import bean definitions from URL location [classpath:com/config/resources.xml]</p> </blockquote> <p>The JAR file is on the classpath of a Java project, which is in turn used by my web app. Should I really be doing my Spring configuration in the web project as opposed the Java project, or does that matter?</p>
<p>If it needs to be in the classpath of your webapp, then you should stick the JAR containing the config file into your WEB-INF/lib directory.</p> <p>If you're using a webapp, then the common convention is use a ContextLoaderListener to ensure a WebApplicationContext is inserted into a standard place in the ServletContext:</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:/com/config/resources.xml&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>Then use <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html" rel="noreferrer">WebApplicationContextUtils</a> to fish the application context out of the servlet context using:</p> <pre><code>WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); </code></pre>
<p>I don't really recall why this matters, but try putting an asterisk (<em>) in front of the colon (:) classpath</em>:/ If this doesn't work, try the asterisk after the colon (classpath:*), although I think it was before the colon.</p>
37,893
<p>I need to know if it is possible to dynamically bind a textbox residing within a datarepeater to a 'dynamically' created BindingSource. I am using VB.net. The database I am using is a MySQL database. </p> <p>I have to use the connection dynamically due to the fact that the database my not permanently reside on the same server.</p> <p>[edit]<br> ok, so it seams that I am a dolt when asking questions. The app that I am making is not web based. it is a simple (I hope) app that connects to a MySQL database, accesses a table so I can edit/view it. Current setup is using the Add DataSource wizard. I have successfully connected to the dbase dynamically using the mysql connector dll but without the textboxes set at design time to a datasource, I am unsure on how to 'link' them via the datarepeater.</p>
<p>Your connection string should be defined in your Web.Config, and if you move your database to a different server, it's just a matter of modifying the web.config entry. As long as you keep the connection string name the same, the BindingSource object will pick up the new value from the config.<hr><strong>edit</strong><br><br> In truth, the same concept should apply here as it does in the web app answer listed above.</p> <p>All of your data objects should be hard-coded, and it's just the connection string (which you'll have to either ask the user for, or push out as update when the DB moves) which will get modified.</p> <p>For example, create a App.Config file in your project. Have one of your configuration values be the connection string. This config value will be where you go to get the connection string whenever you need it. Then your wizard will be there to allow users to easily modify the connection.</p>
<p>then look in app.config</p> <p>the conenction string should be there.</p> <p>If it is not then you should put it in here as you can change this file at any time and not have to recompile your app.</p>
11,316
<p>I have a PHP website backed by a MySQL database and a small team of programmers submitting code to subversion. Typically we write code, test it locally, commit to subversion and then copy changed files to a hidden area for online testing.</p> <p>However mistakes can be made. Occasionally I want to refresh the site so that I know, without a doubt, that the site code and database really represents what's in subversion. I'd like to get as close to a one click solution as possible so that it's foolproof.</p> <p>What's the best way to do that?</p> <p>BTW, if it matters, we develop on windows machines.</p>
<p>The export can be automatically done after every commit with a post-commit hook:</p> <p><a href="http://svnbook.red-bean.com/en/1.5/svn.ref.reposhooks.post-commit.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.5/svn.ref.reposhooks.post-commit.html</a></p> <p>You can setup the hook to automatically export the project inside the hidden area for the online testing.</p>
<p>I would recommend:</p> <ul> <li>copying each old build to its own directory (for quick restores; you probably only need to keep one of these) in a non-web-accessible part of your server.</li> <li>Then use <code>svn export</code> to get the entire new build from svn. Don't use <code>svn checkout</code>, as this will leave .svn directories all over the place.</li> </ul>
25,579
<p>Alright, I know how the <code>fieldset</code>/<code>legend</code> works out in HTML. Say you have a form with some fields:</p> <pre><code>&lt;form&gt; &lt;fieldset&gt; &lt;legend&gt;legend&lt;/legend&gt; &lt;input name="input1" /&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>What should I use the <code>legend</code> for? It's being displayed as a <strong>title</strong>, but isn't a legend semantically an explanation of the contents? In my view, preferably you'd do something like this:</p> <pre><code>&lt;form&gt; &lt;fieldset&gt; &lt;legend&gt;* = required&lt;/legend&gt; &lt;label for="input1"&gt;input 1 *&lt;/label&gt;&lt;input id="input1" name="input1" /&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>But that doesn't really work out with how fieldsets are rendered. Is this just a ambigious naming in HTML, or is it my misunderstanding of the English word 'legend'?</p> <hr> <p>Edit: fixed some errors ;-)</p>
<p>Yes, the naming is ambiguous. It’s best to consider it as a caption for the fieldset.</p> <p>See <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.10" rel="nofollow noreferrer">the HTML spec on <code>FIELDSET</code> and <code>LEGEND</code> elements</a> if you haven’t already:</p> <blockquote> <p>The <a href="http://www.w3.org/TR/html401/interact/forms.html#edef-LEGEND" rel="nofollow noreferrer"><code>LEGEND</code></a> element allows authors to assign a caption to a <a href="http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET" rel="nofollow noreferrer"><code>FIELDSET</code></a>. The legend improves accessibility when the <a href="http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET" rel="nofollow noreferrer"><code>FIELDSET</code></a> is rendered non-visually.</p> </blockquote>
<p>I guess you meant to write</p> <pre><code>&lt;form&gt; &lt;fieldset&gt; &lt;legend&gt;legend&lt;/legend&gt; &lt;input name="input1" /&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>but you're right in part. The word legend has several meanings including</p> <ul> <li>An explanatory caption accompanying an illustration. </li> <li>An explanatory table or list of the symbols appearing on a map or chart.</li> </ul> <p>So it can in fact mean both.</p>
31,588
<p>I am working with some tables where I want the C# class to have a different property name than the underlying table column. However, when I use the Translate method to read the results, the properties that don't match the source name never get populated. Even when I use Linq to generate the SQL.</p> <p>For instance, my table is defined in the DB like this:</p> <pre><code>CREATE TABLE User_Entry ( UserId int IDENTITY (1, 1) NOT NULL, Login_Id varchar (50) NOT NULL, Active char(1) NOT NULL, PASSWORD varchar(75) NULL ) </code></pre> <p>Here's the class it maps to (generated by the LINQ designer...LINQ attributes and other stuff left out for brevity):</p> <pre><code>public partial class User { int UserId; string Login; string Active, string Pwd } </code></pre> <p>When I do the following, the Login and Pwd properties are not populated but the UserId and the Active properties are.</p> <pre><code>Data.DbContext db = new Data.DbContext(); IQueryable query = db.Users.Where(usr =&gt; usr.Login == request.LoginString); SqlCommand cmd = (SqlCommand)data.GetCommand(query); ... execute the command (asynchronously) ... User user = db.Translate&lt;User&gt;( dataReaderResult ).FirstOrDefault(); </code></pre> <p>!At this point, I inspect the user object and I can see that the Login and Pwd columns are not populated!</p> <p>Here is the sql that was generated:</p> <pre><code>exec sp_executesql N'SELECT [t0].[UserID] AS [UserId], [t0].[Login_ID] AS [Login], [t0].[Active], [t0].[PASSWORD] AS [Pwd] FROM [dbo].[User_Entry] AS [t0] WHERE [t0].[Login_ID] = @p0', N'@p0 varchar(13)', @p0 = 'test_user' </code></pre> <p>Originally, when the UserId column had a different property name I was getting an exception <code>The required column [UserId] does not exist in the results</code>. I looked around and I saw a response from some MSFT people that said it was a bug.</p> <p>Is this related? Was it ever fixed? Does anyone know when it will be fixed?</p> <p>Edit: Some more info.</p> <p>The bug that I think this is related to has a comment from Kathy Lu MSFT on 14 Aug 2007 <a href="https://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1983746&amp;SiteID=1&amp;pageid=0" rel="nofollow noreferrer">here</a>, where she says:</p> <blockquote> <p>Thank you for reporting this issue. From your issue we were able reproduce the issue and the product team is looking into an appropriate triage and resolution.</p> </blockquote> <p>I'm wondering if this is related to what I'm experiencing and if I can get more info about it. I searched <code>linq translate site:connect.microsoft.com</code> but I didn't find anything.</p>
<p>I'll start. <strong>feel free to edit and improve this</strong></p> <p>This is for a ficticious product called: dundermifflin.com</p> <ol> <li><p>Setup a development virtual machine running the same software you plan on using in production: e.g. Ubuntu with PostgreSQL, Apache and PHP5.</p></li> <li><p>Each developer runs their own copy of this VM with the hostname set to their username, (e.g. phpguy.dundermifflin.com)</p></li> <li><p>Setup a central staging server (same as the development VM). This is staging.dundermifflin.com.</p></li> <li><p>Setup a central Subversion server with a new repository for dundermifflin.com. This is devel.dundermifflin.com.</p> <ul> <li>4a. Add post-commit hook to run tests for "trunk" commits</li> <li>4b. Add post-commit hook to package/deploy to staging server for commits tagged "staging"</li> <li>4c. Add post-commit hook to package/deploy to production server for commits tagged "release"</li> </ul></li> </ol> <p>This method does not address database continuous integration which means rolling back SVN to a previous revision will break the build unless your database is very static. Suggestions?</p> <ol start="5"> <li><p>Use Bugzilla on the central Subversion server (devel.dundermifflin.com) for bug tracking.</p></li> <li><p>Write a shell script to run PHPUnit/SimpleTest tests (to be called by item 4a).</p></li> </ol>
<p>For continuous integration, linked with your version control system, and automated unit testing I find this article very interesting:</p> <p><a href="http://nohn.net/blog/view/id/cruisecontrol_ant_and_phpunit" rel="nofollow noreferrer">Continuous builds with CruiseControl, Ant and PHPUnit</a></p>
25,872
<p>Is there a regular expression that matches valid regular expressions? </p> <p>(I know there are several flavors of regexps. One would do.)</p>
<p>If you merely want to check whether a regular expression is valid or not, simply try to compile it with whichever programming language or regular expression library you're working with.</p> <p>Parsing regular expressions is far from trivial. As the author of <a href="http://www.regexbuddy.com" rel="noreferrer">RegexBuddy</a>, I have been around that block a few times. If you really want to do it, use a regex to tokenize the input, and leave the parsing logic to procedural code. That is, your regex would match one regex token (<code>^</code>, <code>$</code>, <code>\w</code>, <code>(</code>, <code>)</code>, etc.) at a time, and your procedural code would check if they're in the right order.</p>
<p>Depending on your goal I would say definately maybe.</p> <p>If you want to filter regexps out from somewhere, it might prove difficult as regular expressions come in all sizes and shapes and they don't all start and end with slashes.</p> <p>If you just need to know wether or not a regexp is valid there is another way. Depending on the language you're using you could try/catch</p> <p>If you can be more specific I could try and give a better answer, the question is intruiging.</p>
47,356
<p>I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp" /&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ trace (rightAxisGrp.selection); trace (rightAxisGrp.selection.data.name); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" dataField="left" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" dataField="right" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:dataProvider&gt; &lt;mx:Array&gt; &lt;mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Sambirano Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Simmons' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Pygmy Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Goodman's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Jolly's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Claire's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Lokobe Mouse Lemur" /&gt; &lt;mx:Object left="true" right="true" name="Bongolava Mouse Lemur" /&gt; &lt;/mx:Array&gt; &lt;/mx:dataProvider&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre> <hr> <p><em>UPDATED</em> (thanks bill!)</p> <p>Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.utils.ObjectProxy; import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection = new ArrayCollection (); private function selectItem (selObject:Object, property:String) : void { for each (var obj:ObjectProxy in myData) { obj[property] = (obj.name === selObject.name); } readingsGrid.invalidateDisplayList (); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (leftAxisGrp.selectedValue, 'left'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (rightAxisGrp.selectedValue, 'right'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" dataProvider="{myData}" sortExpertMode="true" height="150" width="400" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn id="leftCol" headerText="L" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" buttonMode="true" value="{data}" selected="{data.left}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn id="rightCol" headerText="R" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" buttonMode="true" value="{data}" selected="{data.right}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:creationComplete&gt; &lt;![CDATA[ myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" })); myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" })); ]]&gt; &lt;/mx:creationComplete&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre>
<p>What's happening here is that Flex only creates itemRenderer instances for the <em>visible</em> columns. When you scroll around, those instances get recycled. So if you scroll down, the RadioButton object that was drawing the first column of the first row may now have changed to instead be drawing the first column of the seventh row. Flex resets the "data" property of the itemRenderer whenever this happens.</p> <p>So while there are 15 rows of data, there are only ever 12 RadioButtons (6 for the "left", and 6 for the "right" for the 6 visible rows), not 30 RadioButtons, as you might expect. This isn't a big problem if you're only <em>displaying</em> the selection, but it becomes more of a problem when you allow updates.</p> <p>To fix the display issue, instead of setting the "dataField" on the column, you can bind the RadioButton's "selected" property to the itemRenderer's data.left (or right) value. You'll then need to make the items in your dataProvider "Bindable".</p> <p>To fix the update issue, since you'd be binding directly to the dataProvider item values, you need to be sure to update them. Since there's isn't one RadioButton per-item, you'll need another scheme for that. In this case I put in a handler that goes and sets the left/right property of each item to "false", except for the "selected" one, which gets set to "true".</p> <p>I updated your example code based on these thoughts. Try something like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application layout="absolute" xmlns:my="*" xmlns:mx="http://www.adobe.com/2006/mxml"&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp" change="selectItem(leftAxisGrp.selectedValue, 'left');"/&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp" change="selectItem(rightAxisGrp.selectedValue, 'right');"&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false" dataProvider="{adgData.object}"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" value="{data}" selected="{data.left}"/&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" value="{data}" selected="{data.right}"/&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;mx:Model id="adgData"&gt; &lt;root&gt; &lt;object left="false" right="false" name="Reddish-gray Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Golden-brown Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Northern Rufous Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Sambirano Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Simmons' Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Pygmy Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Brown Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Madame Berthe's Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Goodman's Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Jolly's Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Mittermeier's Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Claire's Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Danfoss' Mouse Lemur" /&gt; &lt;object left="false" right="false" name="Lokobe Mouse Lemur" /&gt; &lt;object left="true" right="true" name="Bongolava Mouse Lemur" /&gt; &lt;/root&gt; &lt;/mx:Model&gt; &lt;mx:Script&gt; &lt;![CDATA[ private function selectItem(selObject:Object, property:String) : void { for each(var obj:Object in adgData.object) { obj[property] = (obj === selObject); } readingsGrid.invalidateDisplayList(); } ]]&gt; &lt;/mx:Script&gt; &lt;/mx:Application&gt; </code></pre>
<p>Reproduced this. Likely to be a ADG bug, we've run into a few here. (Didn't find this one on bugs.adobe.com, but their search sucks).</p> <p>You could try Flex 3.0.3, or a nightly build <a href="http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html" rel="nofollow noreferrer">here</a> (warning, may be pretty broken), and see if they've fixed it, or you could try implementing a custom renderer, but that is a pain to get right.</p>
13,719
<p>We have a DLL which is produced in house, and for which we have the associated static LIB of stubs.</p> <p>We also have an EXE which uses this DLL using the simple method of statically linking to the DLL's LIB file (ie, not manually using LoadLibrary).</p> <p>When we deploy the EXE we'd like the DLL file name to be changed for obfuscation reasons (at customer's request).</p> <p><strong>How can we do this so that our EXE still finds the DLL automagically?</strong></p> <p>I have tried renaming the DLL and LIB files (after they were built to their normal name), then changing the EXE project settings to link with the renamed LIB. This fails at runtime, as I guess the name of the DLL is baked into the LIB file, and not simply guessed at by the linker replacing ".lib" with ".dll".</p> <p>In general, we do not want to apply this obfuscation to all uses of the DLL, so we'd like to keep the current DLL project output files are they are.</p> <p>I'm hoping that there will be a method whereby we can edit the DLL's LIB file, and replace the hardcoded name of the DLL file with something else. In which case this could be done entirely within the EXE project (perhaps as a pre-build step).</p> <hr> <p><strong>Update</strong>: I find that Delay Loading does not work, as my DLL contains exported C++ classes. See <a href="http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2004-09/0377.html" rel="noreferrer">this article</a>.</p> <p>Are there any alternatives?</p>
<p>Using the LIB tool (included with visual studio) you can generate a lib file from a def file. Asuming your dll source does not include a def file, you have to create one first. You can use dumpbin to assist you. For example: <code>dumpbin /exports ws2_32.dll</code></p> <p>In the output you see the names of the functions exported. Now create a def file like this:</p> <pre><code>LIBRARY WS2_32 EXPORTS accept @1 bind @2 closesocket @3 connect @4 </code></pre> <p>The @number is the ordinal in the dumpbin output</p> <p>Use <code>LIB /MACHINE:x86 /def:ws2_32.def</code> to generete the lib file.</p> <p>Now you can easily modify the def file, and generate a new libfile each time you rename your dll.</p> <p>you can verify the libfile using dumpbin: <code>dumpbin /exports ws2_32.lib</code>. You should get the same output as the original lib file.</p>
<p>you'll have to use Assembly.Load and have the obfuscated assembly name saved in the app.config.</p> <p>either that or use the same approach that plug-ins use. have a class in your assembly implement an interface that you search for from your app in every assembly in a certain directory. if found loat it. you'll of course have to not obfuscate the Interface name.</p>
35,469
<p>Ok, this is possibly borderline-subjective, but I wonder where one would put a simple class that does something within an ASP.net MVC project? I mean a class like the <a href="http://www.stum.de/2008/10/20/base36-encoderdecoder-in-c/" rel="noreferrer">Base36 De/Encoder</a>, that is neither Model nor Controller. Should this always go into a separate Class Library Assembly, or do such Classes have a place within the MVC Web Application project?</p> <p>And yes, I know that it probably does not really matter, I'm just possibly a bit over careful to learn a new technology the "right" way from the beginning.</p>
<p>I personally put such classes in some common "utils" assembly. Not only does it avoid junking up your MVC project, but such helper classes often find their way into other projects I work on.</p>
<p>You should still have your separate projects where you include your own libraries, helpers and frameworks. You should still see the ASP.NET MVC project as a web project. You don't have to put all your business logic or web helpers in the Model folder.</p>
26,994
<p>Is there a way to specify a child's initial window position in Qt?</p> <p>I have an application that runs on Linux and Windows and it looks like the default behavior of Qt lets the Window Manager determine the placement of the child windows. </p> <p>On Windows, this is in the center of the screen the parent is on which seems reasonable. </p> <p>On Linux, in GNOME (metacity) it is always in the upper left-hand corner which is annoying. I can't find any window manager preferences for metacity that allow me to control window placement so I would like to override that behavior.</p>
<p><a href="http://doc.qt.io/qt-4.8/qwidget.html#geometry-prop" rel="nofollow noreferrer">Qt Widget Geometry</a></p> <p>Call the move(x, y) method on the child window before show(). The default values for x and y are 0 so that's why it appears in the upper left-hand corner.<br> You can also use the position of the parent window to compute a relative position for the child.</p>
<p>Generally, I'd recommend not forcing window positions unless your application has some very special windowing requirements. It's the window manager's job to determine where new windows are put and most of them do a good job. If MetaCity isn't picking a good position, then that's its problem.</p> <p>If you do your own window placement you may get a better result then what a poor window manager would give, but you'll also miss out on the intelligent window placement algorithms available in more advanced window managers.</p>
5,039
<p>i've been approached to create a bespoke ftp app that users will download in order to be able to upload video files ( up to 100mb). </p> <ul> <li>they want it to be idiot proof ( ie easy for non-computer literate people ). I'm assuming that setting up an ftp app like FileZilla with their username and password would be too much of a stretch for most users. </li> <li>cross platform ( ouch )</li> </ul> <p>Surely i'm not the first person that has approached the problem of how to enable users to upload huge files. Wondering if anyone can give me any tips. </p>
<p>(Does it have to be FTP? FTP have trouble with firewalls, ASCII mode and of course the password is in the clear.)</p> <p>Many languages have FTP libraries available you could string together with a small amount of UI glue to make your own simple uploader app. For example Python has an ftplib in the standard library. Last time I did this was in C with Pfau's ftplib, for example, but modern scripting languages will be much easier to write in if you don't mind the overhead of packaging your app up with an interpreter.</p> <p>You have .NET in your tags... there isn't FTP in the standard class library for .NET but you can certainly download third-party libraries freely. On the other hand you say cross-platform, so I'm not sure if you're really talking about .NET on the client.</p> <p>What you could do is provide multiple means of upload, for example a basic HTTP* file upload built into your site, which everyone will know how to use, and a standard [S?]FTP interface for the advanced users who will be able to operate an FTP client. Not that operating an FTP client is really <em>that</em> difficult: just tell them to paste an ftp:// URL into Windows Explorer and most people should get on all right.</p> <p>*: ideally using AJAX feedback to let the user know how for their upload is going, and/or perhaps a Flash uploader. And remember to turn off/up any script timeout rules on the server so it doesn't give up halfway through an upload. HTTP upload will never be optimal for files of the order of 100MB, but you can certainly improve the default rather crappy unresponsiveness of browsers here.</p>
<p>Upload to where?</p> <p>You could get everyone to install <a href="http://getdropbox.com" rel="nofollow noreferrer">Dropbox</a> and create a share from a business account that they all have access to.</p>
26,416
<p>I want to be able to make an HTTP call updating some select boxes after a date is selected. I would like to be in control of updating the textbox so I know when there has been a "true" change (in the event the same date was selected). Ideally, I would call a function to pop-up the calendar and be able to evaluate the date before populating the text box...so I can do my validation before making a server call. </p>
<p>JQuery's <a href="http://docs.jquery.com/UI/Datepicker" rel="noreferrer">datepicker</a> is an extremely flexible tool. With the ability to attach handlers prior to opening or after date selection, <a href="http://marcgrabanski.com/article/jquery-ui-datepicker-themes" rel="noreferrer">themes</a>, range selection and a variety of other incredibly useful options, I've found that it meets all my needs.</p> <p>The fact that I sit next to one of its maintainers here at work is also fairly useful... </p>
<p>I don't like the MS ASP.NET ajax, but their datepicker is superb. Otherwise, jQuery datepicker.</p>
4,501
<p>We have a SQL 2000 server that has widely varied jobs that run at different times of day, or even different days of the month. Normally, we only use the SQL profiler to run traces for very short periods of time for performance troubleshooting, but in this case, that really wouldn't give me a good overall picture of the kinds of queries that are run against the database over the course of a day or week or month.</p> <p>How can I minimize the performance overhead of a long-running SQL trace? I already know to:</p> <ul> <li>Execute the trace server-side (sp_ create_trace), instead of using the SQL Profiler UI.</li> <li>Trace to a file, and not to a database table (which would add extra overhead to the DB server).</li> </ul> <p>My question really is about filters. If I add a filter to only log queries that run more than a certain duration or reads, it still has to <em>examine</em> all activity on the server to decide if it needs to log it, right? So even with that filter, is the trace going to create an unacceptable level of overhead for a server that is already on the edge of unacceptable performance? </p>
<p>I found an article that actually measures the performance impact of a SQL profiler session vs a server-side trace:</p> <p><a href="http://sqlblog.com/blogs/linchi_shea/archive/2007/08/01/trace-profiler-test.aspx" rel="nofollow noreferrer">http://sqlblog.com/blogs/linchi_shea/archive/2007/08/01/trace-profiler-test.aspx</a></p> <p>This really was my underlying question, how to make sure that I don't bog down my production server during a trace. It appears that if you do it correctly, there is minimal overhead.</p>
<p>It’s actually possible to collect more detailed measurements than you can collect from Profiler – and do it 24x7 across an entire instance -- without incurring any overhead. This avoids the necessity of figuring out ahead of time what you need to filter… which can be tricky. </p> <p>Full disclosure: I work for one of the vendors who provide such tools… but whether you use ours or someone else’s… this may get you around the core issue here.</p> <p>More info on our tool here <a href="http://bit.ly/aZKerz" rel="nofollow">http://bit.ly/aZKerz</a></p>
36,542
<p>I have got 3 text files (A, B and C), each with several hundred email addresses. I want to merge list A and list B into a single file, ignoring differences in case and white space. Then I want to remove all emails in the new list that are in list C, again ignoring differences in case and white space.</p> <p>My programming language of choice is normally C++, but it seems poorly suited for this task. Is there a scripting language that could do this (and similar tasks) in relatively few lines?</p> <p>Or is there software already out there (free or commercial) that would allow me to do it? Is it possible to do it in Excel, for example?</p>
<p>The fastest way to do this probably wouldn't necessarily require coding. You could import files A and B into Excel in one worksheet, then (if necessary) do a filter on that resulting list of addresses to remove any duplicates.</p> <p>The next step would be to import file C into a second worksheet. In a third worksheet, you'd do a VLOOKUP to pick out all the addresses in your first list and remove them if they're in your "List C".</p> <p>The VLOOKUP would look something like this:</p> <p><strong>=IF(ISNA(VLOOKUP(<em>email_address_cell</em>, Sheet2!<em>email_duplicates_list</em>, 1, false), "", (VLOOKUP(<em>email_address_cell</em>, Sheet2!<em>email_duplicates_list</em>, 1, false)))</strong></p> <p>I've also included a check to see if the formula returns a "Value Not Available" error, in which case the cell just shows a blank value. From there, you just need to remove your white-space and there's your final list.</p> <p>Now having said all that, you could still do a VBA macro to do much the same thing, but perhaps clean the lists up a bit, depending on what you need. Hope that helps!</p>
<p>Excel can do it, as above. The programming language most suited though is Perl. </p>
34,892
<p>I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's <em>invisible</em> to the end user?</p> <p>(The application is written in C#)</p>
<p>I found this article, which has a complete wrapper class included for manipulating the windows firewall. <a href="http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&amp;mid=404&amp;ctl=Details&amp;ItemID=8" rel="noreferrer">Adding an Application to the Exception list on the Windows Firewall</a></p> <pre class="lang-cs prettyprint-override"><code>/// /// Allows basic access to the windows firewall API. /// This can be used to add an exception to the windows firewall /// exceptions list, so that our programs can continue to run merrily /// even when nasty windows firewall is running. /// /// Please note: It is not enforced here, but it might be a good idea /// to actually prompt the user before messing with their firewall settings, /// just as a matter of politeness. /// /// /// To allow the installers to authorize idiom products to work through /// the Windows Firewall. /// public class FirewallHelper { #region Variables /// /// Hooray! Singleton access. /// private static FirewallHelper instance = null; /// /// Interface to the firewall manager COM object /// private INetFwMgr fwMgr = null; #endregion #region Properties /// /// Singleton access to the firewallhelper object. /// Threadsafe. /// public static FirewallHelper Instance { get { lock (typeof(FirewallHelper)) { if (instance == null) instance = new FirewallHelper(); return instance; } } } #endregion #region Constructivat0r /// /// Private Constructor. If this fails, HasFirewall will return /// false; /// private FirewallHelper() { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); // Assume failed. fwMgr = null; if (fwMgrType != null) { try { fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType); } // In all other circumnstances, fwMgr is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } } #endregion #region Helper Methods /// /// Gets whether or not the firewall is installed on this computer. /// /// public bool IsFirewallInstalled { get { if (fwMgr != null &amp;&amp; fwMgr.LocalPolicy != null &amp;&amp; fwMgr.LocalPolicy.CurrentProfile != null) return true; else return false; } } /// /// Returns whether or not the firewall is enabled. /// If the firewall is not installed, this returns false. /// public bool IsFirewallEnabled { get { if (IsFirewallInstalled &amp;&amp; fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled) return true; else return false; } } /// /// Returns whether or not the firewall allows Application "Exceptions". /// If the firewall is not installed, this returns false. /// /// /// Added to allow access to this metho /// public bool AppAuthorizationsAllowed { get { if (IsFirewallInstalled &amp;&amp; !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed) return true; else return false; } } /// /// Adds an application to the list of authorized applications. /// If the application is already authorized, does nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// This is the name of the application, purely for display /// puposes in the Microsoft Security Center. /// /// /// When applicationFullPath is null OR /// When appName is null. /// /// /// When applicationFullPath is blank OR /// When appName is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed OR /// If the firewall does not allow specific application 'exceptions' OR /// Due to an exception in COM this method could not create the /// necessary COM types /// /// /// If no file exists at the given applicationFullPath /// public void GrantAuthorization(string applicationFullPath, string appName) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (appName == null) throw new ArgumentNullException("appName"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("appName must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) &gt;= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed."); if (!AppAuthorizationsAllowed) throw new FirewallHelperException("Application exemptions are not allowed."); #endregion if (!HasAuthorization(applicationFullPath)) { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false); // Assume failed. INetFwAuthorizedApplication appInfo = null; if (authAppType != null) { try { appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType); } // In all other circumnstances, appInfo is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } if (appInfo == null) throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance."); appInfo.Name = appName; appInfo.ProcessImageFileName = applicationFullPath; // ... // Use defaults for other properties of the AuthorizedApplication COM object // Authorize this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo); } // otherwise it already has authorization so do nothing } /// /// Removes an application to the list of authorized applications. /// Note that the specified application must exist or a FileNotFound /// exception will be thrown. /// If the specified application exists but does not current have /// authorization, this method will do nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public void RemoveAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) &gt;= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion if (HasAuthorization(applicationFullPath)) { // Remove Authorization for this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath); } // otherwise it does not have authorization so do nothing } /// /// Returns whether an application is in the list of authorized applications. /// Note if the file does not exist, this throws a FileNotFound exception. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public bool HasAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) &gt;= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist.", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion // Locate Authorization for this application foreach (string appName in GetAuthorizedAppPaths()) { // Paths on windows file systems are not case sensitive. if (appName.ToLower() == applicationFullPath.ToLower()) return true; } // Failed to locate the given app. return false; } /// /// Retrieves a collection of paths to applications that are authorized. /// /// /// /// If the Firewall is not installed. /// public ICollection GetAuthorizedAppPaths() { // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); ArrayList list = new ArrayList(); // Collect the paths of all authorized applications foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) list.Add(app.ProcessImageFileName); return list; } #endregion } /// /// Describes a FirewallHelperException. /// /// /// /// public class FirewallHelperException : System.Exception { /// /// Construct a new FirewallHelperException /// /// public FirewallHelperException(string message) : base(message) { } } </code></pre> <p>The ClickOnce sandbox did not present any problems.</p>
<p>The answer is you only allow trusted software to run with Admin privileges. From time to time SOME software has to have admin privileges and make sensitive changes to your system. You might as well have a read only hard disk otherwise...</p>
13,889
<p>I've got the following in my .css file creating a little image next to each link on my site:</p> <pre class="lang-css prettyprint-override"><code>div.post .text a[href^="http:"] { background: url(../../pics/remote.gif) right top no-repeat; padding-right: 10px; white-space: nowrap; } </code></pre> <p>How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?</p>
<p>If you set the background color and have a negative right margin on the image, the image will cover the external link image.</p> <p>Example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a[href^="http:"] { background: url(http://en.wikipedia.org/skins-1.5/monobook/external.png) right center no-repeat; padding-right: 14px; white-space: nowrap; } a[href^="http:"] img { margin-right: -14px; border: medium none; background-color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="http://www.google.ca"&gt;Google&lt;/a&gt; &lt;br/&gt; &lt;a href="http://www.google.ca"&gt; &lt;img src="http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/50px-Commons-logo.svg.png" /&gt; &lt;/a&gt;</code></pre> </div> </div> </p> <p>edit: If you've got a patterned background this isn't going to look great for images that have transparency. Also, your <code>href^=</code> selector won't work on IE7 but you probably knew that already</p>
<p>If you have the content of the links as a span, you could do this, otherwise I think you would need to give one scenario a class to differentiate it.</p> <pre class="lang-css prettyprint-override"><code>a &gt; span { background: url(../../pics/remote.gif) right top no-repeat; padding-right: 10px; white-space: nowrap; } a &gt; img { /* any specific styling for images wrapped in a link (e.g. polaroid like) */ border: 1px solid #cccccc; padding: 4px 4px 25px 4px; } </code></pre>
8,399
<p>I'm looking to use SQL to format a number with commas in the thousands, but no decimal (so can't use Money) - any suggestions?</p> <p>I'm using SQL Server 2005, but feel free to answer for others as well (like MySQL)</p>
<p>In MySQL, the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format" rel="nofollow noreferrer"><code>FORMAT()</code></a> function will do the trick.</p>
<p>For SQL Server, you could format the number as money and then delete the right-most three characters.</p> <pre><code>replace(convert (varchar, convert (money, 109999), 1), '.00','') </code></pre>
6,363
<p>I'm about to begin an ASP.NET application that will be targeted towards iPhones, Blackberries, and Windows Mobile browsers. Aside from the iPhone, I haven't been able to find much information on what technologies these platforms support.</p> <p>Since I'm used to developing for desktop browsers, I like using things like jQuery and advanced CSS features. It looks like I won't be able to use these things on a mobile platform.</p> <p>What I was wondering is if anyone knew good developer's resources where I could find what works for mobile browsers (like a <a href="http://quirksmode.org" rel="nofollow noreferrer">quirksmode.org</a> for mobile devices).</p> <p>As far as I know, jQuery won't work on mobile browsers (besides the iPhone). Does anyone know of any attempts to port jQuery in some form to mobile browsers? I say jQuery because that's what my existing website uses and I'd like to keep consistency, but if there are offerings from other frameworks, I'd be interested in checking them out too.</p> <p><strong>UPDATE</strong><br> I wanted to update this to let anyone know who might stumble upon this question. The person who runs the site quirksmode.org has recently begun creating Mobile Device compatibility tables. You can check them out here: </p> <p><a href="http://quirksmode.org/m/" rel="nofollow noreferrer">http://quirksmode.org/m/</a></p>
<p>Both Microsoft and RIM have made emulators of their mobile operating systems available. I highly recommend downloading them. They can piggyback off the host operating system and use your ethernet connection to retrieve URLs and display them as their real-world counterparts.</p>
<p>Last I checked the Windows Mobile IE was a fork from the IE5 codebase, so what worked there, <em>should</em> work on mobile IE. However I recall some limitations (hopefully others can clarify) I was under the impression that the list was not supported.</p> <p>As for iPhone, outside of flash, it should do whatever Safari does on Windows/Mac.</p> <p>Blackberry devices use their own proprietary browser, you'll have to see if someone has details on it.</p>
34,637
<p>I am coming from Java and am currently working on a C# project. What is the recommended way to go about a) unit testing existing C# code and b) accomplishing TDD for C# development?</p> <p>Also is there an equivalent to EMMA / EclEmma (free yet powerful code coverage tool) for Visual Studio and C# code?</p>
<p>1 <a href="http://www.nunit.org/" rel="noreferrer">Nunit</a><br> 2 <a href="http://ncover.org/" rel="noreferrer">NCover</a> or<br> 3 <a href="http://sourceforge.net/projects/partcover/" rel="noreferrer">PartCover</a> (I never used it) </p>
<p>I'd install:</p> <ol> <li>NUnit for your Unit testing framework <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">http://www.nunit.org/index.php</a></li> <li>Test driven.net for runing your tests <a href="http://www.testdriven.net/" rel="nofollow noreferrer">http://www.testdriven.net/</a></li> <li>Rhino Mocks as your mockign framework <a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">http://ayende.com/projects/rhino-mocks.aspx</a></li> </ol> <p>As and aside I find it odd that the NUnit guys seem to be using php to host their homepage...</p>
21,032
<p>Could anyone could point me to some code/give me ideas on how to create a smooth scrolling vertical marquee for VFP 8 or 9?</p> <p>Any help is appreciated.</p>
<p>I guess the question boils down to whether you need to be in complete control of the video, and whether you have money to throw at the project. If you host on youtube etc you are subject to their terms of service and need to work within the constraints of their branding.</p> <p>When I have needed complete control of Flash video clips for clients I have used the <a href="http://www.jeroenwijering.com/?item=JW_FLV_Player" rel="nofollow noreferrer">JW-FLV</a> player. It will happily serve FLV files off an HTTP server. It is possible to embed the player in another Flash movie, but most often you will control the playlist from HTML links. Hosting video files can get very expensive, so expect to pay a hefty bandwidth bill.</p> <p>I would use a 3rd party service if I was creating video for public consumption that had some sort of marketing aspect to it. Host it on YouTube and you can get very good exposure, and people have a chance of finding your video. These services also have global reach in their networks so you may get better performance worldwide.</p> <p>Google recently released Video for Google Apps customers. This allows you to secure your Google video to users belonging to your organisation. This bridges the gap for some projects that would traditionally use self-hosting.</p>
<p>If you are going to use a 3rd party site, use vimeo - it's a great user experience and great video quality.</p>
14,025
<p>What is currently the best way to get a favicon to display in all browsers that currently support it?</p> <p>Please include:</p> <ol> <li><p>Which image formats are supported by which browsers.</p></li> <li><p>Which lines are needed in what places for the various browsers.</p></li> </ol>
<p>I go for a belt and braces approach here. </p> <p>I create a 32x32 icon in both the <code>.ico</code> and <code>.png</code> formats called <code>favicon.ico</code> and <code>favicon.png</code>. The icon name doesn't really matter unless you are dealing with older browsers.</p> <ol> <li>Place <code>favicon.ico</code> at your site root to support the older browsers (optional and only relevant for older browsers.</li> <li>Place favicon.png in my images sub-directory (just to keep things tidy).</li> <li>Add the following HTML inside the <code>&lt;head&gt;</code> element.</li> </ol> <pre>&lt;link rel="icon" href="/images/favicon.png" type="image/png" /&gt; &lt;link rel="shortcut icon" href="/favicon.ico" /&gt;</pre> <p>Please note that:</p> <ul> <li>The MIME type for <code>.ico</code> files was registered as image/vnd.microsoft.icon by the <a href="http://www.iana.org" rel="noreferrer"><strong>IANA</strong></a>. </li> <li>Internet Explorer will ignore the <code>type</code> attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied.</li> </ul> <p><a href="http://www.jonathantneal.com/blog/understand-the-favicon/" rel="noreferrer"><strong>Reference</strong></a></p>
<p>The answer to this question has become <a href="https://stackoverflow.com/a/48969053/7343159">complicated enough</a> that the best way is to just use a tool like RealFaviconGenerator, which lets you upload a png/jpg and then generates favicons and code to cover all the platforms for you: <a href="https://realfavicongenerator.net/" rel="nofollow noreferrer">https://realfavicongenerator.net/</a></p>
5,776
<p>Will be starting a web app that will have to provide <strong>many different HTML forms for data entry</strong>, so I was wondering if there is a web framework out there that does this in a clever way. generally when you have forms you have many considerations like navigation, validation, etc. that are not handled very efficiently by he frameworks I've seen so far.</p> <p>Has someone taken the pain out of forms?</p>
<p>Have you tried looking at <a href="http://grails.org/" rel="nofollow noreferrer">Grails</a>? It can take your domain classes and dynamically scaffold them into web forms and apply server-side validation. The default scaffolding provides navigation, pagination, validation, and all kinds of other -ations that are pretty good!</p> <p>Here's a <a href="http://www.ibm.com/developerworks/java/library/j-grails01158/" rel="nofollow noreferrer">good tutorial</a>.</p>
<p>Try Qcodo.com, It is written in PHP (but fully OOP). It manages both database layer with nice Form templating system.</p>
49,045
<p>Is it a deliberate design decision or a problem with our current day browsers which will be rectified in the coming versions?</p>
<p>JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread (AFAIK). Even Google Chrome will not let a single web page’s JavaScript run concurrently because this would cause massive concurrency issues in existing web pages. All Chrome does is separate multiple components (different tabs, plug-ins, etcetera) into separate processes, but I can’t imagine a single page having more than one JavaScript thread.</p> <p>You can however use, as was suggested, <code>setTimeout</code> to allow some sort of scheduling and β€œfake” concurrency. This causes the browser to regain control of the rendering thread, and start the JavaScript code supplied to <code>setTimeout</code> after the given number of milliseconds. This is very useful if you want to allow the viewport (what you see) to refresh while performing operations on it. Just looping through e.g. coordinates and updating an element accordingly will just let you see the start and end positions, and nothing in between.</p> <p>We use an abstraction library in JavaScript that allows us to create processes and threads which are all managed by the same JavaScript interpreter. This allows us to run actions in the following manner:</p> <ul> <li>Process A, Thread 1</li> <li>Process A, Thread 2</li> <li>Process B, Thread 1</li> <li>Process A, Thread 3</li> <li>Process A, Thread 4</li> <li>Process B, Thread 2</li> <li>Pause Process A</li> <li>Process B, Thread 3</li> <li>Process B, Thread 4</li> <li>Process B, Thread 5</li> <li>Start Process A</li> <li>Process A, Thread 5</li> </ul> <p>This allows some form of scheduling and fakes parallelism, starting and stopping of threads, etcetera, but it will not be true multi-threading. I don’t think it will ever be implemented in the language itself, since true multi-threading is only useful if the browser can run a single page multi-threaded (or even more than one core), and the difficulties there are way larger than the extra possibilities.</p> <p>For the future of JavaScript, check this out: <a href="https://web.archive.org/web/20170920070053/https://developer.mozilla.org/presentations/xtech2006/javascript/" rel="noreferrer">https://developer.mozilla.org/presentations/xtech2006/javascript/</a></p>
<p>Multi-threading with javascript is clearly possible using webworkers bring by HTML5.</p> <p>Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.</p> <p>Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming <a href="https://github.com/GOMServices/oodk-js-oop-for-js" rel="nofollow">https://github.com/GOMServices/oodk-js-oop-for-js</a></p>
6,104
<p>I'd like to buy a 3D printer and use it as a &quot;platform&quot; for an <strong>external</strong> optical sensor. The idea is to mount an optical sensor on the Z-axis and to put a workpiece on the X-Y table. Now, I'd like to move the sensor across the workpiece and trigger the measurement of the optical sensor. Hence, the 3D printer is not actually printing, but only used as a motion and trigger device for the optical sensors.</p> <p>I have never used a 3D printer, but I'm afraid that I'll run into several problems:</p> <ol> <li>The standard G-code of &quot;wait one second&quot; is <code>G04 X1</code> on many CNC machines. Does this code exist on 3D printers as well?</li> <li>Is it possible to extract a trigger signal (e.g. 5Β V) from the 3D printer? Are printers available which provide a G-code for an external trigger? Could anybody suggest a model? I'm happy to pay some extra dollars if I don't have to solder by myself. Of course, a second option would be to use the voltage, which is used to heat the filament.</li> </ol>
<p>A flexible material, such as PETG or ABS, is probably the best. PLA is brittle, especially after absorbing moisture, and probably would crack under continued use.</p> <p>Nylon is good, but not easy to use. With PETG in an enclosure, I end up running fans to avoid heat creep; so PETG may actually do better without an enclosure.</p> <p>If you're printing to flex your print, keep in mind the the x and y axes are stronger than the z-axis, which depends on how well the layers stick together. PETG tends to stick to the print surface too well; so I use an Elmer's glue stick for it to pull up the glue layer instead of damaging my print surface.</p>
<p>PETG, ABS and NYLON would work great for press-fit or snap-fit connections. If you really can't build a (cardboard) enclosure I would go for PETG as it has good repeatable mechanical properties and does not require an enclosure.</p>
1,905
<p>What is the best way to generate a current datestamp in Java? </p> <p>YYYY-MM-DD:hh-mm-ss</p>
<p>Using the standard JDK, you will want to use java.text.SimpleDateFormat</p> <pre><code>Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); String myDateString = sdf.format(myDate); </code></pre> <p>However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat</p> <pre><code>Date myDate = new Date(); FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss"); String myDateString = fdf.format(myDate); </code></pre> <p>FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); Date yourDate = sdf.parse("2008-09-18:22-03-15"); </code></pre>
<p>SimpleDateFormatter is what you want. </p>
12,437
<p>I'm looking into a mechanism for serialize data to be passed over a socket or shared-memory in a language-independent mechanism. I'm reluctant to use XML since this data is going to be very structured, and encoding/decoding speed is vital. Having a good C API that's liberally licensed is important, but ideally there should be support for a ton of other languages. I've looked at <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">google's protocol buffers</a> and <a href="http://en.wikipedia.org/wiki/ASN.1" rel="noreferrer">ASN.1</a>. Am I on the right track? Is there something better? Should I just implement my own packed structure and not look for some standard?</p>
<p>Given your requirements, I would go with Google Protocol Buffers. It sounds like it's ideally suited to your application.</p>
<p>Few Thing's you need to Consider</p> <pre><code>1. Storage 2. Encoding Style (1 byte 2 byte) 3. TLV standards </code></pre> <p>ASN.1 Parser is the good for binary represenations the best part is ASN.1 is a well-established technology that is widely used both within ITU-T and outside of it. The notation is supported by a number of software vendors.</p>
17,419
<p>I need to do transactions (begin, commit or rollback), locks (select for update). How can I do it in a document model db?</p> <p>Edit:</p> <p>The case is this:</p> <ul> <li>I want to run an auctions site.</li> <li>And I think how to direct purchase as well.</li> <li>In a direct purchase I have to decrement the quantity field in the item record, but only if the quantity is greater than zero. That is why I need locks and transactions.</li> <li>I don't know how to address that without locks and/or transactions.</li> </ul> <p>Can I solve this with CouchDB?</p>
<p>No. CouchDB uses an "optimistic concurrency" model. In the simplest terms, this just means that you send a document version along with your update, and CouchDB rejects the change if the current document version doesn't match what you've sent.</p> <p>It's deceptively simple, really. You can reframe many normal transaction based scenarios for CouchDB. You do need to sort of throw out your RDBMS domain knowledge when learning CouchDB, though. It's helpful to approach problems from a higher level, rather than attempting to mold Couch to a SQL based world.</p> <p><strong>Keeping track of inventory</strong></p> <p>The problem you outlined is primarily an inventory issue. If you have a document describing an item, and it includes a field for "quantity available", you can handle concurrency issues like this:</p> <ol> <li>Retrieve the document, take note of the <code>_rev</code> property that CouchDB sends along</li> <li>Decrement the quantity field, if it's greater than zero</li> <li>Send the updated document back, using the <code>_rev</code> property</li> <li>If the <code>_rev</code> matches the currently stored number, be done!</li> <li>If there's a conflict (when <code>_rev</code> doesn't match), retrieve the newest document version</li> </ol> <p>In this instance, there are two possible failure scenarios to think about. If the most recent document version has a quantity of 0, you handle it just like you would in a RDBMS and alert the user that they can't actually buy what they wanted to purchase. If the most recent document version has a quantity greater than 0, you simply repeat the operation with the updated data, and start back at the beginning. This forces you to do a bit more work than an RDBMS would, and could get a little annoying if there are frequent, conflicting updates.</p> <p>Now, the answer I just gave presupposes that you're going to do things in CouchDB in much the same way that you would in an RDBMS. I might approach this problem a bit differently:</p> <p>I'd start with a "master product" document that includes all the descriptor data (name, picture, description, price, etc). Then I'd add an "inventory ticket" document for each specific instance, with fields for <code>product_key</code> and <code>claimed_by</code>. If you're selling a model of hammer, and have 20 of them to sell, you might have documents with keys like <code>hammer-1</code>, <code>hammer-2</code>, etc, to represent each available hammer.</p> <p>Then, I'd create a view that gives me a list of available hammers, with a reduce function that lets me see a "total". These are completely off the cuff, but should give you an idea of what a working view would look like.</p> <p><strong>Map</strong></p> <pre><code>function(doc) { if (doc.type == 'inventory_ticket' &amp;&amp; doc.claimed_by == null ) { emit(doc.product_key, { 'inventory_ticket' :doc.id, '_rev' : doc._rev }); } } </code></pre> <p>This gives me a list of available "tickets", by product key. I could grab a group of these when someone wants to buy a hammer, then iterate through sending updates (using the <code>id</code> and <code>_rev</code>) until I successfully claim one (previously claimed tickets will result in an update error).</p> <p><strong>Reduce</strong></p> <pre><code>function (keys, values, combine) { return values.length; } </code></pre> <p>This reduce function simply returns the total number of unclaimed <code>inventory_ticket</code> items, so you can tell how many "hammers" are available for purchase.</p> <p><strong>Caveats</strong></p> <p>This solution represents roughly 3.5 minutes of total thinking for the particular problem you've presented. There may be better ways of doing this! That said, it does substantially reduce conflicting updates, and cuts down on the need to respond to a conflict with a new update. Under this model, you won't have multiple users attempting to change data in primary product entry. At the very worst, you'll have multiple users attempting to claim a single ticket, and if you've grabbed several of those from your view, you simply move on to the next ticket and try again.</p> <p>Reference: <a href="https://wiki.apache.org/couchdb/Frequently_asked_questions#How_do_I_use_transactions_with_CouchDB.3F" rel="noreferrer">https://wiki.apache.org/couchdb/Frequently_asked_questions#How_do_I_use_transactions_with_CouchDB.3F</a></p>
<p>Just use SQlite kind of lightweight solution for transactions, and when the transaction is completed successfully replicate it, and mark it replicated in SQLite</p> <p>SQLite table</p> <pre><code>txn_id , txn_attribute1, txn_attribute2,......,txn_status dhwdhwu$sg1 x y added/replicated </code></pre> <p>You can also delete the transactions which are replicated successfully.</p>
38,411
<p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p> <p>The alternatives I tried were:</p> <ul> <li><p>Boost.Python</p> <p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li> <li><p>SWIG</p> <p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li> </ul> <p>What have you used to do this, and what has been your experience with it?</p>
<p>I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has <em>much</em> better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.</p> <p>I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.</p>
<p>A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.</p> <p>The downside: It takes so long to install and use Boost that all the Tab-completion time-saving won't ever amortize ;-(</p> <p>So I prefer Swig: No bells and whistles, but works reliably after a short introductory example.</p>
34,906
<p>Imagine I have String in C#: "I DonΓƒΒ’Γ’β€šΒ¬Γ’β€žΒ’t see ya.."</p> <p>I want to remove (replace to nothing or etc.) these "ΓƒΒ’Γ’β€šΒ¬Γ’β€žΒ’" symbols. </p> <p>How do I do this?</p>
<p>That 'junk' looks a lot like someone interpreted UTF-8 data as ISO 8859-1 or Windows-1252, probably repeatedly.</p> <p>ΓƒΒ’Γ’β€šΒ¬Γ’β€žΒ’ is the sequence C3 A2, E2 82 AC, E2 84 A2.</p> <ul> <li>UTF-8 C3 A2 = U+00E2 = Γ’</li> <li>UTF-8 E2 82 AC = U+20AC = €</li> <li>UTF-8 E2 84 A2 = U+2122 = β„’</li> </ul> <p>We then do it again: in Windows 1252 this sequence is E2 80 99, so the character should have been U+2019, RIGHT SINGLE QUOTATION MARK (’)</p> <p>You could make multiple passes with byte arrays, Encoding.UTF8 and Encoding.GetEncoding(1252) to correctly turn the junk back into what was originally entered. You will need to check your processing to find the two places that UTF-8 data was incorrectly interpreted as Windows-1252.</p>
<p>The ASCII / Integer code for these characters would be out of the normal alphabetic Ranges. Seek and replace with empty characters. String has a Replace method I believe.</p>
9,830
<p>There are various samples available for how to host Python or Ruby running on the DLR, inside your own AppDomain.</p> <p>Are you able to do this yet with VB? There have been mentions of this since the DLR was announced 18 months ago, but I can't find a code sample for it.</p> <p>Maybe with the PDC VS10 CTP? If so, what assembly contains the appropriate subclassed ScriptRuntime for VBx?</p> <p>If this is not yet possible, can any MSFT-ies give us an update on when we might see some bits?</p>
<p>There's no release of VB (or C#) that is hostable via the DLR hosting APIs. In general the DLR hosting APIs, and the possibility of getting more MS created languages to support them, are tenatively thought to be post-Dev10. So it won't happen anytime in the short term.</p>
<p>Officially, there's no supported dynamic languages until VS10 is released. At that time, VBx, which apparently will be built on top of the DLR, will be released, probably alongside version 2.0 of the DLR. (Version 1.0's release is immanent.)</p> <p>You might find some useful stuff in the VS10 CTP, but keep in mind it's neither supported, nor will there be much for documentation at this time. If you're hell-bent on hosting VB in your app, on the DLR, you'll just have to wait a year and a bit.</p>
38,089
<p>I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales such as the following:</p> <p><strong>Locales (ID, LocationName, ParentID)</strong> where autonomous locations (such as countries, e.g. USA) are parents of themselves. This way I can have an arbitrarily deep nesting of 'political units' (COUNTRY > STATE > CITY or COUNTRY > STATE > CITY > UNIVERSITY). Some queries will necessarily involve recursion.</p> <p>I would appreciate any other recommendations or perhaps advice regarding predictable issues that I am likely to encounter with such a scheme.</p>
<p>You might want to have a look at Freebase.com as a site that's had some open discussion about what a "location" means and what it means when a location is included in another. These sorts of questions can generate a lot of discussion.</p> <p>For example, there is the obvious "geographic nesting", but there are less obvious logical nestings. For example, in a strictly geographic sense, Vatican City is nested within Italy. But it's not nested politically. Similarly, if your user is located in a research center that belongs to a university, but isn't located on the University's property, do you model that relationship or not?</p>
<p>I'm modeling an apps for global users and I have the same problems, but I think that this approach could already be in use in many enterprise. But why this problem don't have an universal solution? Or, has this problem one best solution that can be the start point or anybody in the world need think in a solution for it since beginnig? In IT, we are making the same things any times and in many places, unfortunately. For exemplo, who are not have made more than one user, customer or product's database? And the worst, all enterprise in the world has made it. I think that could have universal solutions for universal problems.</p>
7,298
<p>I have a problem when assigning functions to the click event of a button in IE 7 with jQuery. Something like the following works fine in Opera but produces an infinite loop in IE:</p> <pre><code>function updateIndputFields(index, id) { $("#reloadBtn").click(function(){ updateIndputFields(index, id) }); } </code></pre> <p>As I understand it, an infinite loop would not be the expected behavior in this situation. But I'm new to jQuery so maybe I've missed something. Anyways, what should I do to make the click event of the reloadBtn button be set to 'updateIndputFields(index, id)' in IE?</p>
<p>I think the key to your answer is in unbinding the event that you have already bound to the click event. I used this on IE and, if I understand what you're trying to do, it seems to do what you need:</p> <pre><code>&lt;script type="text/javascript"&gt; function updateIndputFields(index, id) { $('#output').append('&lt;p&gt;' + index + ' : ' + id + '&lt;/p&gt;'); $('#reloadBtn').unbind('click'); $("#reloadBtn").click(function(){ updateIndputFields(index, id) }); } &lt;/script&gt; &lt;p&gt;&lt;a href="#" id="reloadBtn"&gt;reload&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="#" onclick="updateIndputFields(1,2);return false;"&gt;start&lt;/a&gt;&lt;/p&gt; &lt;div id="output"&gt;&lt;/div&gt; </code></pre> <p>Each click should output the passed parameters exactly once into the output div.</p> <p>If you don't unbind the originally assigned click event, then it stays present and you attach a duplicate click event handler to the event each time it's clicked. Even in Firefox, not unbinding the event creates an interesting recursive situation.</p>
<p>Try unbinding the event before binding it.</p>
40,763
<p>Is there any difference between a <code>volatile</code> Object reference and <code>AtomicReference</code> in case I would just use <code>get()</code> and <code>set()</code>-methods from <code>AtomicReference</code>?</p>
<p>Short answer is: No.</p> <p>From the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/package-summary.html" rel="noreferrer"><code>java.util.concurrent.atomic</code></a> package documentation. To quote:</p> <blockquote> <p>The memory effects for accesses and updates of atomics generally follow the rules for volatiles:</p> <ul> <li><code>get</code> has the memory effects of reading a <code>volatile</code> variable.</li> <li><code>set</code> has the memory effects of writing (assigning) a <code>volatile</code> variable.</li> </ul> </blockquote> <p>By the way, that documentation is very good and everything is explained.</p> <hr> <p><a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/AtomicReference.html#lazySet(V)" rel="noreferrer"><code>AtomicReference::lazySet</code></a> is a newer (Java 6+) operation introduced that has semantics unachievable through <code>volatile</code> variables. See <a href="https://stackoverflow.com/a/1468020/591495)">this post</a> for more information.</p>
<p>Sometimes even if you only use gets and sets, AtomicReference might be a good choice:</p> <p>Example with volatile:</p> <pre class="lang-java prettyprint-override"><code>private volatile Status status; ... public setNewStatus(Status newStatus){ status = newStatus; } public void doSomethingConditionally() { if(status.isOk()){ System.out.println("Status is ok: " + status); // here status might not be OK anymore because in the meantime some called setNewStatus(). setNewStatus should be synchronized } } </code></pre> <p>The implementation with AtomicReference would give you a copy-on-write synchronization for free.</p> <pre class="lang-java prettyprint-override"><code>private AtomicReference&lt;Status&gt; statusWrapper; ... public void doSomethingConditionally() { Status status = statusWrapper.get(); if(status.isOk()){ System.out.println("Status is ok: " + status); // here even if in the meantime some called setNewStatus() we're still referring to the old one } } </code></pre> <p>One might say that you could still could have a proper copy if you substituted:</p> <pre class="lang-java prettyprint-override"><code>Status status = statusWrapper.get(); </code></pre> <p>with:</p> <pre class="lang-java prettyprint-override"><code>Status statusCopy = status; </code></pre> <p>However the second one is more likely to be removed by someone accidentally in the future during "code cleaning".</p>
35,566
<p>Given a DOM element how do I find its nearest parent with a given css class?</p> <pre><code>$(".editButton").click(function() { (magic container selector goes here).addClass("editing"); }); </code></pre> <p>I don't want to use lots or $(...).parent().parent() since I don't want to be bound to a particular dom structure.</p>
<p>This should work</p> <pre><code>$(this).parents('.classYouWant:first').addClass("editing"); </code></pre>
<p>Use <code>.parents(".yourClass")</code> instead of <code>.parent()</code>.</p> <p><a href="http://docs.jquery.com/Traversing/parents#expr" rel="nofollow noreferrer">jQuery parents()</a></p>
49,526
<p>We have a huge web application running on lasso, mainly because it first was a huge internal Filemaker database, that was to be opened to the public as a web app.</p> <p>The web application doesn't use Filemaker though, it runs on a MySQL database, recreated every day.</p> <p>The only reason I know of for using lasso is it's easy integration with Filemaker, but I never used lasso. (I'm a perl/php/mysql/javascript guy)</p> <hr> <p>So I have three questions:<br> Is lasso a viable language for a web app? Are there any important benefits it offers over other languages?</p> <p>Should we want to upgrade that app, should we use a more widely used and know language, or should we stick with lasso?</p> <p>Is there anyone here that actually uses lasso?</p>
<p>Hey there... just thought I'd add my two cents to the discussion: I am currently developing daily in Lasso. I was hired here (big New England university) about 1.5 years ago as a web programmer... with little programming experience (In a former life, I was a web designer. I knew CSS and HTML like the back of my hand, but only some very limited php). In fact, I hadn't even heard of the Lasso programming language before I started here. Anyway, they were pretty confident that I'd pick it up quickly. As skeptical as I was, they were right. The Lasso syntax is quick and easy to learn. Once you wrap your head around the syntax and the <code>[SquareBrackets]</code>, the rest falls into place instantly. In a short time I was able to build some really complex, database driven, web apps. </p> <p>As far as community, clearly Lasso's is nowhere near the size of that of php or ruby... but what I've found is that Lasso's developers are die hard fans of the language and thus are very active and helpful. Personally, I find a small devoted community more easily approachable and less intimidating. Most of the really juicy Lasso conversations take place on <a href="http://www.nabble.com/Lasso---Talk-f739.html" rel="nofollow noreferrer">LassoTalk</a>. Oh also, I went to the Lasso Developers Conference last year and was blown away by the dedication of the Lassosoft company and the developer community. (Not to mention all of the exciting stuff coming up in Lasso 9... later this year?)</p> <p>Some downsides to Lasso: First and foremost, cost. It's expensive. There's no two ways about it (though if you're just looking to build something for demo or for a very small deployment, you might be able to get away with the <a href="http://www.lassosoft.com/Downloads/index.lasso" rel="nofollow noreferrer">developer's installation</a>). Second, lack of mature hosting options. Take a look at the vast amount of stuff you can get in any random $5/mo. php hosting plan and compare that to anything you can find for Lasso. Yeah, it's pretty rough out there (these guys are not much to look at, but are pretty reliable: <a href="http://cheaplassohosting.com/" rel="nofollow noreferrer">cheaplassohosting.com</a>). I'd guess that most Lasso users are hosting their own solutions though.</p> <p>If you decide to keep going with Lasso, here a few resources that I've found to be invaluable:</p> <p><a href="http://tagswap.net/index.lasso" rel="nofollow noreferrer">tagSwap - a puplic exchange for lasso custom tags</a></p> <p><a href="http://reference.lassosoft.com/Reference.LassoApp" rel="nofollow noreferrer">Lasso Reference</a></p> <p><a href="http://www.lassosoft.com/Documentation/TotW/index.lasso" rel="nofollow noreferrer">Tip of the Week</a></p> <p>Also worth noting, there's a Lasso environment for Eclipse as well as a built-in support in Panic's Coda (which I enthusiastically endorse!).</p> <p>Yeesh... didn't mean for this to be so lengthy. Anyway, I'd be happy to answer some specifics for you. Good luck with whatever direction you choose to go in!</p>
<p>We are unfortunately maintaining a Lasso app here and it's an absolute nightmare. Lasso crashes once a day on average. The people at LassoSoft are very quick at taking our money but do not provide any useful support. Also like you probably noticed, nobody uses Lasso and you'll struggle to hire qualified staff. You'd be better off with Ruby, Python, Perl, Java or even PHP.</p>
38,712
<p>We have seen the following exceptions very frequently on IBM AIX when attempting to make an SSL connection to our server:</p> <pre><code>java.net.SocketException: Socket closed at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275(Compiled Code)) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(DashoA6275(Compiled Code)) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java(Inlined Compiled Code)) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java(Compiled Code)) at java.io.FilterOutputStream.flush(FilterOutputStream.java(Compiled Code)) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Inlined Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Inlined Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.checkForNewMessages(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.timeoutExpired(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.xmd.timer.TimerEvent$1.run(TimerEvent.java(Compiled Code)) </code></pre> <p>From the error, you would think this was just a network problem, but the client had never experienced the problem before about 2 months ago, and AFAIK, there haven't been any changes to the network layout.</p> <p>We also receive this fairly frequently:</p> <pre><code>java.net.SocketException: Connection timed out:could be due to invalid address at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:336) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:201) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188) at java.net.Socket.connect(Socket.java:478) at java.net.Socket.connect(Socket.java:428) at java.net.Socket.&lt;init&gt;(Socket.java:335) at java.net.Socket.&lt;init&gt;(Socket.java:210) at javax.net.ssl.SSLSocket.&lt;init&gt;(Unknown Source) </code></pre> <p>I'm suspecting that this is an AIX problem, but I guess it could be a firewall issue? I also saw some people in google searches hinting at a problem with commons http, but I couldn't see how that would be related.</p> <p>Is this something that others have seen with AIX recently?</p>
<p>"java.net.SocketException: Socket closed" means that your side closed the socket. You say that this happens when you attempt to make an SSL connection to your server. However, the stack trace suggests that this happens when HTTPClient attempts to write an HTTP request over an already established connection.</p> <p>This could happen if, for example, you somehow managed to make HTTPClient send a request via a connection that was previously closed by HTTPClient, or, more likely, by some other code on your side. Check whether you are accessing the underlying socket somewhere. Or it could be that the socket is closed by the SSL/TLS protocol (if I'm not mistaken, SSL/TLS has its own higher-level protocol for closing the underlying connection), but HTTPClient somehow managed to not notice this (don't know whether it's possible, but, say, the remote side closed the SSL connection but was using HTTP/1.1 persistent connections and didn't set a Connection: close response).</p> <p>You can troubleshoot these issues by analyzing the TCP traffic using tcpdump/Wireshark. You could also start an stunnel on a machine to the server's HTTPS port, then make your code communicate with the server over plain HTTP via this tunnel. This should enable you to see the HTTP traffic in plaintext.</p> <p>"java.net.SocketException: Connection timed out" means that the TCP connection could not be established due to a timeout. Could be that the packets are dropped by a firewall. For example, it could be that you need to use an HTTP proxy to make HTTPS requests. It could also be that the server machine is really busy or the network is really busy. Again, I suggest you try tcpdump/Wireshark to see what's going on at the TCP level.</p>
<p>I have had issues with http client that were corrected by using a multithreaded connection. We fixed it by moving from the first to the second of the configurations below:</p> <pre><code>&lt;bean id="httpClient" class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"&gt; &lt;property name="httpClient"&gt; &lt;bean class="org.apache.commons.httpclient.HttpClient"&gt; &lt;property name="connectionTimeout"&gt;&lt;value&gt;1000&lt;/value&gt;&lt;/property&gt; &lt;property name="timeout"&gt;&lt;value&gt;3000&lt;/value&gt;&lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="httpClient" class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"&gt; &lt;property name="httpClient"&gt; &lt;bean class="org.apache.commons.httpclient.HttpClient"&gt; &lt;property name="connectionTimeout"&gt;&lt;value&gt;1000&lt;/value&gt;&lt;/property&gt; &lt;property name="timeout"&gt;&lt;value&gt;3000&lt;/value&gt;&lt;/property&gt; &lt;property name="httpConnectionManager"&gt; &lt;bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager" destroy-method="shutdown"&gt; &lt;property name="params"&gt; &lt;bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams"&gt; &lt;property name="defaultMaxConnectionsPerHost" value="20" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre>
26,290
<p>I have several arrays of arrays or arrays of dicts that I would like to store in my iPhone app. This lists are static and won't be modified by the app or users. Occasionally they may be displayed but more likely they'll be iterated over and compared to some input value. Would the best way to store these arrays be a CoreData/SQLite data store, in a header file, or something I'm not thinking of? I could see making a class that only has these arrays stored in them for access, but I'm not sure if that's the best route to take.</p>
<p>Use a property list file. Load it with NSDictionary +dictionaryWithContentsofFile:.</p>
<p>Depending on how often you want to modify or localize the items, and your lookup time requirements, a static array may also be the way to go. For constant data, however, SQLite is probably not the route to take, unless you have complex query requirements (as opposed to just by-index).</p>
30,232
<p>I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.</p> <p>For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence.</p>
<p>You're seeing that behaviour because innerHTML is read-only for table elements in IE. From MSDN's <a href="http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx" rel="noreferrer">innerHTML Property</a> documentation:</p> <blockquote> <p>The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.</p> </blockquote>
<p>I just figured out that if you try to set innerHTML on an element in IE that isn't logically correct it will throw this error. For example if you try and set the innerHTML of a table to "<b> hi from stu </b>" it will fail, because the table must be followed by a sequence. Apparently firefox isn't this picky. Hope it helps.</p>
18,797
<p>I try to externalize all strings (and other constants) used in any application I write, for many reasons that are probably second-nature to most stack-overflowers, but one thing I would like to have is the ability to automate spell checking of any user-visible strings. This poses a couple problems:</p> <ul> <li>Not all strings are user-visible, and it's non-trivial to spearate them, and keep that separation in place (but it is <em>possible</em>)</li> <li>Most, if not all, string externalization methods I've used involve significant text that will not pass a spell checker such as aspell/ispell (eg: theStrName="some string." and comments)</li> <li>Many spellcheckers (once again, aspell/ispell) don't handle many words out of the box (generally technical terms, proper nouns, or just 'new' terminology, like metadata).</li> </ul> <p>How do you incorporate something like this into your build procedures/test suites? It is not feasible to have someone manually spell check all the strings in an application each time they are changed -- and there is <em>no chance</em> that they will all be spelled correctly the first time.</p>
<p>We do it manually, if errors aren't picked up during testing then they're picked up by the QA team, or during localization by the translators, or during localization QA. Then we lodge a bug.</p> <p>Most of our developers are not native English speakers, so it's not an uncommon problem for us. The number that slip through the cracks is so small that this is a satisfactory solution for us.</p> <p>Nothing over a few hundred lines is ever 100% bug-free (well... maybe the odd piece of embedded code), just think of spelling mistakes as bugs and don't waste too much time on it.</p> <p>As soon as your application matures, over 90% of strings won't change between releases and it would be a reasonably trivial exercise to compare two versions of your resources, figure out what'ts new (check them first), what's changed/updated (check next) and what hasn't changed (no need to check these)</p> <p>So think of it more like I need to check ALL of these manually the first time, and I'm only going to have to check 10% of them next time. Now ask yourself if you still really need to automate spell checking.</p>
<p>First point, <em>please</em> don't put it into you build process. I would be a vengeful coder if I (meaning my computer) had to spell check all the content on the site every time I tried to debug or build a new feature. I don't even think this kind of operation belongs as a unit test (you're testing a human interface, not a computerised one).</p> <p>Second point, don't write a script. You're going to have so many false positives fall through the cracks that people will stop reading the reports and you are no better off than when you started.</p> <p>Third point, this is probably most easily solved by having humans do it: QA team, copy writers, beta testers, translators, etc. All the big sites with internationalised content that I've built had the same process: we took the copy from the copy writers, sent it to the translating service/agency, put it into the persistence layer, and deployed it. Testers (QA, developers, PMs, designers, etc.) would find spelling or grammatical mistakes and lodge bug reports. There is just too much red tape and pairs of eyes for <em>that</em> many spelling/grammar errors to slip through.</p> <p>Fourth point, there will always be spelling and grammar mistakes on your page. Even major newspaper web sites haven't gotten around this and they have whole office buildings filled with editors.</p>
6,410
<p>As kind of a followup to <a href="https://stackoverflow.com/questions/210446/what-is-the-best-way-for-a-client-app-to-find-a-server-on-a-local-network-in-c">this question</a> I've gotten a solution working on my local machine, but not on a machine on the network.</p> <p>I don't know too much about sockets other than that basics, so bear with me. The goal is for a client to look for a server on a local network, and this is the result of some cut/paste/edit code. </p> <p>This is the client code:</p> <pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294); byte[] data = new byte[1024]; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10); string welcome = "What's your IP?"; data = Encoding.ASCII.GetBytes(welcome); client.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint server = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)server; data = new byte[1024]; int recv = client.ReceiveFrom(data, ref tmpRemote); this.IP.Text = ((IPEndPoint)tmpRemote).Address.ToString(); //set textbox this.Port.Text = Encoding.ASCII.GetString(data, 0, recv); //set textbox client.Close(); } </code></pre> <p>This is the server code:</p> <pre><code>int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10294); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any,IPAddress.Parse("127.0.0.1"))); while (true) { Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)(sender); data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref tmpRemote); Console.WriteLine("Message received from {0}:", tmpRemote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "7010"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote); } </code></pre> <p>It works find on my local machine (both server and client) but when I try another machine on the same network I get "An existing connection was forcibly closed by the remote host"</p> <p>I realize I need to add a lot of try/catch but I'm just trying to get a handle on how this works first.</p>
<p>I have to start by saying that I know nothing about C#, but...</p> <p>Looking at the definition of the <code>ipep</code> in the client code, it looks like you're trying to send your data to yourself, rather than broadcast it (as has been suggested in your other question). The thing that caught my attention was that "127.0.0.1" is the address of "localhost".</p> <p>That would explain why it works nicely when you're running both the client and server on the one machine, as it <em>will</em> be sending to itself.</p> <p>I would expect that correct endpoint would be for a broadcast address (eg. "255.255.255.255") - although you could also choose the broadcast address of the local network that you're on, depending on how widely you wish to broadcast.</p>
<pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294); </code></pre> <p>Should become:</p> <pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 10294); </code></pre> <p>And</p> <pre><code>newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse("127.0.0.1"))); </code></pre> <p>Should Become</p> <pre><code>newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse("255.255.255.255"))); </code></pre> <p>I think.</p> <p>OK, this doesn't work, so something's still wrong.</p>
26,307
<p>I have a <code>TextCtrl</code> in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?</p>
<p>Realize that most fonts are proportional, which means that each character may take a different width. WWW and lll are both 3 characters, but they will require vastly different sizes of text box. Some fonts, such as Courier, are designed to be fixed width and will not have this problem. Unfortunately you may not have any control over which font is selected in the text box.</p> <p>If you still want to try this, the key is to get the width of a character in pixels, multiply it by the number of characters, then add some padding for the borders around the characters. You may find this to be a good starting point:</p> <p><a href="http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents" rel="nofollow noreferrer">http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents</a></p> <p>or, as litb suggests:</p> <p><a href="http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent" rel="nofollow noreferrer">http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent</a></p>
<p>There doesn't seem to be a way. You can, however, use <code>wxWindow::GetTextExtent</code>. This is C++ code, but can be easily adapted to wxPython:</p> <pre><code>int x, y; textCtrl-&gt;GetTextExtent(wxT("T"), &amp;x, &amp;y); textCtrl-&gt;SetMinSize(wxSize(x * N + 10, -1)); textCtrl-&gt;SetMaxSize(wxSize(x * N + 10, -1)); /* re-layout the children*/ this-&gt;Layout(); /* alternative to Layout, will resize the parent to fit around the new * size of the text control. */ this-&gt;GetSizer()-&gt;SetSizeHints(this); this-&gt;Fit(); </code></pre> <p>This is, you take the size of a reasonable width character (fonts may have variable width characters) and multiply it properly, adding some small value to account for native padding (say, 10px).</p>
43,897
<p>The vim * star / asterisk search (:help star) is a great feature which lets you find the next occurrence of the word the cursor is over. Unfortunately it treats dollar-prefixes as part of the string, so if I press * while over the "SearchTerm" in the class name it finds "SearchTerm" in the comment, and "$this->SearchTerm", but not "$SearchTerm":</p> <pre><code>class SearchTerm { /* do something with SearchTerm */ var $SearchTerm; function DoStuff() { return $this-&gt;SearchTerm; } } </code></pre> <p>Is there a way of telling star search to ignore the $-prefix?</p> <p><strong>Just to expand on <a href="https://stackoverflow.com/users/4993/haes]">Haes</a> answer:</strong></p> <p>I needed to remove $ from iskeyword</p> <pre><code>:set iskeyword # iskeyword=@,48-57,_,192-255,$ :set iskeyword-=$ # remove the $ as an acceptable word character </code></pre>
<p>Actually using vim 7.2 on Mac, star search exactly works as you would like it to do.</p> <p>EDIT: Check what your 'iskeyword' (:set iskeyword) is set to because star search is based on this option to find the word search term.</p> <p>Alternatively, you could could use 'g*' (:help gstar) to get a partial search for the word the cursor is over.</p> <p>Hope this helps somehow.</p>
<p>You should be able to escape the $ by placing a backslash before it: \$</p>
38,305
<p>Where do you store <em>user-specific</em> and <em>machine-specific</em> <strong>runtime</strong> configuration data for J2SE application?</p> <p>(For example, <em>C:\Users\USERNAME\AppData\Roaming&lt;/em&gt; on Windows and /home/username</em> on Unix)</p> <p>How do you get these locations in the filesystem in platform-independent way?</p>
<p>That depends on your kind of J2SE Application:</p> <ul> <li>J2SE executable JAR file (very simple): use <a href="http://www.mindspring.com/~mgrand/java-system-properties.htm" rel="noreferrer">user.home System property</a> to find home-dir. Then make a subdir accordingly (like e.g. PGP, SVN, ... do)</li> <li>Java Web Start provides very nice included methods to safe properties. Always user-specific</li> <li>Finally Eclipse RCP: There you have the notion of the workspace (also derived from user.home) for users and configuration (not totally sure how to access that tricky in Vista) for computer wide usage</li> </ul> <p>All these approaches are, when used with care -- use correct <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#separator" rel="noreferrer">separatorChar</a> -- OS neutral.</p>
<p>For user specific config, you could write a config file to the folder pointed to by the "user.home" system property. Would only work on that machine of course.</p>
23,612
<p>I have the following code:</p> <pre><code>&lt;script type="text/javascript"&gt; function SubmitForm() { form1.submit(); } function ShowResponse() { } &lt;/script&gt; . . . &lt;div&gt; &lt;a href="#" onclick="SubmitForm();"&gt;Click&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I want to capture the html response of <code>form1.submit</code>? How do I do this? Can I register any callback function to form1.submit method?</p>
<p>You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the <code>submit()</code> function doesn't actually return anything, it just sends the form data to the server.</p> <p>If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll <em>need</em> to use a library. <a href="http://www.jquery.com" rel="noreferrer">jQuery</a> is by far the most popular, and my personal favourite. There's a great plugin for jQuery called <a href="http://malsup.com/jquery/form/" rel="noreferrer">Form</a> which will do exactly what it sounds like you want.</p> <p>Here's how you'd use jQuery and that plugin:</p> <pre><code>$('#myForm') .ajaxForm({ url : 'myscript.php', // or whatever dataType : 'json', success : function (response) { alert("The server says: " + response); } }) ; </code></pre>
<p>you can do that without ajax. </p> <p>write your like below. </p> <p> .. .. .. </p> <p>and then in "action.php" </p> <p>then after frmLogin.submit();</p> <p>read variable $submit_return.. </p> <p>$submit_return contains return value. </p> <p>good luck. </p>
49,004
<p>We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.</p> <p>Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior.</p>
<p>When you say lock up, do you mean VS is actually hung, or do the tests not run?</p> <p>The easiest way to track down what is going on would be to look at a dump of the hung process. If you are on Vista, just right-click on the process and choose to create a memory dump. If you are on Windows XP, and don't have the <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx" rel="nofollow noreferrer">Debugging Tools for Windows</a> installed, you can get a memory dump using ntsd.exe. You'll need the process ID, which you can get from Task Manager by adding the PID column to the Processes tab display.</p> <p>Once you have that, run the following commands:</p> <pre><code>ntsd -p &lt;PID&gt; .dump C:\mydump.dmp </code></pre> <p>You can then either inspect that dump using <a href="http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx" rel="nofollow noreferrer">WinDBG and SOS</a> or if you can post the dump somewhere I'd be happy to take a look at it.</p> <p>In any case, you'll want to likely take two dumps about a minute apart. That way if you do things like !runaway you can see which threads are working which will help you track down why it is hanging.</p> <p>One other question - are you on VS2008 SP1?</p>
<p>When you say lock up, do you mean VS is actually hung, or do the tests not run?</p> <p>The easiest way to track down what is going on would be to look at a dump of the hung process. If you are on Vista, just right-click on the process and choose to create a memory dump. If you are on Windows XP, and don't have the <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx" rel="nofollow noreferrer">Debugging Tools for Windows</a> installed, you can get a memory dump using ntsd.exe. You'll need the process ID, which you can get from Task Manager by adding the PID column to the Processes tab display.</p> <p>Once you have that, run the following commands:</p> <pre><code>ntsd -p &lt;PID&gt; .dump C:\mydump.dmp </code></pre> <p>You can then either inspect that dump using <a href="http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx" rel="nofollow noreferrer">WinDBG and SOS</a> or if you can post the dump somewhere I'd be happy to take a look at it.</p> <p>In any case, you'll want to likely take two dumps about a minute apart. That way if you do things like !runaway you can see which threads are working which will help you track down why it is hanging.</p> <p>One other question - are you on VS2008 SP1?</p>
7,351
<p>Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction?</p> <p>We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/ms940016.aspx" rel="nofollow noreferrer">SetCursor</a>/<a href="http://msdn.microsoft.com/en-us/library/aa453410.aspx" rel="nofollow noreferrer">LoadCursor</a>/<a href="http://msdn.microsoft.com/en-us/library/aa453730.aspx" rel="nofollow noreferrer">ShowCursor</a> APIs, like this:</p> <pre><code>SetCursor(LoadCursor(NULL, IDC_WAIT)); // my code ShowCursor(FALSE); </code></pre>
<p>From: <a href="http://mobiledeveloper.wordpress.com/2006/07/05/wait-cursor/" rel="nofollow noreferrer">http://mobiledeveloper.wordpress.com/2006/07/05/wait-cursor/</a></p> <p>Have a look at Cursor.Current = Cursors.WaitCursor;</p> <pre><code>try { Cursor.Current = Cursors.WaitCursor; //Do something time consuming… } finally { Cursor.Current = Cursors.Default; } </code></pre>
30,138
<p>Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session.</p> <p>I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible.</p> <p>So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts?</p>
<p><strong>Right answer</strong>: memcached . Fast, clean, supports multiple processes, integrates <strong>very</strong> cleanly with Rails these days. Not even that bad to set up, but it is one more thing to keep running.</p> <p><strong>90% Answer</strong>: There are probably multiple Rails processes running around -- one for each Mongrel you have, for example. Depending on the specifics of your caching needs, its quite possible that having one cache per Mongrel isn't the worst thing in the world. For example, supposing you were caching the results of a long-running query which </p> <ul> <li>gets fresh data every 8 hours</li> <li>is used every page load, 20,000 times a day</li> <li>needs to be accessed in 4 processes (Mongrels)</li> </ul> <p>then you can drop that 20,000 requests down to 12 with about a single line of code</p> <pre><code>@@arbitrary_name ||= Model.find_by_stupidly_long_query(param) </code></pre> <p>The double at-mark, a Ruby symbol you might not be familiar with, is a global variable. ||= is the commonly used Ruby idiom to execute the assignment if and only if the variable is currently nil or otherwise evaluates to false. It will stay good until you explicitly empty it OR until the process stops, for any reason -- server restart, explicitly killed, what have you. </p> <p>And after you go down from 20k calculations a day to 12 in about 15 seconds (OK, two minutes -- you need to wrap it in a trivial if block which stores the cache update time in a different global), you might find that there is no need to spend additional engineering assets on getting it down to 4 a day.</p> <p>I actually use this in one of my production sites, for caching a few expensive queries which literally only need to be evaluated once in the life of the process (i.e. they change only at deployment time -- I suppose I could precalculate the results and write them to disk or DB but why do that when SQL can do the work for me). </p> <p>You don't get any magic expiry syntax, reliability is pretty slim, and it can't be shared across processes -- but its 90% of what you need in a line of code.</p>
<p>@p3t0r- is right,MemCached is probably the best option, but you could also use the sqlite database that comes with Rails. That won't work over multiple machines though, where MemCached will. Also, sqlite will persist to disk, though I think you can set it up not to if you want. Rails itself has no application-scoped storage since it's being run as one-process-per-request-handler so it has no shared memory space like ASP.NET or a Java server would.</p>
13,423
<p>I read about this ages ago but never tried it now I can't remember if this is possible or not. Is it possible to extend a class from two parents on php5 e.g.</p> <p>class_d extends class_c and class_b</p> <p>moreover can you do this if class_c and class_b are themselves extended from class_a ... so you get something like this</p> <pre><code> class_a class_b class_c class_d </code></pre>
<p>No. </p> <p>The best way is probably what you suggested: add a getFoo() method to your inner class.</p>
<p>yes:</p> <pre><code>public class Foo { public class Bar { public Foo getMyFoo() { return Foo.this; } } public Foo foo(Bar bar) { return bar.getMyFoo(); } public static void main(String[] arguments) { Foo foo1=new Foo(); Bar bar1=foo1.new Bar(); Foo foo=(new Foo()).foo(bar1); System.out.println(foo==foo1); } } </code></pre>
39,907
<p>I am progamatically creating a SharePoint site using </p> <pre><code>SPWeb spWeb = spSite.AllWebs.Add(...); </code></pre> <p>What code do I need run to set the spWeb to turn off the "Show pages in navigation" option?</p> <p><strong>Answer:</strong></p> <pre><code>publishingWeb.IncludePagesInNavigation = false; </code></pre>
<p>Wasn't sure myself but I was able to locate <a href="http://msdn.microsoft.com/en-us/magazine/cc507633.aspx" rel="noreferrer">this</a>:</p> <blockquote> <p>Modifying navigation is another common branding task since it affects what users can see and how they can proceed through a site hierarchy. The Microsoft.SharePoint.Publishing namespace exposes several classes that target the Publishing site infrastructure, such as PublishingWeb and PublishingPage. Using these classes, we can easily modify navigation for each site. If you want a child Web to display as a root level site in global navigation, first turn off inheritance from the parent site, like so:</p> </blockquote> <pre><code>publishingWeb.InheritGlobalNavigation = false; </code></pre> <blockquote> <p>You might also want to hide all site pages from global navigation. Setting IncludePagesInNavigation to false hides all pages in the site, regardless of whether the PublishingPage.IncludeInGlobalNavigation property is set to true</p> </blockquote> <pre><code>// do not show pages in navigation publishingWeb.IncludePagesInNavigation = false; </code></pre> <blockquote> <p>If you are dealing with default sites that don't inherit from PublishingWeb, it's still possible to hide these sites from the global navigation bar. For example, if you create a site collection using the collaboration portal template and want to exclude the News site from global navigation, add that site to the __GlobalNavigationExcludes property of the site:</p> </blockquote> <pre><code>string globalNavExcludes = String.Empty; SPWeb webSite = MSDNSiteCollection.RootWeb; // _GlobalNavigationExcludes property contains a delimited string of // GUIDs identifying the Id of each site to be excluded from global // navigation if (webSite.AllProperties.ContainsKey("__GlobalNavigationExcludes")) { globalNavExcludes = webSite.AllProperties["__GlobalNavigationExcludes"].ToString(); } SPWeb newsSite = MSDNSiteCollection.AllWebs["News"]; // string is delimited "{GUID};{GUID};", // use format code B to convert to string globalNavExcludes += String.Concat(currentWeb.ID.ToString("B"), ";"); webSite.AllProperties["__GlobalNavigationExcludes"] = globalNavExcludes; webSite.Update(); </code></pre> <blockquote> <p>Adding navigation nodes directly to an SPNavigationNodeCollection is a good way to display only the nodes you want as well as to group nodes and links to external sites. Figure 10 shows how to add an internal link, external link, and a heading to the global navigation bar. This example addresses some of the properties of the SPNavigation class that affect whether the link opens in a new window and how to handle empty URLs.</p> </blockquote>
<p>For SP 2010 use below...</p> <p>publishingWeb.Navigation.GlobalIncludePages = false;</p>
28,236
<p>In my Rails controller, I'm creating multiple instances of the same model class. I want to add some RSpec expectations so I can test that it is creating the correct number with the correct parameters. So, here's what I have in my spec:</p> <pre> Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => @user.id, :position_id => 1, :is_leader => true) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "2222", :position_id => 2) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "3333", :position_id => 3) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "4444", :position_id => 4) </pre> <p>This is causing problems because it seems that the Bandmate class can only have 1 "should_receive" expectation set on it. So, when I run the example, I get the following error:</p> <pre> Spec::Mocks::MockExpectationError in 'BandsController should create all the bandmates when created' Mock 'Class' expected :create with ({:band_id=>1014, :user_id=>999, :position_id=>1, :is_leader=>true}) but received it with ({:band_id=>1014, :user_id=>"2222", :position_id=>"2"}) </pre> <p>Those are the correct parameters for the second call to create, but RSpec is testing against the wrong parameters.</p> <p>Does anyone know how I can set up my should_receive expectations to allow multiple different calls?</p>
<p>Multiple expectations are not a problem at all. What you're running into are ordering problems, given your specific args on unordered expectations. Check <a href="http://rspec.info/documentation/3.3/rspec-mocks/#Ordering" rel="noreferrer">this page</a> for details on ordering expectations.</p> <p>The short story is that you should add <code>.ordered</code> to the end of each of your expectations.</p>
<p><a href="http://rspec.rubyforge.org/rspec/1.1.9/classes/Spec/Mocks.html" rel="nofollow noreferrer">Mock Receive Counts</a></p> <p>my_mock.should_receive(:sym).once<br> my_mock.should_receive(:sym).twice<br> my_mock.should_receive(:sym).exactly(n).times<br> my_mock.should_receive(:sym).at_least(:once)<br> my_mock.should_receive(:sym).at_least(:twice)<br> my_mock.should_receive(:sym).at_least(n).times<br> my_mock.should_receive(:sym).at_most(:once)<br> my_mock.should_receive(:sym).at_most(:twice)<br> my_mock.should_receive(:sym).at_most(n).times<br> my_mock.should_receive(:sym).any_number_of_times </p> <p>Works for rspec 2.5 too.</p>
30,246
<p>I'm using ASP.NET Web Forms for blog style comments. </p> <p>Edit 1: This looks way more complicated then I first thought. How do you filter the src?<br> I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?</p>
<p>If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like:</p> <pre><code>Look at this! [http://a.b.c/m.jpg] </code></pre> <p>Which would get converted to</p> <pre><code>Look at this! &lt;img src="http://a.b.c/m.jpg" /&gt; </code></pre> <p>You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe</p> <pre><code>Look at this! [javascript:alert('pwned!')] </code></pre>
<p>If you end up going with a non-HTML format (which makes things easier b/c you can literally escape all HTML), use a standard syntax like <a href="http://daringfireball.net/projects/markdown/" rel="nofollow noreferrer">markdown</a>. The <a href="http://daringfireball.net/projects/markdown/syntax#img" rel="nofollow noreferrer">markdown image syntax</a> is <code>![alt text](/path/to/image.jpg)</code></p> <p>There are others also, like <a href="http://www.textism.com/tools/textile/" rel="nofollow noreferrer">Textile</a>. Its syntax for images is <code>!imageurl!</code></p>
13,536
<p>I've been looking around for a Java API that can communicate with serial devices on Windows/Win32 but many of the APIs I've checked out are either for Linux, too outdated, or just had bad critics.</p> <p>Can someone recommend one to me that they've tried or knows about that is easy to implement on Windows XP?</p>
<p>I started looking for the same thing couple weeks ago, and I've been very happy with the multi-platform <a href="http://users.frii.com/jarvi/rxtx/" rel="noreferrer">RXTX</a> library so far. Works with any Windows, Linux and OS X. Has a very clean, easy to understand API.</p> <p>edit: RXTX is also open source.</p>
<p>Java is notorious for its flaky serial I/O support. At a previous job, we tried both RXTX and SerialIO for an application that streamed data at 56kbps from a Teknic servo controller, and found them to gobble up the CPU quite a bit. Perhaps for apps that don't require continuous streaming from a serial port, both of these libraries are good, but we didn't feel that streaming I/O from a serial port should be eating a sustained 15-30% of the CPU on the machine when it is much needed for other threads in the JVM that need to be responsive.</p> <p>Instead, we created a server in C++ that would read the stream of data from the serial port on the servo, transform/packetize it and send it to our Java app in XML over a socket connection. The CPU load on the serial I/O server in C++? Barely creeping into 1% at its worst.</p> <p>There are certain things Java does well - serial I/O, in my opinion, isn't one of them, depending on the type of application... </p> <p>Ultimately, you should take even what I said with a grain of salt, and try both, RXTX and SerialIO (which is dirt cheap, like $50 or so for the java version) and if they meet your needs, go with it. Personally, I'd stick with SerialIO because it is supported and actively worked on. RXTX, not so much.</p>
33,098
<p>How can I rename a Virtual Directory (or Web Application) in IIS 6.0/7.0 using VBScript?</p>
<p>Do you want to rename it in IIS, or change the virtual path? adsutil can do either. It should be installed in c:\inetpub\AdminScripts</p> <p>adsutil.vbs SET W3SVC/<em>svcnum</em>/Root/<em>AppName</em>/AppFriendlyName "New Friendly Name"<br /> adsutil.vbs SET W3SVC/<em>svcnum</em>/Root/<em>AppName</em>/AppRoot "New Application Path"</p>
<p>I assume you want to use a local shell script.</p> <p>Try PowerShell, I think IIS7 has introduced <a href="http://learn.iis.net/page.aspx/98/using-scripts-to-automate-management/" rel="nofollow noreferrer">new administration tools</a> that look quite powerful. I <strong>think</strong> you could also use these scripts to manage IIS remotely via WMI.</p> <p>It shouldn't be any more complicated then VBScript.</p> <p>Another way would be to use VBScript to edit the IIS configuration files or create an <a href="http://learn.iis.net/page.aspx/165/how-to-use-microsoftwebadministration/" rel="nofollow noreferrer">administration object</a>, but that doesn't really seem to be the way to go about it.</p> <p>Hopefully this helps.</p>
33,184
<p>How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:</p> <pre><code>//MySQL SELECT foo FROM table LIMIT 10, 10 </code></pre> <p>But I can't find a way to define offset.</p>
<p>Tested query in PSQL:</p> <pre><code>select top n * from tablename where id not in( select top k id from tablename ) </code></pre> <p>for all n = no.of records u need to fetch at a time. and k = multiples of n(eg. n=5; k=0,5,10,15,....)</p>
<p>I face this problem in MS Sql too... no Limit or rownumber functions. What I do is insert the keys for my final query result (or sometimes the entire list of fields) into a temp table with an identity column... then I delete from the temp table everything outside the range I want... then use a join against the keys and the original table, to bring back the items I want. This works if you have a nice unique key - if you don't, well... that's a design problem in itself.</p> <p>Alternative with slightly better performance is to skip the deleting step and just use the row numbers in your final join. Another performance improvement is to use the TOP operator so that at the very least, you don't have to grab the stuff past the end of what you want.</p> <p>So... in pseudo-code... to grab items 80-89...</p> <pre><code>create table #keys (rownum int identity(1,1), key varchar(10)) insert #keys (key) select TOP 89 key from myTable ORDER BY whatever delete #keys where rownumber &lt; 80 select &lt;columns&gt; from #keys join myTable on #keys.key = myTable.key </code></pre>
14,977
<p>I have tried, 'PreviousPage', 'PreviousPage.IsCrossPagePostBack' 'Page.previousPage', page.title</p> <p>It causes the client to stop rendering the page after this line.</p> <p>simple example</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { response.write("I can see this"); string test = PreviousPage.IsCrossPagePostBack.toString(); //Any page call Causes client rendering to freeze response.write("But i cant see this"); System.Windows.Forms.MessageBox.Show("However i can see this,proving that the server is still running the code"); } </code></pre> <p>Anybody Please, any ideas? </p>
<p>ANSWER</p> <p>Well it ended up it was something stupid. code smell over.</p> <p>The button i was using to fire the PostBack had a handler that fired to redirect, i just deleted the handler, keeping the PostBackUrl setting and magic.</p>
<p>Have you checked PreviousPage for null?</p> <p>From <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx" rel="nofollow noreferrer">msdn</a>:</p> <blockquote> <p>The PreviousPage property is a null reference (Nothing in Visual Basic) when the user requests that page directly from the server.</p> </blockquote> <p>Also - <code>MessageBox</code> in a web form, <em>not</em> a great idea... perhaps use the inbuilt <a href="http://msdn.microsoft.com/en-us/library/bb386420.aspx" rel="nofollow noreferrer">trace.axd</a></p>
37,724
<p>I am seeing a strange problem:</p> <p>I have a linux machine, installed JDK1.6 on that machine, and some business went on, and some days later had to change the IP address of the machine. and now after some months... i am trying to get some spring application to work... and it seems the RMI Server is starting at my old ip address...</p> <pre><code> 21:12:45,412 DEBUG [org.springframework.remoting.rmi.RmiServiceExporter] RMI registry access threw exception java.rmi.ConnectIOException: Exception creating connection to: 192.168.13.55; nested exception is: java.net.SocketException: Network is unreachable at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:614) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184) at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322) at sun.rmi.registry.RegistryImpl_Stub.list(Unknown Source) at org.springframework.remoting.rmi.RmiServiceExporter.testRegistry(RmiServiceExporter.java:411) at org.springframework.remoting.rmi.RmiServiceExporter.getRegistry(RmiServiceExporter.java:391) </code></pre> <p>can somone explain the process or shed some light on what is going on here, or might be going on here.</p>
<p>ok, thanks for the response... i really appreciate that...but i was probably too drunk to notice the entries in my /etc/hosts file were binding my hostname to the old IP address...so as soon as i removed that...things worked like a charm.</p>
<p>Have you checked your spring config to ensure you don't have an old reference somewhere?</p>
36,771
<p>I'm using this to check for the availability of a URL:</p> <pre><code>$fp = fsockopen($url, 443, $errno, $errstr); </code></pre> <p>and I get this error back...</p> <p><strong>Warning: fsockopen() [function.fsockopen]: unable to connect to <a href="https://example.com/soapserver.php:443" rel="noreferrer">https://example.com/soapserver.php:443</a> (Unable to find the socket transport "https" - did you forget to enable it when you configured PHP?) in C:\Home etc etc....</strong></p> <p>I'm using an IIS server btw,( no its not my doing! ) so I think its something to do with not having open-ssl, but I'm not sure. Can anyone help please? </p> <p>I did a phpinfo() and I do have ssl, but on IMAP and cURL, thats all.</p> <p>Any ideas?</p>
<p>Uncomment the line: <code>extension=php_openssl.dll</code> in <code>php.ini</code></p>
<p>Check curl installed or not for php. if it is not installed install the curl. for windows Uncomment the line: extension=php_openssl.dll in php.ini, for ubuntu sudo apt-get install php-curl</p>
49,589
<p>I'm trying to build a similar 'slider' as demoed here <a href="http://ui.jquery.com/repository/real-world/product-slider/" rel="nofollow noreferrer">http://ui.jquery.com/repository/real-world/product-slider/</a> but I'm trying to use interior divs inside of the list items (<code>&lt;li&gt;</code>). it seems as if this demo breaks if you're not using an image or block element (<code>&lt;p&gt;</code>,<code>&lt;div&gt;</code>,etc.)</p> <p>Anyone have any quick solutions to this? I basically want to use text and possibly images inside of a <code>&lt;div&gt;</code> instead of using images.</p> <p>I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight? Any ideas?</p>
<p>I think I <em>sort of</em> have a working example of what you're trying to do, but there are a couple issues.</p> <p>Using the example you posted as a base, you can replace the HTML markup of the LI's in a UL to be DIV's in a container DIV. For example:</p> <pre><code> &lt;div class="sliderGallery"&gt; &lt;div class="div-that-gets-cropped"&gt; &lt;div class="text-and-images-chunk"&gt;Some text!&lt;br /&gt;&lt;img class="pb-airportexpress" src="slider-gallery_files/pb_airport_express.jpg" /&gt;&lt;/div&gt; &lt;div class="text-and-images-chunk"&gt;Some text!&lt;br /&gt;&lt;img src="slider-gallery_files/pb_airport_extreme.jpg" /&gt;&lt;/div&gt; &lt;div class="text-and-images-chunk"&gt;Some text!&lt;br /&gt;&lt;img src="slider-gallery_files/pb_timecapsule_20080115.jpg" /&gt;&lt;/div&gt; ... &lt;/div&gt; </code></pre> <p>Then you modify the jQuery code in the page to target that container DIV instead of the UL:</p> <pre><code> window.onload = function () { var container = $('div.sliderGallery'); var divThatGetsCropped = $('div.div-that-gets-cropped', container); var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth(); $('.slider', container).slider({ minValue: 0, maxValue: itemsWidth, handle: '.handle', stop: function (event, ui) { divThatGetsCropped.animate({'left' : ui.value * -1}, 500); }, slide: function (event, ui) { divThatGetsCropped.css('left', ui.value * -1); } }); }; </code></pre> <p>Then you have some non-trivial CSS changes to make... The original example relied on the LI's being styled to display: inline, inside of a container with overflow hidden. It's going to be a headache to try to get everything to show up correctly if you just style these "text-and-images-chunk" DIV's to be displayed inline. You probably want to float them all.</p> <p><strong>BUT</strong>, floated elements won't play very nicely with the container "div-that-gets-cropped" DIV because of the way it's being "revealed" by the "sliderGallery" DIV (at least that's what I'm experiencing in Firefox 3.03). I got around this by setting a really big width for the "div-that-gets-cropped" DIV (10000 px):</p> <pre><code> .sliderGallery div.div-that-gets-cropped { position: absolute; list-style: none; overflow: none; white-space: nowrap; padding: 0; margin: 0; width: 10000px; } .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk { float: left; margin-right: 24px; } </code></pre> <p>And you'll have to tweak the "left" values for .slider-lbl1, .slider-lbl2 to match up whatever the widths end up being (this might be tricky if the size of your text ends up changing the width of the "text-and-images-chunk" elements).</p> <p>The one issue I noticed is that when you have the images in a block-level element, there isn't a good way to get them to "hug" the bottom, as they do in the example using inline. You might be able to get this working by playing around with the positioning of the elements (I couldn't), but hopefully this won't be a big deal in your specific usage.</p> <p>All of that said, jCarousel seems like it's <em>intended for exactly what you're doing</em>, even if it does add a little code bulk.</p>
<p>Check out the jCarousel Lite plugin. I've found it to be very useful and easy to configure.</p> <p><a href="http://www.gmarwaha.com/jquery/jcarousellite/index.php?#demo" rel="nofollow noreferrer">http://www.gmarwaha.com/jquery/jcarousellite/index.php?#demo</a></p>
23,255
<p>How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to be in UTC.</p>
<p>Use timegm() instead of mktime()</p>
<p>This is really a comment with code to address the answer by Leo Accend: Try the following:</p> <pre><code>#include &lt;time.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* * A bit of a hack that lets you pull DST from your Linux box */ time_t timegm( struct tm *tm ) { // From Leo's post, above time_t t = mktime( tm ); return t + localtime( &amp;t )-&gt;tm_gmtoff; } main() { struct timespec tspec = {0}; struct tm tm_struct = {0}; if (gettimeofday(&amp;tspec, NULL) == 0) // clock_gettime() is better but not always avail { tzset(); // Not guaranteed to be called during gmtime_r; acquire timezone info if (gmtime_r(&amp;(tspec.tv_sec), &amp;tm_struct) == &amp;tm_struct) { printf("time represented by original utc time_t: %s\n", asctime(&amp;tm_struct)); // Go backwards from the tm_struct to a time, to pull DST offset. time_t newtime = timegm (&amp;tm_struct); if (newtime != tspec.tv_sec) // DST offset detected { printf("time represented by new time_t: %s\n", asctime(&amp;tm_struct)); double diff = difftime(newtime, tspec.tv_sec); printf("DST offset is %g (%f hours)\n", diff, diff / 3600); time_t intdiff = (time_t) diff; printf("This amounts to %s\n", asctime(gmtime(&amp;intdiff))); } } } exit(0); } </code></pre>
35,882
<p>Is the <a href="http://www.digitalmars.com/d/" rel="noreferrer">D language</a> a credible alternative to Java and C++? What will it take to become a credible alternative? Should I bother learning it? Does it deserve evangelizing?</p> <p>The main reason I ask is that with the new C++ standard (c++0x) almost here, it's clear to me that the language has gone well past the point of no return with respect to anyone ever understanding it. I know that C/C++ will never die but at some point we need to move on. Even COBOL had its day and Java has in many respects undone C++. So what's next? Does D fill the bill?</p>
<p>What determines the success and popularity of a programming language for real-world software development is only partially related to the quality of the language itself. As a pure language, D arguably has many advantages over C++ and Java. At the very least it is a credible alternative as a pure language, all other things being equal.</p> <p>However, other things matter for software development - almost more than the language itself: portability (how many platforms does it run on), debugger support, IDE support, standard library quality, dynamic library support, bindings for common APIs, documentation, the developer community, momentum, and commercial support, just to name a few. In every one of those regards, D is hopelessly behind Java, C++, and C#. In fact, I'd argue it's even behind so-called "scripting" languages like Python, Perl, PHP, Ruby, and even JavaScript in these regards.</p> <p>To be blunt, you simply can't build a large-scale, cross-platform application using D. With an immature standard library, <s>no support in any modern IDEs</s> (there are plugins for both Visual Studio and Xamarin Studio/MonoDevelop), limited dynamic/shared library support, and few bindings to other languages, D is simply not an option today.</p> <p>If you like what you see of D, by all means, learn it - it shouldn't take long if you already know Java and C++. I don't think evangelism would be helpful - at this point if D is going to succeed, what it really needs is more people quietly using it and addressing its major shortcomings like standard library and IDE support.</p> <p>Finally, as for C++, while most agree the language is too complex, thousands of companies are successfully using C++ as part of a healthy mix of languages by allowing only a smaller, well-defined subset of the language. It's still hard to beat C++ when both raw performance and small memory usage are required.</p>
<p>Works great for my own pet projects. I'd use it for employers' projects but for not knowing how hard it would be for them to find someone to take over the source after i move on. There are no technical reasons to avoid it, at least on the supported platforms. (knock on wood)</p>
17,678
<p>How would you make the contents of Flex RIA applications accessible to Google, so that Google can index the content and shows links to the right items in your Flex RIA. Consider a online shop, created in Flex, where the offered items shall be indexed by Google. Then a link on Google should open the corresponding product in the RIA.</p>
<p>Currently the best technique for making an RIA indexable by search engines is called <a href="http://en.wikipedia.org/wiki/Progressive_enhancement" rel="nofollow noreferrer">progressive enhancement</a> (or graceful degradation, depending on which way you see it). Basically you create a simple HTML version of the application using the same data as the application loads. This version should be dynamically generated by some kind of backend server technology. This HTML version can be indexed by Google, but each page also contains a check that determines if the visitor is capable of viewing the rich version, and if so replaces the HTML content with the Flash, Flex or Silverlight application, preferably in such a way that the application starts in a state where it shows the same data as the current page. "Replaces" can mean that it just embeds the application on top of the HTML content, or that it redirects the user to a page that embeds it. The former solution is preferable, because the latter can be considered <a href="http://en.wikipedia.org/wiki/Cloaking" rel="nofollow noreferrer">cloaking</a>.</p> <p>One way of keeping the HTML and RIA versions of a shop synchronized is to decide on a URL scheme and make sure that RIA uses some kind of deep linking technique. If a visitor arrives to a specific item via a search engine, say <code>/items/345</code> the corresponding pseudo-URL in the RIA should be the same, so that you can embed the RIA on top of the page and set that URL as a parameter to make the RIA display that same page as soon as it has loaded.</p> <p>This summer, Google and Yahoo! announced that they would begin using a custom version of Flash Player to index Flash based applications by exploring them "in the same way that a person would". Now, two months later there is still no evidence that this is actually happening. <a href="http://blog.digitalbackcountry.com/?p=1617" rel="nofollow noreferrer">Ryan Stweart had to cancel his Flex SEO competition</a> because it became evident that no one could win. The problem seems to be that event though the technique may very well work (although I'm sceptical), the custom Flash Player needs some kind of network interface to be able to load any referenced resources, like XML data, other SWFs, etc., and <a href="http://blog.iconara.net/2008/07/27/why-google-isnt-indexing-dynamic-content-yet/" rel="nofollow noreferrer">this is currently not implemented by Google</a>. This means that for an application that loads all it's data dynamically, like say, all that I can think of, Googlebot will not actually see anything relevant. Yahoo! ignores SWF based content altogether.</p> <p>Oh, and it just so happens that I talk about Flex and SEO on <a href="http://www.theflexshow.com/blog/index.cfm/2008/9/10/The-Flex-Show-Episode-54" rel="nofollow noreferrer">the latest episode of the Flex show</a> =)</p>
<p>There is a massive thread available here:</p> <p><a href="http://tech.groups.yahoo.com/group/flexcoders/message/58926" rel="nofollow noreferrer">http://tech.groups.yahoo.com/group/flexcoders/message/58926</a></p> <p>But essentially, google already indexes .SWF files (you can test this out yourself by restricting search results to just .SWF files). It can search any text content within the SWF file.</p> <p>However, if the text information in your site comes from a database / web server. Then it won't be able to access this information easily.</p> <p>One example of getting this to work is using an XML file as your index page, then using an XSLT transform to render it using Flex. "Ted On Flex" has good information about this.</p> <p><a href="http://flex.org/consultants" rel="nofollow noreferrer">http://flex.org/consultants</a></p>
8,877
<p>I need to write test cases for my application. I've chosen NUnit. Please let me know how to add NUnit to my Visual Studio IDE. where can I download them?</p>
<p>Your question is a bit ambiguous.. </p> <ul> <li>Are you interested in learning nunit (In which case nunit.org would be the place to look along with some books on TDD/UnitTesting)</li> <li>If you're trying to integrate nunit with VisualStudio IDE, I'd go with the external executable approach listed as Option#1 <a href="http://www.dev102.com/2008/03/22/3-ways-to-run-nunit-from-visual-studio/" rel="noreferrer">here</a> or TestDriven.net Option#2</li> </ul>
<p>Best place to start would probably be: <a href="http://testdriven.net/" rel="noreferrer">http://testdriven.net/</a></p> <p>They have NUnit, and a host of other unit testing suites that can integrate with various versions of Visual Studio, as well as some documentation on them.</p>
23,906
<p>I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.</p> <p>The closest I have been able to manage is this:</p> <pre><code>If IsNull({ValuationReport.YestPrice}) Then 'N/A' Else ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2) </code></pre> <p>However this represents negative numbers using a negative sign, not parentheses. </p> <p>I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?</p>
<p>I think you are looking for <code>ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))</code></p> <p>You can use <code>CCur</code> to convert numbers or string to Curency formats. <code>CCur(number)</code> or <code>CCur(string)</code></p> <hr> <p>I think this may be what you are looking for,</p> <p><code>Replace (ToText(CCur({field})),"$" , "")</code> that will give the parentheses for negative numbers</p> <p>It is a little hacky, but I'm not sure CR is very kind in the ways of formatting</p>
<pre><code>if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then "nd" else totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00') </code></pre> <p>The above logic should be what you are looking for.</p>
19,702
<p>How can I create a Sidebar form in delphi.</p> <p>I try the <code>ScreenSnap</code> and <code>Align</code> properties but I need that the form stay visible even if the user maximize other forms, without been on top. Just like the windows sidebar do.</p> <p><strong>Update</strong>: From the comments: if a window is maximized, it maximizes next to the window, not in front of or behind.</p>
<p>What you're looking for is called an <em>AppBar</em>. Begin your research with the <a href="http://msdn.microsoft.com/en-us/library/bb762108.aspx" rel="noreferrer"><code>ShAppBarMessage</code></a> API function.</p>
<p>You can call a Windows API function to force your application to stay on top:</p> <pre><code>SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); </code></pre>
36,732
<p>I am creating a joomla plugin and want to load an array of images after the page has loaded. To do that, I'm currently using mootools.js to call myserver URL, obtain the JSON response and parse the response into javascript variables that represent each image url. It works great, but mootools.js is appropriately named since it is a real heffer in the size department. </p> <p>Is there a lightweight script out there that will make the ajax call and parse the JSON object? The smaller the better. </p>
<p>I just found a JSON parser, json2.js, at json.org that minifies down to about 3k. You basically do a standard HTTPRequest via AJAX and then pass the response text to the JSON parser to create the JSON object. </p> <p>Thanks for all the answers and I did track them all down. I couldn't get any of them small enough to compete with this approach, though. </p>
<p>Two suggestions:</p> <ol> <li>Find a library that breaks the functionality you need down into relatively small components. Then download only the components you need. YUI is nicely divided, but even those files can be somewhat larger than necessary. A smaller project that is based on YUI is Fork. Find this library at <a href="http://forkjavascript.org/" rel="nofollow noreferrer">http://forkjavascript.org</a></li> <li>Find the functionality you need in one of the open source libraries and refactor it into your own significantly smaller version.</li> </ol>
37,934
<p>May be my title is not clear. I am looking for some kind of version control on database tables, like subversion does on files, like wiki does.</p> <p>I want to trace the changes log. I want to extract and run the diff in reverse. (undo like a "svn merge -r 101:100"). I may need a indexed search on the history.</p> <p>I've read the "<a href="https://stackoverflow.com/questions/49755/design-pattern-for-undo-engine">Design Pattern for Undo Engine</a>", but it is related to "Patterns". Are there anything I could reuse without reinvent the wheel?</p> <p><strong>EDIT:</strong> For example, bank account transactions. I have column "balance"(and others) updated in table. a user will find a mistake by him 10 days later, and he will want to cancel/rollback the specific transaction, without changing others.</p> <p>How can I do it gracefully in the application level?</p>
<p>Martin Fowler covers the topic in <a href="http://martinfowler.com/eaaDev/timeNarrative.html" rel="nofollow noreferrer" title="Patterns for things that change with time">Patterns for things that change with time</a>. Still patterns and not an actual framework but he shows example data and how to use it.</p>
<p>Based on your comment to James Anderson, I would have the user interface write a new insert when cancelling a transaction. It would insert a new record into the table that had the same values as the cancelled transaction except the value would be a negative number instead of a positive number. If you have a structure that includes something to define the purpose of the transaction, I would make it say cancelled and the record number of the transaction it was cancelling.</p>
45,956
<p>Has anyone ever tried, or had any success at getting Wascana (Eclipse CDT + MinGW for Windows) to compile FFMPEG under Windows. Apparently it is possible, there is even a <a href="http://www.craigshaw.com/2007/07/25/BuildingFFMPEGUsingCDTForWindows.aspx" rel="nofollow noreferrer">tutorial at Craig Shaw's website</a> but I have not been able to make it work.</p> <p>I run ./configure on the FFMPEG source code then create a new project in Eclipse and point it at the source but it doesn't recognise it as a Makefile project. I think I need to create a builder which works with MinGW but my feeble attempts so far have been unsuccessful.</p>
<p>Hey, I can answer my own question! After a lot of fiddling around, I have come up with the procedure:</p> <p><em>NOTE: This is for Wascana 0.9.3 and a Sep 2008 SVN version of FFMPEG.</em></p> <p><strong>Prepare Environment</strong></p> <p>After installing Wascana, you'll need to update various MinGW and MSYS packages. Download and unpack the following (you can download them from the MinGW website):</p> <p>MSYS packages:</p> <ul> <li>bash-3.1</li> <li>coreutils-5.97</li> <li>m4-1.4.7</li> <li>make-3.81</li> </ul> <p>MinGW packages:</p> <ul> <li>w32api-3.12</li> <li>MinGW Runtime 3.15</li> </ul> <p><strong>Build</strong></p> <ol> <li>Unpack the FFMPEG source code and configure like so (do not compile it yet):</li> </ol> <p>./configure --enable-memalign-hack --disable-shared --enable-static --disable-mmx --disable-mmx2 --disable-optimizations --disable-stripping</p> <ol start="2"> <li>Launch Wascana/Eclipse and create a new C project.</li> <li>Do not select "Hello World" project, just select a Makefile project and select the MinGW toolchain.</li> <li>Set the project path to wherever your FFMPEG source code is.</li> <li>Click finish and the source should build itself!</li> </ol> <p><strong>Install</strong></p> <ol> <li>Right click the project and select Make Targets > Create.</li> <li>In the dialog, set both the Make Target and Target name to "install".</li> <li>Run the target you just created. This will install the FFMPEG libraries.</li> </ol> <p><strong>Execute and Debug</strong></p> <ol> <li>Open the Debug Dialog</li> <li>Right-click on "C/C++ Local Application" and choose "New"</li> <li>Fill in the project name and select the EXE you want to run (in my case, ffplay_g.exe)</li> <li>Go to the debugger tab and change the debugger to "MinGW gdb Debugger"</li> </ol> <p>I also had to make sure a copy of SDL.dll was in the ffmpeg directory.</p> <p>Phew, what an ordeal. That all worked for me, hopefully it will work for you too!</p>
<p>install last MSYS and MinGW Cf. <a href="http://ffmpeg.arrozcru.com/wiki/index.php?title=MSys_MinGW" rel="nofollow noreferrer">link text</a></p>
30,925
<p>As I understand it, the command to ignore the <em>content</em> of a directory using SVN is this:</p> <pre><code>svn propset svn:ignore "*" tmp/ </code></pre> <p>This should set the ignore property on the content of the <code>tmp</code> directory, right? In other words, the wildcard is set to be the ignore value on the tmp directory. Trouble is, here's what is happening on my Windows box:</p> <pre><code>&gt; svn propset svn:ignore "*" ./tmp property 'svn:ignore' set on 'app' property 'svn:ignore' set on 'config' property 'svn:ignore' set on 'db' property 'svn:ignore' set on 'doc' property 'svn:ignore' set on 'lib' property 'svn:ignore' set on 'log' property 'svn:ignore' set on 'nbproject' property 'svn:ignore' set on 'public' [etc...] </code></pre> <p>That's not right. Am I doing something wrong (or perhaps going insane), or is my svn on Windows broken?</p> <p><strong>Some notes:</strong></p> <ul> <li>The machine is running Windows Vista SP1</li> <li>Setting this property via Tortoise works perfectly.</li> <li>I'm using the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">Collabnet binaries for Windows</a>:</li> </ul> <blockquote> <p><code>> svn --version<br /> svn, version 1.5.2 (r32768)<br /> compiled Aug 28 2008, 19:05:34</code></p> </blockquote> <hr> <p><strong><em>Update:</em></strong> I've have just tried this on a Windows XP machine and it works as expected. So either this is a Vista specific issue, or there is a problem with my Vista configuration. Is anyone else able to reproduce this problem on Vista? I have just spotted that Vista isn't listed as one of the supported platforms on the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">CollabNet downloads page</a>.</p>
<p>The command <strong><em>should</em></strong> be working as you expect.</p> <p>The <code>*</code> is getting globbed, which it shouldn't be doing. So, you're running:<br> <code>svn propset svn:ignore [value] app config db doc lib log nbproject public ... tmp</code><br> (since app was the first folder affected, I'm guessing there's another folder before it).</p> <p>2 things you can try:</p> <ol> <li>Specify a list file: <code>svn propset svn:ignore tmp -F .svnignore</code></li> <li>Just specify the path: <code>svn propset svn:ignore tmp</code>. This should open your default text editor (if configured) to allow you to write and save the list.</li> </ol> <hr> <p><strong>Reply to comment</strong></p> <p>Since you're now attempting to correct the setting, <code>propedit</code> and <code>propdel</code> would work fine -- especially if you have other changes within the directory.</p> <p>But, if you don't have any other changes to worry about (check <code>svn st</code>), it'll be faster using <code>svn revert -R</code> and <code>svn propset</code>.</p>
<p>Try it without the trailing slash. Also, the tmp directory itself has to be added to the repository.</p>
19,491
<p>How do you calculate the Content-Length is a soap message? Is it the number of chars in the whole soap message?</p>
<p>Its the number of bytes, not the number of characters, so it will depend on the text encoding used.</p>
<p>Yes. Convert your XML message to a string and use the length of the string as Content-Length.</p> <p>(Assuming you are using eight-byte characters.)</p>
36,977
<p>I'm developing a kind of an exchange format between instances of an application so that user could save information to file and restore it later. The whole 'exchange format' is a single class that gets serialized and written to disk.</p> <p>How would you suggest to store graphical/sound information inside that class? I'd like to avoid just putting the files into it a .jar.</p>
<p>You might keep your resources stored in the class as byte[] arrays. Using ByteArrayInputStream and ByteArrayOutputStream you are able to wrap the arrays as streams and use them to store and retrieve resources.</p>
<p>** me **</p> <p>how about more details on your case? the "best" method usually depends on the particular application/use. does the image/sound come from files? from a stream? Is each instance of the class expected to store separate images? Or can an image be shared between different instances?</p> <p><strong>gsmd</strong></p> <blockquote> <p>images come from files, sounds come from a stream; there's actually a Set of items some of which may have an image attached; an image can't be shared</p> </blockquote> <hr> <p>What methods have you tried? I guess using the Serializable interface is the way to go. Here's <a href="http://java.sun.com/developer/technicalArticles/ALT/serialization/" rel="nofollow noreferrer">two</a> <a href="http://java.sun.com/developer/technicalArticles/Programming/serialization/" rel="nofollow noreferrer">articles</a> on the topic. </p> <p>Basically,</p> <ol> <li>implement the Serializable interface in your class</li> <li>mark members which shouldn't be saved in the file as transient (members which contain contextual data like file handles, socket connections ,etc).</li> <li><p>you have to customize how your image and sound classes write data using, but implementing:</p> <blockquote> <p>private void writeObject(ObjectOutputStream out) throws IOException;</p> <p>private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;</p> </blockquote></li> </ol>
25,010
<p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p> <pre><code>&gt;&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() &gt;&gt;&gt; obj.myPublicMethod() public method &gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' &gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] &gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>What's the deal?!</p> <p>I'll explain this a little for those who didn't quite get that.</p> <pre><code>&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() </code></pre> <p>I create a class with a public method and a private method and instantiate it.</p> <p>Next, I call its public method.</p> <pre><code>&gt;&gt;&gt; obj.myPublicMethod() public method </code></pre> <p>Next, I try and call its private method.</p> <pre><code>&gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' </code></pre> <p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <code>dir()</code> on the object reveals a new magical method that Python creates magically for all of your 'private' methods.</p> <pre><code>&gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] </code></pre> <p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p> <pre><code>&gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>So much for encapsulation, eh?</p> <p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
<p>The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __init__(self): ... self.__baz = 42 ... def foo(self): ... print self.__baz ... &gt;&gt;&gt; class Bar(Foo): ... def __init__(self): ... super(Bar, self).__init__() ... self.__baz = 21 ... def bar(self): ... print self.__baz ... &gt;&gt;&gt; x = Bar() &gt;&gt;&gt; x.foo() 42 &gt;&gt;&gt; x.bar() 21 &gt;&gt;&gt; print x.__dict__ {'_Bar__baz': 21, '_Foo__baz': 42} </code></pre> <p>Of course, it breaks down if two different classes have the same name.</p>
<blockquote> <p>Why are Python's 'private' methods not actually private?</p> </blockquote> <p>As I understand it, they <em>can't</em> be private. How could privacy be enforced?</p> <p>The obvious answer is &quot;private members can only be accessed through <code>self</code>&quot;, but that wouldn't work - <code>self</code> is not special in Python. It is nothing more than a commonly-used name for the first parameter of a function.</p>
9,594
<p>We are using verisign's time stamp service currently, but every so often the time stamp server becomes unavailable - mostly due to our ISP failing.</p> <p>We now timestamp everything we build, even simple dev builds as we had a lot of trouble with Vista not running the unsigned/unstamped files properly.</p> <p>Can we setup a time stamp service to do the same? I've looked around and not really found any information at my current level of knowledge that tells me this can or cannot be done.</p>
<p>This works. Not sure how efficient it is though.</p> <pre><code>CREATE PROCEDURE [dbo].[get_bars_in_foo] @bars varchar(255) AS BEGIN DECLARE @query AS varchar(MAX) SET @query = 'SELECT * FROM [foo] WHERE bar IN (' + @bars + ')' exec(@query) END -- exec [get_bars_in_foo] '1,2,3,4' </code></pre>
<p>If you go to using a stored procedure, you can use <a href="http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/232/pageid/119.aspx" rel="nofollow noreferrer">this method</a>, which I discussed in regards to how to do it in SQL.</p>
44,554
<p>I would like to check my JavaScript files without going to <a href="http://www.jslint.com/" rel="noreferrer">JSLint</a> web site.<br> Is there a desktop version of this tool for Windows?</p>
<p>From <a href="http://www.jslint.com/lint.html" rel="nofollow noreferrer">http://www.jslint.com/lint.html</a>:</p> <blockquote> <p>The analysis is done by a script running on your machine. Your script is not sent over the network.</p> <p>It is also available as a <a href="http://www.widgetgallery.com/?search=jslint" rel="nofollow noreferrer">Konfabulator widget</a>. You can check a file by dragging it and dropping it on the widget. You can recheck the file by double-clicking the widget.</p> <p>It is also available in a <a href="http://web.archive.org/web/20091217105428/http://www.jslint.com/wsh/index.html" rel="nofollow noreferrer">WSH Command Line</a> version.</p> <p>It is also available in a <a href="http://www.jslint.com/rhino/index.html" rel="nofollow noreferrer">Rhino Command Line</a> version.</p> </blockquote> <p>Or since JSLint is a JavaScript program running in your browser - you could grab the script and run it locally.</p>
<p>Most browsers have the ability to save an "entire" page, meaning that all external files such as StyleSheets, JavaScripts etc are also downloaded and properly linked into the HTML document (usually placed in a folder next to the HTML file). So, it should definitely be possible to use the tool offline.</p>
28,088
<p>I am trying to use the <code>Directory.GetFiles()</code> method to retrieve a list of files of multiple types, such as <code>mp3</code>'s and <code>jpg</code>'s. I have tried both of the following with no luck:</p> <pre><code>Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories); Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories); </code></pre> <p>Is there a way to do this in one call?</p>
<p>For .NET 4.0 and later, </p> <pre><code>var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s =&gt; s.EndsWith(".mp3") || s.EndsWith(".jpg")); </code></pre> <p>For earlier versions of .NET,</p> <pre><code>var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s =&gt; s.EndsWith(".mp3") || s.EndsWith(".jpg")); </code></pre> <p><strong>edit:</strong> <em>Please read the comments. The improvement that <a href="https://stackoverflow.com/users/97516/paul-farry">Paul Farry</a> suggests, and the memory/performance issue that <a href="https://stackoverflow.com/users/21567/christian-k">Christian.K</a> points out are both very important.</em></p>
<p>you can add this to your project</p> <pre><code>public static class Collectables { public static List&lt;System.IO.FileInfo&gt; FilesViaPattern(this System.IO.DirectoryInfo fldr, string pattern) { var filter = pattern.Split(&quot; &quot;); return fldr.GetFiles( &quot;*.*&quot;, System.IO.SearchOption.AllDirectories) .Where(l =&gt; filter.Any(k =&gt; l.Name.EndsWith(k))).ToList(); } } </code></pre> <p>then use it anywhere like this</p> <pre><code>new System.IO.DirectoryInfo(&quot;c:\\test&quot;).FilesViaPattern(&quot;txt doc any.extension&quot;); </code></pre>
19,726
<p>Say I have a table in a SQL 2005 database with 2,000,000+ records and a few indexes. What advantage is there to using index hints in my queries? Are there ever disadvantages to using index hints in queries?</p>
<p>First, try using SQL Profiler to generate a .trc file of activity in your database for a normal workload over a few hours. And then use the "Database Engine Tuning Advisor" on the SQL Server Management Studio Tools menu to see if it suggests any additional indexes, composite indexes, or covering indexes that may be beneficial.</p> <p>I never use query hints and mostly work with multi-million row databases. They sometimes can affect performance negatively.</p>
<p>My experience is that sometimes you know more about your dataset then SQL Server does. In that case you should use query hints. In other words: You help the optimizer decide.</p> <p>I once build a datawarehouse where SQL Server did not use the optimal index on a complex query. By giving an index hint in my query I managed to make a query go about 100 times faster.</p> <p>Use them only after you analysed the query plan. If you think your query can run faster when using another index or by using them in a different order, give the server a hint.</p>
14,283
<p>The built-in <code>PHP</code> extension for <code>SOAP</code> doesn't validate everything in the incoming <code>SOAP</code> request against the <code>XML Schema</code> in the <code>WSDL</code>. It does check for the existence of basic entities, but when you have something complicated like <code>simpleType</code> restrictions the extension pretty much ignores their existence.</p> <p>What is the best way to validate the <code>SOAP</code> request against <code>XML Schema</code> contained in the <code>WSDL</code>?</p>
<p>Been digging around on this matter a view hours. Neither the native PHP SoapServer nore the NuSOAP Library does any Validation. PHP SoapServer simply makes a type cast. For Example if you define</p> <pre><code>&lt;xsd:element name="SomeParameter" type="xsd:boolean" /&gt; </code></pre> <p>and submit </p> <pre><code>&lt;get:SomeParameter&gt;dfgdfg&lt;/get:SomeParameter&gt; </code></pre> <p>you'll get the php Type boolean (true)</p> <p>NuSOAP simply casts everthing to string although it recognizes simple types:</p> <p>from the nuSOAP debug log:</p> <pre><code>nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean </code></pre> <p>So the best way is joelhardi solution to validate yourself or use some xml Parser like XERCES</p>
<p>Some time ago I've create <a href="http://hype-free.blogspot.com/2007/01/implementing-web-services-with-open.html" rel="nofollow noreferrer">a proof of concept</a> web service with PHP using <a href="http://sourceforge.net/projects/nusoap" rel="nofollow noreferrer">NuSOAP</a>. I don't know if it validates the input, but I would assume it does.</p>
13,189
<p>Sql Server 2008 supports spatial data with new geometry and geography UDT's. They both support AsGml() method to serialize data in gml format. However they serialize data into GML3 format. Is there any way to tell it to serialize data into GML2 format?</p>
<p>As Marko said, there is no support for gml2 in Sql Server 2008, so I just ended up writing a function for transforming gml3 returned by the server to gml2 that I needed.</p>
<p>There is no support for GML2, but there is extensibility API that can be used to implement custom serialization.</p> <p>Here is an example of custom serialization using SqlGeometry.Populate(IGeometrySink) method (C# code):</p> <pre><code>CustomWriter w = new CustomWriter(); SqlGeometry.Parse("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))").Populate(w); System.Console.WriteLine(w); public class CustomWriter : IGeometrySink { private StringBuilder _builder = new StringBuilder(); public string ToString() { return _builder.ToString(); } public void SetSrid(int srid) { _builder.Append('@'); _builder.Append(srid); } public void BeginGeometry(OpenGisGeometryType type) { _builder.Append(" ("); _builder.Append(type); } public void BeginFigure(double x, double y, double? z, double? m) { _builder.Append(" ["); _builder.Append(x); _builder.Append(' '); _builder.Append(y); } public void AddLine(double x, double y, double? z, double? m) { _builder.Append(','); _builder.Append(x); _builder.Append(' '); _builder.Append(y); } public void EndFigure() { _builder.Append(']'); } public void EndGeometry() { _builder.Append(')'); } } </code></pre> <p>To do deserialization use SqlGeometryBuilder class:</p> <pre><code>// Create "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))" using Builder API SqlGeometryBuilder b = new SqlGeometryBuilder(); b.SetSrid(0); b.BeginGeometry(OpenGisGeometryType.Polygon); b.BeginFigure(0, 0); b.AddLine(10, 0); b.AddLine(10, 10); b.AddLine(0, 10); b.AddLine(0, 0); b.EndFigure(); b.EndGeometry(); SqlGeometry g = b.ConstructedGeometry; </code></pre>
45,954
<p>I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my <code>index.php</code> (ex. <code>somecity.domain.com</code>). </p> <p>Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. <code>blog.domain.com</code>).</p> <p>My <code>.htaccess</code> currently reads:</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </code></pre> <p>Can I manipulate this <code>.htaccess</code> to achieve what I need? Can it be done through Apache?</p>
<p>Your .htaccess does nothing useful, as Apache is probably configured with DirectoryIndex index.php. Well, it does move domain.com/a to domain.com/index.php, but I doubt that is what you want.</p> <p>Your wildcard virtualhost works because you probably have ServerAlias *.domain.com in your configuration, or a single virtualhost and DNS pointing to the address of your server. (When you have a single virtualhost, it shows up for any request, and the first listed virtualhost is the default one)</p> <p>You have to create new VirtualHosts for the static domains, leaving the default one as, well, the default one :)</p> <p>Check <a href="http://httpd.apache.org/docs/2.2/vhosts/examples.html" rel="nofollow noreferrer">these</a> <a href="http://wiki.apache.org/httpd/ExampleVhosts" rel="nofollow noreferrer">tutorials</a> that explain it all.</p>
<p>You'll have to configure apache for those static sub-domains. The "catch-all" site will be the default site configured, so that one will catch the other ones.</p>
8,393
<p>Anyone know if there is already a validator for "type" strings?</p> <p>I want to make sure that the type attributes in my custom config are one of the following:</p> <pre> type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly" type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089" </pre> <p>Writing one is easy enough, I just don't want to reinvent the wheel.</p>
<p>I'm not sure what you mean by "custom config", but if you're still working within .NET's configuration framework (e.g., developing a custom <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx" rel="nofollow noreferrer">configurationSection</a>/<a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.aspx" rel="nofollow noreferrer">configurationElement</a>), you can simply type the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute.aspx" rel="nofollow noreferrer">property</a> as System.Type (instead of string), and .NET will do the validation automatically.</p>
<p>You'll get an error with resharper's Global Error Analysis if it can't find the namespace or class, but that's not always helpful if your referencing a plugin.</p> <p>probably the simpliest thing is to put your code to load the app domain in a try catch block.</p> <p>if the dll is in the bin it will be loaded on startup but it won't throw an error until you use it so if you just new up an instance of ContainingClass. You could pull the namespaces from the config and then try and use each class.</p>
32,013
<p>I have a number of generated .sql files that I want to run in succession. I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio).<br> Is it possible to do something like this and if so what is the syntax for doing this?</p> <p>I'm hoping for something like:</p> <pre><code>exec 'c:\temp\file01.sql' exec 'c:\temp\file02.sql' </code></pre> <p>I am using SQL Server 2005 and running queries in management studio.</p>
<p>use <a href="http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx" rel="noreferrer">xp_cmdshell</a> and <a href="http://msdn.microsoft.com/en-us/library/ms166559.aspx" rel="noreferrer">sqlcmd</a></p> <pre><code>EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName </code></pre>
<p>Take a look at OSQL. This utility lets you run SQL from the command prompt. It's easy to get installed on a system, I think it comes with the free SQL Server Express.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa213090(SQL.80).aspx" rel="nofollow noreferrer">Using the osql Utility </a></p> <p>A qick search of "OSQL" on stack overflow shows a lot of stuff is available.</p> <p>The main thing to handle properly is the user and password account parameters that get passed in on the command line. I have seen batch files that use NT file access permissions to control the file with the password and then using this file's contents to get the script started. You could also write a quick C# or VB program to run it using the Process class.</p>
29,947
<p>What are futures? It's something to do with lazy evaluation.</p>
<p>When you create a future, a new background thread is started that begins calculating the real value. If you request the value of the future, it will block until the thread has finished calculating. This is very useful for when you need to generate some values in parallel and don't want to manually keep track of it all.</p> <p>See <a href="http://moonbase.rydia.net/software/lazy.rb/" rel="noreferrer">lazy.rb</a> for Ruby, or <a href="http://www.bluishcoder.co.nz/2006/07/scala-futures-and-lazy-evaluation.html" rel="noreferrer">Scala, futures, and lazy evaluation</a>.</p> <p>They can probably be implemented in any language with threads, though it would obviously be more difficult in a low-level language like C than in a high-level functional language.</p>
<p><a href="http://en.wikipedia.org/wiki/Future_(programming)" rel="nofollow noreferrer">The Wiki Article</a> gives a good overview of Futures. The concept is generally used in concurrent systems, for scheduling computations over values that may or may not have been computed yet, and further, whose computation may or may not already be in progress.</p> <p>From the article:</p> <blockquote> <p>A future is associated with a specific thread that computes its value. This computation may be started either eagerly when the future is created, or lazily when its value is first needed.</p> </blockquote> <p>Not mentioned in the article, futures are a <a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming" rel="nofollow noreferrer">Monad</a>, and so it is possible to project functions on future values into the monad to have them applied to the future value when it becomes available, yielding another future which in turn represents the result of that function.</p>
10,591
<p>I’ve been using Thingiverse pretty heavily since I started printing, and I frequently come across the same text block in unrelated models. Am I missing the joke or a hidden meaning in the frequent reuse of the following content?</p> <blockquote> <p>Designed up this dealer button to use in home games or have just as something laying around for any poker fan. It was inspired by a dealer button in Pokerstars VR.</p> <p>Printing:</p> <p>Ring - Infil to add weight, supports needed for spade inset. Letter embossing doesn't need it.<br /> Spade - Infil to add weight, no supports<br /> Letters - Print flat, already scaled to fit nicely in the embossing<br /> Star - Infil to add weight.</p> <p>Full print with 4x4x4 walls/top/bottom and 38% infil came to about 48g in weight.</p> <p>Glue in lettering and spade. Star may need minor sanding but should push fit into the space tightly and not need anything else to secure it.</p> </blockquote> <p>Here is an example of what I mean: <a href="https://www.thingiverse.com/thing:4887617" rel="nofollow noreferrer">Voronoi bear</a>. Just curious if anyone knows why that’s used as a pseudo default description, or if I should avoid those files for any reason I’m unaware of.</p> <p>Here’s another example: <a href="https://www.thingiverse.com/thing:4871879" rel="nofollow noreferrer">cats</a></p>
<p>The &quot;dealer button&quot; text is the default text that Thingiverse inserts when you create a new Thing entry. If you get in a hurry and hit &quot;Publish Thing&quot; before you edit that, it'll go up for everyone to see with the &quot;dealer button&quot; default text still in place. Many times, when you see that, you'll also see the defaults still in place for machine specs, filament type, etc.</p> <p>In other words, it's just a user error, especially prevalent on &quot;quickie&quot; uploads that aren't intended for a wide audience or long term preservation. Based on comments, this may also be a relatively recent change at Thingiverse; I've only uploaded designs there over the past few months, and I've seen it every time over that time frame (since about April 2021).</p>
<p>Consider this example: <a href="https://www.thingiverse.com/thing:4888256" rel="nofollow noreferrer">https://www.thingiverse.com/thing:4888256</a></p> <p>The text entered by the author is visible above the seemingly random text you mentioned in your question.</p> <p>Seeing how Thingiverse is a Makerbot product, it's likely that they've messed up their database somehow.</p>
1,989
<p>I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called <a href="http://en.wikipedia.org/wiki/Spss" rel="noreferrer">SPSS</a>. Part of the output that they care about looks like this:</p> <p><img src="https://i.stack.imgur.com/m0swl.png" alt="[Part of the SPSS output"></p> <p>They're really only concerned about the <code>F</code> and <code>Sig.</code> values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them.</p> <p>I thought the <code>F</code> value might be the result of the <a href="http://en.wikipedia.org/wiki/F-test#Table_on_F-test" rel="noreferrer">F-test</a>, but after following the steps given on Wikipedia, I got a result that was different from what <code>SPSS</code> gives.</p>
<p><a href="http://people.richland.edu/james/lecture/m170/ch13-2wy.html" rel="nofollow noreferrer">This website</a> might help you out a bit more. Also <a href="http://www.unesco.org/webworld/idams/advguide/Chapt4_3.htm" rel="nofollow noreferrer">this one</a>.</p> <p>I'm working from a fairly rusty memory of a statistics course, but here goes nothing:</p> <p>When you're doing analysis of variance (ANOVA), you actually calculate the F statistic as the ratio from the mean-square variances "between the groups" and the mean-square variances "within the groups". The second link above seems pretty good for this calculation.</p> <p>This makes the F statistic measure exactly how powerful your model is, because the "between the groups" variance is explanatory power, and "within the groups" variance is random error. High F implies a highly significant model.</p> <p>As in many statistical operations, you back-determine Sig. using the F statistic. Here's where your Wikipedia information comes in slightly handy. What you want to do is - using the degrees of freedom given to you by SPSS - find the proper P value at which an <a href="http://www.ento.vt.edu/~sharov/PopEcol/tables/f005.html" rel="nofollow noreferrer">F table</a> will give you the F statistic you calculated. The P value where this happens [F(table) = F(calculated)] is the significance.</p> <p>Conceptually, a lower significance value shows a very strong ability to reject the null hypothesis (which for these purposes means to determine your model has explanatory power).</p> <p>Sorry to any math folks if any of this is wrong. I'll be checking back to make edits!!!</p> <p>Good luck to you. Stats is fun, just maybe not this part. =)</p>
<p>Can you explain more why SPSS itself isn't a fine solution to the problem? Is it that it generates pivot tables as output that are hard to manipulate? Is it the cost of the program? </p> <p>F-statistics can arise from any number of particular tests. The F is just a distribution (loosely: a description of the "frequencies" of groups of values), like a Normal (Gaussian), or Uniform. In general they arise from ratios of variances. Opinion: many statisticians (myself included), find F-based tests to be unstable (jargon: non-<em>robust</em>).</p> <p>The particular output statistics (Pillai's trace, etc.) suggest that the original analysis is a MANOVA example, which as other posters describe is a complicated, and hard to get right procedure.</p> <p>I'm guess also that, based on the MANOVA, and the use of SPSS, this is a psychology or sociology project... if not please enlighten. It might be that other, simpler models might actually be easier to understand and more repeatable. Consult your local university statistical consulting group, if you have one. </p> <p>Good luck! </p>
2,400
<p>I have several projects and a website in a large asp.net solution. In some of projects I have an app.config file and in the website I have my web.config. In each config I specify several things that are common amongst them, such as connection strings. Is there any way to consolidate these common items into one config file and reference that from the various projects that need them?</p>
<p>Many of these have been said or are similar to previous answers... With AD integration:</p> <p>a) I don't have to worry about the users who have access to any given application, I can pass that off to the security guys.</p> <p>b) I can restrict access at a table by table level based on groups that already exists, as well as forcing standard users to only have the ability to call stored proc's.</p> <p>c) When a developer leaves my group, we don't have to change all the DB passwords (i.e. if you care about data security...)</p> <p>d) It's easy to do custom logging based on the user who makes the change. There are other ways to do this, but I'm all about being lazy.</p> <p>e) Integrates with IIS authentication. If you're already using IE &amp; IIS for your intranet, this just makes life a lot easier.</p> <p>Note: There are far more reasons not to use it, and I never used it before my present position. Here where everything is lined up in AD already... It's just the easiest time I've ever had with database security.</p>
<p>For an enterprise application which will run in an AD environment, using Windows integrated security is definitely the right approach. You don't want users who are already authenticated in the environment to have to manage a separate set of credentials just for your app. Note we are talking about <strong>authentication</strong>... for <strong>authorization</strong> you would still use SQL server's role based security.</p>
43,946
<p>My company has a number of relatively small Access databases (2-5MB) that control our user assisted design tools. Naturally these databases evolve over time as data bugs are found and fixed and as the schema changes to support new features in the tools. Can anyone recommend a database diff tool to compare both the data and schema from one version of the database to the next? Any suggestions will be appreciated: free, open source, or commercial.</p>
<p>I use Red Gate Sql Compare for comparing schemas. It also has an interesting feature that allows you to save a snapshot of the schema which you can then use in later diffs. for example compare the schema of today with the schema of a month ago.</p>
<p>We never actually purchased it as we ended up using SQL Server 2005, but DBDiff seemed to do the trick: <a href="http://www.dkgas.com/downdbdiff.cgi" rel="nofollow noreferrer">http://www.dkgas.com/downdbdiff.cgi</a></p> <p>It works with any ODBC compatible DB.</p>
4,801
<p>I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.</p> <p>As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.</p> <pre><code>╔════════╦═════════════╦════════╦══════╗ β•‘ SiteId β•‘ VisitorType β•‘ Last30 β•‘ Totalβ•‘ ╠════════╬═════════════╬════════╬══════╣ β•‘ 1 β•‘ 1 β•‘ 10 β•‘ 100 β•‘ β•‘ 1 β•‘ 2 β•‘ 40 β•‘ 140 β•‘ β•‘ 2 β•‘ 1 β•‘ 20 β•‘ 180 β•‘ β•šβ•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β• </code></pre> <p>In SQL, I can easily get the counts for SiteID 1 with the following:</p> <pre><code>SELECT SiteId, SUM(Last30) AS Last30Sum FROM Sites WHERE SiteId = 1 GROUP BY SiteId </code></pre> <p>and should get a row like...</p> <pre><code>╔════════╦════════════╗ β•‘ SiteId β•‘ Last30Totalβ•‘ ╠════════╬════════════╣ β•‘ 1 β•‘ 50 β•‘ β•šβ•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β• </code></pre> <p>However I'm not sure how to get this result using Linq. I've tried:</p> <pre><code>var statsRecord = from ss in db.SiteStats where ss.SiteId == siteId group ss by ss.SiteId into ss select ss; </code></pre> <p>but I'm not able to get back the total with something like <code>statsRecord.Last30</code></p> <p>Can someone please let me know where I'm going wrong? Any help is appreciated.</p>
<p>Actually, although Thomas' code will work, it is more succint to use a lambda expression:</p> <pre><code>var totals = from s in sites group s by s.SiteID into grouped select new { SiteID = grouped.Key, Last30Sum = grouped.Sum( s =&gt; s.Last30 ) }; </code></pre> <p>which uses the Sum extension method without the need for a nested LINQ operation.</p> <p>as per the LINQ 101 examples - <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped" rel="noreferrer">http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped</a></p>
<p>Easiest way for me to illustrate is using in-memory objects so it's clear what's happening. LINQ to SQL should be able to take that same LINQ query and translate it into appropriate SQL.</p> <pre><code>public class Site { static void Main() { List&lt;Site&gt; sites = new List&lt;Site&gt;() { new Site() { SiteID = 1, VisitorType = 1, Last30 = 10, Total = 100, }, new Site() { SiteID = 1, VisitorType = 2, Last30 = 40, Total = 140, }, new Site() { SiteID = 2, VisitorType = 1, Last30 = 20, Total = 180, }, }; var totals = from s in sites group s by s.SiteID into grouped select new { SiteID = grouped.Key, Last30Sum = (from value in grouped select value.Last30).Sum(), }; foreach (var total in totals) { Console.WriteLine("Site: {0}, Last30Sum: {1}", total.SiteID, total.Last30Sum); } } public int SiteID { get; set; } public int VisitorType { get; set; } public int Last30 { get; set; } public int Total { get; set; } } </code></pre>
5,527
<p>I have a very simple app I'm trying to get to run under TCP using WCF 3.5 on Vista Enterpise. The error I'm getting when trying to hit a WCF service at <a href="http://localhost:8080" rel="nofollow noreferrer">http://localhost:8080</a> (or any other port not reserved by http) is:</p> <p>TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8080.</p> <p>I've gotten this to work a few months ago, but I forgot how. I'm wondering if I have the port reserved or something...I've tried allowing the compiled executable through Windows Firewall and tried opening port 8080 for TCP through the firewall, but i get the same error. Any thoughts or ideas on where to look or what to check?</p> <p>Thanks!</p>
<p>Try going to http://<em>machinename</em>:8080 - I've had Vista make firewall distinctions based on that before, especially if the Loopback adapter was installed</p>
<p>No dice. Changing localhost to the machine name doesn't let me in.</p> <p>It's not http that is having the problem...localhost works fine there as well. But everything I've tried to do with tcp has faild with the same error. Completely frustrating as I know I've seen this work on this box before.</p> <p><strong>Edit to include commented answer:</strong> <em>Just FYI, finally found the problem. Something was misnamed in the service's config file. I wish the error could have been a bit clearer, but all is well. Thanks!</em></p>
48,598
<p>When we write in a Javascript expression : </p> <pre><code>expression &lt; &lt;%=variableJsp%&gt; </code></pre> <p>the double "&lt;" seems to be a problem and the JSP is not interpreted ?</p> <p>Is it a fault of the other servers that should not accept this type of expression ? Or WebSphere that bugs ?</p>
<p>Your small code-sample looks like something we do without problems.</p> <p>Try creating a JSP that illustrates the problem, and nothing else. Either create a new from scratch, or remove everything not relevant to the problem.</p> <p>Chances are, you will find that the error is not in your code-sample. But if you can make a small JSP-file (a few lines) that illustrates the problem, please show it to us.</p>
<p>I find it generally a bad idea to inline javascript on jsp pages.Your problem is only one of the reasons to make javascript functions external.</p> <p>Although I do not know websphere, this has happened to me on other containers.</p> <p>If you insist on keeping it inline, you can probably use</p> <pre><code>expression &amp;lt; &lt;%=variableJsp%&gt; </code></pre>
37,688
<p>I'm asking more about what this means to my code. I understand the concepts mathematically, I just have a hard time wrapping my head around what they mean conceptually. For example, if one were to perform an O(1) operation on a data structure, I understand that the number of operations it has to perform won't grow because there are more items. And an O(n) operation would mean that you would perform a set of operations on each element. Could somebody fill in the blanks here?</p> <ul> <li>Like what exactly would an O(n^2) operation do?</li> <li>And what the heck does it mean if an operation is O(n log(n))?</li> <li>And does somebody have to smoke crack to write an O(x!)?</li> </ul>
<p>One way of thinking about it is this:</p> <p>O(N^2) means for every element, you're doing something with every other element, such as comparing them. Bubble sort is an example of this.</p> <p>O(N log N) means for every element, you're doing something that only needs to look at log N of the elements. This is usually because you know something about the elements that let you make an efficient choice. Most efficient sorts are an example of this, such as merge sort.</p> <p>O(N!) means to do something for all possible permutations of the N elements. Traveling salesman is an example of this, where there are N! ways to visit the nodes, and the brute force solution is to look at the total cost of every possible permutation to find the optimal one.</p>
<p>log(n) means logarithmic growth. An example would be divide and conquer algorithms. If you have 1000 sorted numbers in an array ( ex. 3, 10, 34, 244, 1203 ... ) and want to search for a number in the list (find its position), you could start with checking the value of the number at index 500. If it is lower than what you seek, jump to 750. If it is higher than what you seek, jump to 250. Then you repeat the process until you find your value (and key). Every time we jump half the search space, we can cull away testing many other values since we know the number 3004 can't be above number 5000 (remember, it is a sorted list).</p> <p>n log(n) then means n * log(n).</p>
13,272
<p>I have a format file where I want one of the columns to be "group". I'm auto-generating the format file and a client wants to upload a file with "group" as one of the columns. I could restrict it so they can't use SQL keywords, but then I need a function to determine if a column name is a SQL keyword, so I'd like to support the user being able to name their clients however they want. I'm wondering if this is possible. I tried using brackets, but that didn't appear to work. My file looks like:</p> <pre> 8.0 1 1 SQLCHAR 0 0 "\r\n" 1 [group] SQL_Latin1_General_CP1_CI_AS </pre>
<p>I tested this out several different ways on SQL 2005 SP2 (target databases in both compatibility modes 80 and 90) and it works OK for me using the SQL 2005 version of bcp.</p> <p>However, I also tested it with the SQL 2000 version of bcp, and that failed with </p> <pre><code>Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'group'. </code></pre> <p>which I guess is what you're getting.</p> <p>Are you able to upgrade the system where you're running bcp to use the SQL 2005 client tools?</p> <p>If you believe that you have already upgraded, check your PATH environment variable to confirm that </p> <pre><code>C:\Program Files\Microsoft SQL Server\90\Tools\binn\ </code></pre> <p>(adjusted for your installation) appears before</p> <pre><code>C:\Program Files\Microsoft SQL Server\80\Tools\BINN </code></pre> <p>otherwise the SQL 2000 command line tools will be used in preference to the SQL 2005</p>
<p>On MS SQL, you can use a SQL Keywork as a column name if you put it in quotation.</p> <p>Example: <code>SELECT id, "group" FROM myTable</code></p>
24,655