input
stringlengths
51
42.3k
output
stringlengths
18
55k
Is Mono ready for prime time? <p>Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, <em>really</em> compatible enough to just take of and run already written code for Microsoft's runtime?</p>
<p>There are a couple of scenarios to consider: (a) if you are porting an existing application and wondering if Mono is good enough for this task; (b) you are starting to write some new code, and you want to know if Mono is mature enough.</p> <p>For the first case, you can use the <a href="http://mono-project.com/MoMA">Mono Migration Analyzer tool</a> (Moma) to evaluate how far your application is from running on Mono. If the evaluation comes back with flying colors, you should start on your testing and QA and get ready to ship.</p> <p>If your evaluation comes back with a report highlighting features that are missing or differ significantly in their semantics in Mono you will have to evaluate whether the code can be adapted, rewritten or in the worst case whether your application can work with reduced functionality. </p> <p>According to our Moma statistics based on user submissions (this is from memory) about 50% of the applications work out of the box, about 25% require about a week worth of work (refactoring, adapting) another 15% require a serious commitment to redo chunks of your code, and the rest is just not worth bothering porting since they are so incredibly tied to Win32. At that point, either you start from zero, or a business decision will drive the effort to make your code portable, but we are talking months worth of work (at least from the reports we have).</p> <p>If you are starting from scratch, the situation is a lot simpler, because you will only be using the APIs that are present in Mono. As long as you stay with the supported stack (which is pretty much .NET 2.0, plus all the core upgrades in 3.5 including LINQ and System.Core, plus any of the Mono cross-platform APIs) you will be fine. </p> <p>Every once in a while you might run into bugs in Mono or limitations, and you might have to work around them, but that is not different than any other system.</p> <p>As for portability: ASP.NET applications are the easier ones to port, as those have little to no dependencies on Win32 and you can even use SQL server or other popular databases (there are plenty of bundled database providers with Mono). </p> <p>Windows.Forms porting is sometimes trickier because developers like to escape the .NET sandbox and P/Invoke their brains out to configure things as useful as the changing the cursor blinking rate expressed as two bezier points encoded in BCD form in a wParam. Or some junk like that.</p>
Best practise to authorize all users for just one page <p>What is the best way to authorize all users to one single page in a asp.net website.</p> <p>For except the login page and one other page, I deny all users from viewing pages in the website. </p> <p>How do you make this page accessible to all users?</p>
<p>I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to leverage the User.IsInRole type functions you typically only get with Windows authentication.</p> <p>That way in my web.config file, I can do stuff like...</p> <pre><code>&lt;location path="Login.aspx"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users ="*" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; &lt;location path="ManagementFolder"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles ="Administrator, Manager" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre>
Arguments for going open source <p>I've spent my downtime at work this summer writing a framework of sorts for facilitating my day to day work. In short it loads a xml with markup that defines the blocks of the site, their content and the styling of these (very similar to html), handles the loading of assets and such.</p> <p>Now I'm rather pleased with how this is turning out, and I've been itching to release some of my code for public use (and scrutiny). I'm also reasonably sure that it fills a void for quick and easy construction of sites (or parts of them).</p> <p><strong><em>What would be the best arguments to convince my boss/coworkers that releasing this under an open source license is a good idea?</em></strong></p>
<ul> <li>Popularity</li> <li>Community contribution</li> <li>Public scrutiny</li> <li>We will be forced to adhere to standards. (which will in turn make the product better)</li> <li>Goodwill</li> </ul>
Can you set, or where is, the local document root? <p>When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine(file:///) then where should the css file be for the browser to find it?</p> <pre><code>&lt;link href="/temp/test.css" rel="stylesheet" type="text/css" /&gt; </code></pre>
<p>You <i>can</i>, but probably don't want to, set the document root on a per-file basis in the head of your file:</p> <pre> &lt;base href="my-root"&gt; </pre>
How to check set of files conform to a naming scheme <p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p> <p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p> <p>Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.</p> <p>The current code can be found <a href="http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py" rel="nofollow">here</a></p> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. </p> <p>How could I write this system in a more expandable way?</p> <p>The rules it needs to check would be..</p> <ul> <li>File is in the format <code>Show Name - [01x23] - Episode Name.avi</code> or <code>Show Name - [01xSpecial02] - Special Name.avi</code> or <code>Show Name - [01xExtra01] - Extra Name.avi</code></li> <li>If filename is in the format <code>Show Name - [01x23].avi</code> display it a 'missing episode name' section of the output</li> <li>The path should be in the format <code>Show Name/season 2/the_file.avi</code> (where season 2 should be the correct season number in the filename)</li> <li>each <code>Show Name/season 1/</code> folder should contain "folder.jpg"</li> </ul> <p>.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..</p> <p>The only thought I had was a list of dicts in the format:</p> <pre><code>checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets } </code></pre>
<blockquote> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state..</p> </blockquote> <p>This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:</p> <ol> <li>Get a list of all the files</li> <li>Check for "required" files</li> </ol> <p>You would just have have add to your dictionary a list of required files:</p> <pre><code>checker = { ... 'required': ['file', 'list', 'for_required'] } </code></pre> <p>As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex):</p> <pre><code>check_dict = { 'delim' : /\-/, 'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ], 'patterns' : [/valid name/, /valid episode name/, /valid number/ ], 'required' : ['list', 'of', 'files'], 'ignored' : ['.*', 'hidden.txt'], 'start_dir': '/path/to/dir/to/test/' } </code></pre> <ol> <li>Split the filename based on the delimiter.</li> <li>Check each of the parts.</li> </ol> <p>Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the <code>parts</code> and <code>patterns</code> have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order.</p> <p>Ignored and required files can be listed. The <code>.</code> and <code>..</code> files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of <code>svn:ignore</code> properties, but globbing is natural for listing files.</p> <p>Here <code>start_dir</code> would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful.</p> <p>The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of <code>parts</code>, which makes sense but adds complexity.</p> <p>Is this strategy in tune with what you were thinking of?</p>
Code to ask yes/no question in javascript <p>I could only find the function <code>confirm()</code> that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?</p>
<p>Javascript offers 3 modal boxes. Prompt, confirm and alert. None of those satisfy your request. </p> <p>There are a plethora of js modal popup solutions. Here's an example.</p> <ul> <li><a href="http://www.wildbit.com/labs/modalbox/">ModalBox</a></li> </ul>
Display rows in multiple columns in Asp.net Gridview <p>By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?</p>
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.aspx"><code>DataList</code></a> control instead. It has a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.repeatcolumns.aspx"><code>RepeatColumns</code></a> property that you can define the number of columns you want to display.</p> <p>In .NET Framework 3.5, there is an even better solution, the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview"><code>ListView</code></a> control. You can find further information about how to use the ListView control <a href="http://msdn.microsoft.com/en-us/library/bb398790.aspx">here</a>.</p>
Best way to keep an ordered list of windows (from most-recently created to oldest)? <p>What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed.<br> This is for a web application, so we're using jQuery Javascript.</p> <p>We'd talked through a few simplistic solutions, such as using an array and just treating [0] index as the top-most window.</p> <p>I'm wondering if there's any potentially more efficient or useful alternative to what we had brainstormed.</p>
<p>I don't really know javascript, but couldn't you create a stack of windows?</p>
What are the most important things to learn about .net as a Project Manager? <p>Thinking about getting into .net technology project management</p> <p>I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge.</p> <p>What should I know about .net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology?</p> <p><strong>Edit (8.24.08):</strong> The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any .net essentials would be appreciated.</p>
<p>The number one rule is do NOT just ask for status updates. It is Especially <strong>annoying</strong> when phrases like "where are we on this?" are used. If you aren't directly involved in the details then just make sure you have established communication times or plans so that you know whats going on rather than asking for updates.</p>
Any ReSharper equivalent for Xcode? <p>I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm.</p> <p>One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff.</p> <p>On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc? </p> <p>I suspect there aren't but I suppose it can't help to ask.</p>
<p>You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion.</p> <p>The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all <code>NSTextView</code>s; try it!) If you want to have the completions appear automatically, you can go to <strong>Preferences</strong> -> <strong>Code Sense</strong> and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++.</p> <p>Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options:</p> <ol> <li>Back in <strong>Preferences</strong>,go to <strong>Key Bindings</strong>, and then, under <strong>Menu Key Bindings</strong>, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do</li> <li><p>Use the <code>CompletionPrefix</code>. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields.</p> <p>You can see <a href="http://crookedspin.com/2005/06/10/xcode-macros/">a full list of Xcode's default macros and their associated <code>CompletionPrefix</code>es</a> at <a href="http://crookedspin.com">Crooked Spin</a>.</p> <p>You can also add your own macros, or modify the defaults. To do so, edit the file <code>/Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro</code>. The syntax should be self-explanatory, if not terribly friendly.</p></li> </ol> <p>Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve.</p>
Cleaning up RTF text <p>I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.</p> <p>The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)</p> <pre><code>{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl ;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par </code></pre> <p>Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.</p>
<p>I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards.</p>
Executing JavaScript from Flex: Is this javascript function dangerous? <p>I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)</p> <p>I am currently doing this by exposing the following JavaScript method:</p> <pre><code>function doScript(js){ eval(js);} </code></pre> <p>I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):</p> <pre><code>ExternalInterface.call("doScript","alert('foo')); </code></pre> <p>My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...</p> <p>Is there a better way to do this?</p>
<p>There's no need for the JavaScript function, the first argument to <code>ExternalInterface</code> can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong).</p> <p>Try this:</p> <pre><code>ExternalInterface.call("alert('hello')"); </code></pre>
SQL Server - Dirty Reads Pros & Cons <p>Why should I or shouldn't I use dirty reads:</p> <pre><code>set transaction isolation level read uncommitted </code></pre> <p>in SQL Server?</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx">MSDN</a>:</p> <blockquote> <p>When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. </p> </blockquote> <p>Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.</p>
How to stop NTFS volume auto-mounting on OS X? <p>I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.</p> <p>Basically, I have an external disk with two volumes: </p> <p>One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.</p> <p>So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. </p> <p>What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:</p> <ul> <li>I've tried going through options in Disk Utility</li> <li>I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.</li> <li>I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.</li> </ul> <p>Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).</p> <p>EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.</p>
<p>The following entry in <code>/etc/fstab</code> will do what you want, even on 10.5 (Leopard):</p> <pre><code>LABEL=VolumeName none ntfs noauto </code></pre> <p>If the file is not already there, just create it. Do not use <code>/etc/fstab.hd</code>! No reloading of <code>diskarbitrationd</code> needed.</p> <p>If this still doesn't work for you, maybe you can find a hint in the syslog.</p>
Java JPanel redraw issues <p>I have a Java swing application with a panel that contains three JComboBoxes that do not draw properly.<br> The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value.<br> The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel.</p> <p>All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me.<br> Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time. </p> <p>Has anyone else seen this and found a different way to force a redraw of the combo boxes?</p>
<p>Can you give us some more information on how you add the combo boxes to the JPanel? This is a pretty common thing to do in Swing so I doubt that it's a JVM issue but I guess anything is possible.</p> <p>Specifically, I would double check to make sure you're not accessing the GUI from any background threads. In this case, maybe you're reading the choices from a DB or something and updating the JComboBox from a background thread, which is a big no-no in Swing. See SwingUtils.invokeLater().</p>
Silverlight vs Flex <p>My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development.</p> <p>Most of our other development is done using .NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the .NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all .NET code. We have more .NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash.</p> <p>I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. </p> <p>So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?</p>
<p>I think you should look at Silverlight as a long-term play, just as Microsoft seems to be doing. There's an obvious balance on when to use Silverlight vs. Flash when you're concerned about reach and install base, but here are some reasons Silverlight is a good direction to move in:</p> <ol> <li><p>Second mover advantage - Just as Microsoft built a "better Java" with .NET, they're able to look at how you'd design a RIA plugin from scratch, today. They have the advantage of knowing how people use the web today, something the inventors of Flash could never have accurately guessed. Flash can add features, but they can't realistically chuck the platform and start over.</p></li> <li><p>Developer familiarity - While Silverlight is a new model, it's not entirely unfamiliar to developers. They'll "get" the way Silverlight works a lot more quickly than they'll understand firing up a new development environment with a new scripting language and new event paradigms.</p></li> <li><p>Being rid of the timeline model in Flash - Flash was originally built for keyframe based animations, and while there are ways to abstract this away, it's at the core of how Flash works. Silverlight ditches that for an application-centric model. </p></li> <li><p>ScottGu - ScottGu is fired up about Silverlight. Nuff said.</p></li> <li><p>Cool new features - While Silverlight still has some catching up to do with Flash on some obvious features (like webcam / mic integration, or 3d / graphics acceleration), there are some slick new technologies built in to Silverlight - Deep Zoom is one example. I'm seeing more "revolutionary" technologies on the Silverlight side, while Flash seems to be in maintenance mode at this point.</p></li> </ol>
Is there any way to configure windows to not change the focus? <p>I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)</p> <p>Do you know if there's some setting I could touch for this not to happen?</p>
<p>Not that I know of. This has been a plague of Windows versions for quite some time.</p>
Am I missing something about LINQ? <p>I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.</p> <p>I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?</p>
<p>LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.</p> <p>LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.</p> <p>Take the task of finding the intersection of two lists:</p> <p>Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code.</p> <pre><code>foreach (int number in list1) { foreach (int number2 in list2) { if (number2 == number) { returnList.add(number2); } } } </code></pre> <p>Using LINQ, it does the same thing in one line of code:</p> <pre><code>var results = list1.Intersect(list2); </code></pre> <p>You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.</p>
Does Hostmonster support Django <p>I know Hostmonster allows Python. Has anyone successfully run Django on there? Any problems? </p>
<p>I know this is an old question, but here is the answer: <strong>yes, Hostmonster does support Django</strong></p> <p>There used to be <a href="http://helpdesk.hostmonster.com/index.php/kb/article/000531" rel="nofollow">this Hostmonster KB article</a> for details, including instructions on how to set it up, but that link appears to be dead these days, and the only article about Hostmonster article about Django is about <a href="https://my.hostmonster.com/cgi/help/585" rel="nofollow">troubleshooting</a>. You can find instructions on how to set up Django on Hostmonster <a href="http://www.calebmadrigal.com/django-on-hostmonster/" rel="nofollow">elsewhere</a>.</p>
How to enable multisampling for a wxWidgets OpenGL program? <p><strong><a href="http://en.wikipedia.org/wiki/Multisample_anti-aliasing" rel="nofollow">Multisampling</a></strong> is a way of applying <strong>full screen anti-aliasing</strong> (FSAA) in 3D applications. I need to use multisampling in my OpenGL program, which is currently embedded in a <strong>wxWidgets</strong> GUI. Is there a way to do this? Please respond only if you know the detailed steps to achieve this.</p> <p>I'm aware of enabling multisampling using <strong><a href="http://msdn.microsoft.com/en-us/library/ms537544%28VS.85%29.aspx" rel="nofollow">WGL</a></strong> (Win32 extensions to OpenGL). However, since my OpenGL program isn't written in MFC (and I want the code to be multi-platform portable), that's not an option for me.</p>
<p>I finally got Multisampling working with my wxWidgets OpenGL program. It's a bit messy right now, but here's how:</p> <p><strong>wxWidgets</strong> doesn't have <strong>Multisampling</strong> support in their <strong>stable releases</strong> right now (latest version at this time is <strong>2.8.8</strong>). But, it's available as a patch and also through their daily snapshot. (The latter is heartening, since it means that the patch has been accepted and should appear in later stable releases if there are no issues.)</p> <p>So, there are 2 options:</p> <ol> <li><p>Download and build from their <strong><a href="http://biolpc22.york.ac.uk/pub/Daily_HEAD/" rel="nofollow">daily snapshot</a></strong>.</p></li> <li><p>Get the <strong><a href="https://sourceforge.net/tracker/?func=detail&amp;atid=309863&amp;aid=1915804&amp;group_id=9863" rel="nofollow">patch</a></strong> for your working wxWidgets installation.</p></li> </ol> <p>I found the 2nd option to be less cumbersome, since I don't want to disturb my working installation as much as possible. If you don't know how to patch on Windows, see <a href="http://stackoverflow.com/questions/19611/" rel="nofollow">this</a>.</p> <p>At the very least, for Windows, the patch will modify the following files:</p> <pre><code>$(WX_WIDGETS_ROOT)/include/wx/glcanvas.h $(WX_WIDGETS_ROOT)/include/wx/msw/glcanvas.h $(WX_WIDGETS_ROOT)/src/msw/glcanvas.cpp </code></pre> <p>After patching, <strong>recompile</strong> the wxWidgets libraries.</p> <p>To enable multisampling in your wxWidgets OpenGL program, minor changes to the code are required.</p> <p>An attribute list needs to be passed to the <strong>wxGLCanvas</strong> constructor:</p> <pre><code>int attribList[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_SAMPLE_BUFFERS, GL_TRUE, // Multi-sampling WX_GL_DEPTH_SIZE, 16, 0, 0}; </code></pre> <p>If you were already using an attribute list, then add the line with <code>GL_SAMPLE_BUFFERS, GL_TRUE</code> to it. Else, add this attribute list definition to your code.</p> <p>Then modify your wxGLCanvas constructor to take this attribute list as a parameter:</p> <pre><code>myGLFrame::myGLFrame // Derived from wxGLCanvas ( wxWindow *parent, wxWindowID id, const wxPoint&amp; pos, const wxSize&amp; size, long style, const wxString&amp; name ) : wxGLCanvas(parent, (wxGLCanvas*) NULL, id, pos, size, style, name, attribList) { // ... } </code></pre> <p>After the wxGLCanvas element is created, multisampling is turned on by default. To disable or enable it at will, use the related OpenGL calls:</p> <pre><code>glEnable(GL_MULTISAMPLE); glDisable(GL_MULTISAMPLE); </code></pre> <p>Multisampling should now work with the wxWidgets OpenGL program. Hopefully, it should be supported in the stable release of wxWidgets soon, making this information irrelevant :-)</p>
.NET - Get protocol, host, and port <p>Is there a simple way in <em>.NET</em> to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p> <p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p> <p>I need to return:</p> <p><code>http://www.mywebsite.com:80</code></p> <p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p> <p>Any suggestions?</p>
<p>Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named <code>Uri.GetLeftPart()</code> method.</p> <pre><code>Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string output = url.GetLeftPart(UriPartial.Authority); </code></pre> <p>There is one catch to <code>GetLeftPart()</code>, however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of <code>GetLeftPart()</code> in my example above will be <code>http://www.mywebsite.com</code>. </p> <p>If the port number had been something other than 80, it would be included in the result.</p>
PostgreSQL: GIN or GiST indexes? <p>From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&amp;&amp;, @>, &lt;@, etc). However I would be interested in advice about when to use one or the other (or neither possibly).<br> The <a href="http://www.postgresql.org/docs/current/static/textsearch-indexes.html">PostgreSQL documentation</a> has some information about this:</p> <ul> <li>GIN index lookups are about three times faster than GiST</li> <li>GIN indexes take about three times longer to build than GiST</li> <li>GIN indexes are about ten times slower to update than GiST</li> <li>GIN indexes are two-to-three times larger than GiST</li> </ul> <p>However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?</p>
<p>First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best.<br /> Anyway, PostgreSQL documentation has a chapter on <a href="http://www.postgresql.org/docs/8.3/static/gist.html">GIST</a> and one on <a href="http://www.postgresql.org/docs/8.3/static/gin.html">GIN</a>, where you can find more info.<br /> And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.</p>
System.Web.Caching vs. Enterprise Library Caching Block <p>For a .NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block.</p> <ul> <li>What do you use?</li> <li>Why?</li> </ul> <h2><a href="http://msdn.microsoft.com/en-us/library/system.web.caching.aspx">System.Web.Caching</a></h2> <p>Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really.</p> <ul> <li><a href="http://support.microsoft.com/kb/917411">a KB article warning against 1.0 and 1.1 non web app use</a></li> <li>The 2.0 page has a <em>comment</em> that indicates it's OK: <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx">http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx</a></li> <li><a href="http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx">Scott Hanselman is creeped out by the notion</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx">The 3.5 page</a> includes a warning against such use</li> <li>Rob Howard <a href="http://weblogs.asp.net/cschittko/archive/2004/07/04/172684.aspx">encouraged use outside of web apps</a></li> </ul> <p>I don't expect to use one of its highlights, <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx">SqlCacheDependency</a>, but the addition of <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cacheitemupdatecallback.aspx">CacheItemUpdateCallback</a> in .NET 3.5 seems like a Really Good Thing. </p> <h2><a href="http://msdn.microsoft.com/en-us/library/aa480453.aspx">Enterprise Library Caching Application Block</a></h2> <ul> <li>other blocks are already in use so the dependency already exists</li> <li>cache persistence isn't necessary; regenerating the cache on restart is OK</li> </ul> <p>Some cache items should always be available, but be refreshed periodically. For these items, getting a callback <em>after</em> an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated.</p> <h2><a href="http://jehiah.cz/projects/memcached-win32/">Memcached for Win32</a> + <a href="http://sourceforge.net/projects/memcacheddotnet/">.NET client</a></h2> <p>What are the pros and cons when you don't need a <em>distributed</em> cache?</p>
<p>These are the items that I consider for the topic of Caching:</p> <p>MemCached Win32 Velocity .net Cache Enterprise Library Caching Application Block</p> <p><strong>MemCached Win32:</strong> Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. <a href="http://lineofthought.com/tools/memcached" rel="nofollow">http://lineofthought.com/tools/memcached</a></p> <p><strong>Velocity:</strong> This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! <a href="http://blogs.msdn.com/velocity/" rel="nofollow">http://blogs.msdn.com/velocity/</a></p> <p><strong>.NET Cache:</strong> There is no reason to discount the standard .NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache.</p> <p><strong>Enterprise Application Block:</strong> I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!)</p> <p><strong>You don't have to choose up front!</strong> I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or .NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use .NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - <strong>transparently</strong>.</p> <p>I cover .NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested!</p> <p>ASP.NET 3.5 Social Networking (<a href="http://rads.stackoverflow.com/amzn/click/1847194788" rel="nofollow">http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1225408005&amp;sr=8-1</a> ) Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net</p> <p><strong>Update</strong> Changed the link that lists sites using memcached. Thank you David for noticing that it was broken!</p>
Table cells larger than they are meant to be <p>I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me ;)</p> <p>I have <a href="http://woarl.com/board/rob.php?mode=map&amp;x=-1&amp;y=9&amp;w=2&amp;h=2" rel="nofollow">made the latest version live</a> so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated.</p> <p>In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question.</p> <p>I have also uploaded an <a href="http://woarl.com/badMap.png" rel="nofollow">image of the issue</a>.</p>
<p>I think you need to use <code>display: block</code> on your images. When images are <code>inline</code> there's a little extra space for the line spacing.</p>
Can you compile Apache HTTP Server and redeploy its binaries to a different location? <p>As part of our product release we ship Apache HTTP Server binaries that we have compiled on our (UNIX) development machine.</p> <p>We tell our clients to install the binaries (on their UNIX servers) under the same directory structure that we compiled it under. For some clients this is not appropriate, e.g. where there are restrictions on where they can install software on their servers and they don't want to compile Apache themselves.</p> <p>Is there a way of compiling Apache HTTP Server so its installation location(s) can be specified dynamically using environment variables ?</p> <p>I spent a few days trying to sort this out and couldn't find a way to do it. It led me to believe that the Apache binaries were hard coding some directory paths at compilation preventing the portability we require.</p> <p>Has anyone managed to do this ?</p>
<p>I think the way to do(get around) this problem is to develop a "./configure &amp;&amp; make" script that your client uses to install, specify and compile the binaries. That would offcourse require that the client has all the source-code installed on his server or you can make it available on an NFS share.</p>
WCF push to client through firewall? <blockquote> <p>See also <a href="http://stackoverflow.com/questions/1700917/how-does-a-wcf-server-inform-a-wcf-client-about-changes-better-solution-then-si">How does a WCF server inform a WCF client about changes? (Better solution then simple polling, e.g. Coment or long polling)</a></p> </blockquote> <p>I need to use push-technology with WCF through client firewalls. This must be a common problem, and I know for a fact it works in theory (see links below), but I have failed to get it working, and I haven't been able to find a code sample that demonstrates it.</p> <p>Requirements: </p> <ul> <li>WCF</li> <li>Clients connects to server through tcp port 80 (netTcpBinding).</li> <li>Server pushes back information at irregular intervals (1 min to several hours).</li> <li>Users should not have to configure their firewalls, server pushes must pass through firewalls that have all inbound ports closed. TCP duplex on the same connection is needed for this, a dual binding does not work since a port has to be opened on the client firewall.</li> <li>Clients sends heartbeats to server at regular intervals (perhaps every 15 mins) so server knows client is still alive.</li> <li>Server is IIS7 with WAS.</li> </ul> <p>The solution seems to be duplex netTcpBinding. Based on this information:</p> <p><a href="http://blogs.msdn.com/drnick/archive/2006/05/01/configuring-wcf-for-nats-and-firewalls.aspx">WCF through firewalls and NATs</a></p> <p><a href="http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx">Keeping connections open in IIS</a></p> <p>But I have yet to find a code sample that works.. I've tried combining the "Duplex" and "TcpActivation" samples from Microsoft's WCF Samples without any luck. Please can someone point me to example code that works, or build a small sample app. Thanks a lot!</p>
<p>I've found a couple of solutions:</p> <p><a href="http://www.zeroc.com/" rel="nofollow" title="ZeroC Ice">ZeroC Ice</a> GPL with a commercial option. Have only tested quickly. Looks more powerful than .NET Remoting and is very actively developed.</p> <p><a href="http://www.remobjectssdk.com/" rel="nofollow" title="RemObjects">RemObjects</a> Commercial, active development, supports everything but does not seem to have all the more advanced features that GenuineChannels use.</p> <p><a href="http://www.genuinechannels.com/" rel="nofollow" title="GenuineChannels">GenuineChannels</a>. It uses remoting with a lot of nice added features, the most important one being it works through NATs without the need to open the client firewall. Unfortunately seems to be very dead.</p> <p>Another solution is to use streaming with IIS, according to this article: <a href="http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx" rel="nofollow" title="Keeping connections open in IIS">Keeping connections open in IIS</a></p> <p>The client makes the first connection (http with IIS6, tcp with IIS7) to the server at port 80, the connection is then kept open with a streaming response that never ends.</p> <p>I haven't had the time to experiment with this, and I haven't found a sample that says it specifically solves the firewall-problem, but here's an excellent sample that probably works: <a href="http://blogs.thinktecture.com/buddhike/archive/2007/05/23/414851.aspx" rel="nofollow">Streaming XML</a>. </p>
What are the major differences between ANSI C and K&R C? <p>The <a href="http://en.wikipedia.org/wiki/ANSI_C">Wikipedia article on ANSI C</a> says:</p> <blockquote> <p>One of the aims of the ANSI C standardization process was to produce a superset of K&amp;R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style.</p> </blockquote> <p>That makes me think that there are differences. However, I didn't see a comparison between K&amp;R C and ANSI C. Is there such a document? If not, what are the major differences?</p> <p>EDIT: I believe the K&amp;R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore?</p>
<p>There may be some confusion here about what "K&amp;R C" is. The term refers to the language as documented in the first edition of "The C Programming Language." Roughly speaking: the input language of the Bell Labs C compiler circa 1978.</p> <p>Kernighan and Ritchie were involved in the ANSI standardization process. The "ANSI C" dialect superceded "K&amp;R C" and subsequent editions of "The C Programming Language" adopt the ANSI conventions. "K&amp;R C" is a "dead language," except to the extent that some compilers still accept legacy code.</p>
What's a good way to check if two datetimes are on the same calendar day in TSQL? <p>Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index.</p> <p>In this case, merging the function code back into the query seems impractical.</p> <p>I think I am missing something simple here.</p> <p>Here's the function for reference.</p> <pre><code>if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go </code></pre> <p>To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row:</p> <pre><code>where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight </code></pre> <p>[Edit]</p> <p>I'm incorporating @Todd's suggestion:</p> <pre><code>where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 </code></pre> <p>My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort.</p> <p>But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.</p>
<p>This is much more concise:</p> <pre><code>where datediff(day, date1, date2) = 0 </code></pre>
How do I cluster an upload folder with ASP.Net? <p>We have a situation where users are allowed to upload content, and then separately make some changes, then submit a form based on those changes.</p> <p>This works fine in a single-server, non-failover environment, however we would like some sort of solution for sharing the files between servers that supports failover.</p> <p>Has anyone run into this in the past? And what kind of solutions were you able to develop? Obviously persisting to the database is one option, but we'd prefer to avoid that.</p>
<p>In our scenario, we have a separate file server that both of our front end app servers write to, that way you either server has access to the same sets of files.</p>
Configure a Java Socket to fail-fast on disconnect? <p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p> <pre><code>Socket mySocket = new Socket(host,port); </code></pre> <p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p> <pre><code>tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT </code></pre> <p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p> <p>I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.</p> <p>Any advice please?</p> <p>Thanks all</p>
<p>Set a short timeout?</p> <p>Does <code>isOutputShutdown()</code> not get you what you want?</p> <p>You could always build a <code>SocketWatcher</code> class that spins up in its own <code>Thread</code> and repeatedly tries to write empty strings to the <code>Socket</code> until that raises a <code>SocketClosedException</code>.</p>
What is the best way to prevent session hijacking? <p>Specifically this is regarding when using a client session cookie to identify a session on the server.</p> <p>Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie?</p> <p>And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie?</p> <p>If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?</p>
<p>Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed.</p> <p>The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not.</p> <p><strong>EDIT</strong>: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!</p>
Acts-as-readable Rails plugin Issue <p>I'm using Intridea's <a href="http://www.intridea.com/2008/2/29/acts-as-readable-drop-in-mark-as-read-functionality">Acts as Readable</a> Rails plugin for a messaging system I'm currently building. I've defined my message class accordingly:</p> <pre><code>class Post &lt; ActiveRecord::Base acts-as-readable end </code></pre> <p>And everything seems to be working according to plan, but when trying to execute to show unread messages in my message view, I'm running into problems.</p> <p>Their example: (I've changed underscores to hyphens due to formatting issues)</p> <pre><code>bob = User.find_by_name("bob") bob.readings # =&gt; [] Post.find_unread_by(bob) # =&gt; [&lt;Post 1&gt;,&lt;Post 2&gt;,&lt;Post 3&gt;...] Post.find_read_by(bob) # =&gt; [] Post.find(1).read_by?(bob) # =&gt; false Post.find(1).read_by!(bob) # =&gt; &lt;Reading 1&gt; Post.find(1).read_by?(bob) # =&gt; true Post.find(1).users_who_read # =&gt; [&lt;User bob&gt;] Post.find_unread_by(bob) # =&gt; [&lt;Post 2&gt;,&lt;Post 3&gt;...] Post.find_read_by(bob) # =&gt; [&lt;Post 1&gt;] bob.readings # =&gt; [&lt;Reading 1&gt;] </code></pre> <p>So it seems as though if I wanted to list the number of unread messages sitting in a mailbox (for example Inbox (39) ), I should be able to do something like:</p> <pre><code>&lt;%= Post.find_unread_by(current-user).count %&gt; </code></pre> <p>But to no avail. I always seem to get stuck on the simple view issues after everything's set. Any ideas?</p>
<p>The following will work</p> <pre><code>&lt;%= Post.find_unread_by(current_user).size %&gt; </code></pre> <p>or</p> <pre><code>&lt;%= Post.find_unread_by(current_user).length %&gt; </code></pre> <p>However if you check your development.log you should see that it gets the unread count by </p> <ol> <li>Retrieving all the posts</li> <li>Retrieving all the posts read by the user</li> <li>Removing all of 2. from 1. in ruby</li> </ol> <p>This will be very bad performance wise with lots of posts. </p> <p>A better way would be to retrieve the posts read by the current user and then use ActiveRecord::Calculations to get a count without retrieving all the posts in the database</p> <pre><code>Post.count(:conditions =&gt; [ "id NOT IN (?)", Post.find_read_by(current_user)]) </code></pre> <p>This should go into your Post model to follow best practices of not having finders in the view or controller </p> <h2>Post.rb</h2> <pre><code>def self.unread_post_count_for_user(user) count(:conditions =&gt; [ "id NOT IN (?)", Post.find_read_by(user)]) end </code></pre> <p>Then your view will just be</p> <pre><code>&lt;%= Post.unread_post_count_for_user(current-user) %&gt; </code></pre>
How Does One Sum Dimensions of an Array Specified at Run-Time? <p>I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about."</p> <p>Example: Consider the following example... </p> <pre> Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. </pre> <p>I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. </p> <h3>Update:</h3> <p>Just got home. Here is some info to answer your questions:</p> <ol> <li>Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out.</li> <li>@jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).</li> <li>I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. </li> <li>The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).</li> </ol> <p>Thanks everyone for your imput.</p>
<p>@Jeff</p> <p>I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question.</p> <p>@Ed</p> <p>Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well?</p> <p>EDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ...</p> <p>Let's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, <code>array_care[4][4][4]</code> for 1,2, and 6. The <code>array_care[4][4][4]</code> will hold the end result.</p> <p>Next, we want to iterate in a very specific way. We have the array <code>input[4][4][4][4][4][4][4][4]</code> to parse through, and we care about dimensions 1, 2, and 6.</p> <p>We need to define some temporary indexes:</p> <pre><code>int dim[8] = {0,0,0,0,0,0,0,0}; </code></pre> <p>We also need to store the order in which we want to increase the indexes:</p> <pre><code>int increase_index_order[8] = {7,5,4,3,0,6,2,1}; int i = 0; </code></pre> <p>This order is important for doing what you requested.</p> <p>Define a termination flag:</p> <pre><code>bool terminate=false; </code></pre> <p>Now we can create our loop:</p> <pre><code>while (terminate) { array_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]]; while ((dim[increase_index_order[i]] = 3) &amp;&amp; (i &lt; 8)) { dim[increase_index_order[i]]=0; i++; } if (i &lt; 8) { dim[increase_index_order[i]]++; i=0; } else { terminate=true; } } </code></pre> <p>That should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :(</p>
When do you use the "this" keyword? <p>I was curious about how other people use the <strong>this</strong> keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:</p> <p>In a constructor:</p> <pre><code>public Light(Vector v) { this.dir = new Vector(v); } </code></pre> <p>Elsewhere</p> <pre><code>public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } </code></pre>
<p>I don't mean this to sound snarky, but it doesn't matter.</p> <p>Seriously.</p> <p>Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office. </p> <p>It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something. </p> <p>I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.</p>
How IE7 determines a site's Security Zone <p>Does anyone know how IE7 determines what Security Zone to use for a site? I see the basics for IE6 <a href="http://www.microsoft.com/technet/prodtechnol/ie/reskit/6/default.mspx?mfr=true" rel="nofollow">here</a>, but I can't find the equivalent for IE7.</p>
<p>I could use a little more information to narrow down my answer, but here is what I have:</p> <p>Internet Explorer has 5 different security zones be default: Local Machine Zone, Intranet, Internet, Trusted, and Restricted These are determined in urlmon.dll (Url Moniker) More information here: <a href="http://msdn.microsoft.com/en-us/library/ms537183" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms537183</a>(VS.85).aspx</p> <p>But you can also implement your own custom security zone: <a href="http://msdn.microsoft.com/en-us/library/ms537182" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms537182</a>(VS.85).aspx</p> <p>The way that IE determines the security zones should not have changes between IE6 and IE7 (or IE8 for that matter)</p> <p>Intranet sites are determined: 1. By url host names do not have any dots (<a href="http://stackoverflow" rel="nofollow">http://stackoverflow</a> vs <a href="http://stackoverflow.com" rel="nofollow">http://stackoverflow.com</a>)</p> <ol> <li>Sites from the file:// scheme where the resource is collected from UNC</li> </ol>
Source Control Beginners <p>What would be the best version control system to learn as a beginner to source control?</p>
<p>Anything but Visual Source Safe; preferably one which supports the concepts of branching and merging. As others have said, Subversion is a great choice, especially with the TortoiseSVN client.</p> <p>Be sure to check out (pardon the pun) <a href="http://www.ericsink.com/scm/source_control.html">Eric Sink's classic series of Source Control HOWTO articles</a>.</p>
Notification of drop in drag-drop in Windows <p>My C# program has a list of files that can be dragged from it and dropped into another program. My requirements are that the file be copied to a different directory first.</p> <p>So, can I be notified of the drop operation so that I can only copy the file if operation succeeds? I'd rather wait till I know it needs to be copied before actually performing the copy.</p> <p>Also, is it possible to know what program the drop operation is occurring in? Ideally I'd like to alter the filepath based on who or what its being dropped.</p> <p>The solution to this can be in any .NET language or C/C++ with COM.</p>
<p>There are a few ambiguities in your question. What operation needs to be successful?</p> <p>For everything you want to know about drag and drop, browse through these search results (multiple pages worth):</p> <p><a href="http://www.google.com/search?q=drag+drop+site%3Ablogs.msdn.com%2Foldnewthing&amp;rls=com.microsoft:en-us&amp;ie=UTF-8&amp;oe=UTF-8&amp;startIndex=&amp;startPage=1" rel="nofollow">Raymond Chen on drag and drop</a></p>
What is your best list of 'must have' development tools? <p>I recently burned up my development laptop (it literally emitted smoke from the vents). After pulling the hd I was unable to get it to spin with a USB device attached to a home tower. Since I was on a deadline I had to rush and buy a new laptop (Turion 64 x2) running Vista.</p> <p>After I installed my required applications VS2005/2008, Sql Server editions client tools, Adobe CS3, and source control clients: <strong>I am wondering what list of “must haves” developer tools that are out there these days?</strong> I’m a big fan of Fiddler and LinqPad, but I am wondering what I am missing?</p> <p>[edit]I read the other question here and I am aware of Hanselman's list. I was not specific enough in my original question. By "these days" I meant new and latest tools (perhaps available only 64 bit), which in geek years might just be 12 days, I dunno. :)[/edit]</p>
<p>Let me be general [then specific]:</p> <ol> <li>Your IDE of choice [<a href="http://www.microsoft.com/Express/">VS 2008</a> here]</li> <li>Your debugger [It is usually part of your IDE, but sometimes <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx">WinDbg</a> is needed]</li> <li>Its plugins for refactoring and source control [<a href="http://www.jetbrains.com/resharper/">Resharper 4+</a> and <a href="http://ankhsvn.open.collab.net/">Ankh SVN 2+</a>]</li> <li>Your OS's addons for source control [<a href="http://tortoisesvn.tigris.org/">Tortoise SVN</a>]</li> <li>A better Diff and Merge Tool to plug into the above SCM tools [<a href="http://winmerge.org/">WinMerge</a>]</li> <li>A fast loading text editor for when your IDE is too much [<a href="http://www.vim.org/">vim</a>, <a href="http://notepad-plus.sf.net/">Notepad++</a>]</li> <li>If you're doing web development, get tools for that [<a href="http://www.mozilla.com/en-US/firefox/">Firefox 3</a> with Add-ons: <a href="http://chrispederick.com/work/web-developer/">Web Developer</a>, <a href="http://getfirebug.com/">Firebug</a>, <a href="http://tamperdata.mozdev.org">TamperData</a>, <a href="http://code.google.com/p/poster-extension/">Poster</a>, <a href="http://www.janodvarko.cz/firecookie">Firecookie</a>, <a href="http://fireftp.mozdev.org/">FireFTP</a>, <a href="http://www.firephp.org/">FirePHP</a>, <a href="http://xrefresh.com/rainbow">Rainbow</a> for Firebug, <a href="http://reloadevery.mozdev.org/">ReloadEvery</a>, <a href="http://selenium-ide.openqa.org/">Selenium IDE</a>]</li> <li>Requisite tools for working with text [<a href="http://www.gnu.org/software/textutils/textutils.html">GNU TextUtils</a>, via <a href="http://cygwin.org/">cygwin</a> or <a href="http://gnuwin32.sf.net">gnuwin32.sf.net</a>]</li> <li>Scripting tools [<a href="http://www.perl.org/">Perl</a>, <a href="http://python.org/">Python</a>, <a href="http://www.zsh.org/">zsh</a>, all those <a href="http://www.gnu.org/software/coreutils/">GNU base packages</a> in cygwin]</li> <li>A Regular Expression testing tool for when your eyes hurt [<a href="http://www.ultrapico.com/Expresso.htm">Expresso</a>, <a href="http://www.regexbuddy.com/">RegexBuddy</a>]</li> </ol> <p>For Java I swap out 1 and 3 with <a href="http://www.eclipse.org/">Eclipse</a>, and its plugins for <a href="http://maven.apache.org/">Maven</a> and <a href="http://subversion.tigris.org/">SVN</a>, I haven't found a refactoring plug in... you'd think I'd use <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a> but I never started using it.</p>
Windows / Active Directory - User / Groups <p>I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:</p> <pre><code>DOMAIN\USER DOMAIN\GROUP </code></pre> <p>I have a list of users in active directory format that I need to add:</p> <pre><code>ou=group1;ou=group2;ou=group3 </code></pre> <p>I have tried adding DOMAIN\Group1, but I get a 'user not found' error.</p> <p>P.S. should also be noted that I'm not a Lan admin </p>
<p>Programatically or Manually?</p> <p>Manually, i prefer <a href="http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx" rel="nofollow">AdExplorer</a>, which is a nice Active directory Browser. You just connect to your domain controller and then you can look for the user and see all the details. Of course, you need permissions on the Domain Controller, not sure which though.</p> <p>Programatically, it depends on your language of couse. On .net, the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx" rel="nofollow">System.DirectoryServices</a> Namespace is your friend. (I don't have any code examples here unfortunately)</p> <p>For Active Directory, I'm not really an expert apart from how to query it, but here are two links I found useful:</p> <p><a href="http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm" rel="nofollow"><a href="http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm" rel="nofollow">http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm</a></a></p> <p><a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow"><a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow">http://en.wikipedia.org/wiki/Active_Directory</a></a> (General stuff about the Structure of AD)</p>
What Javascript rich text editor will not break the browser's spellcheck? <p>I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.</p> <p>As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko_spellcheck option, which is supposed to fix it, but it doesn't.</p> <p>Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?</p>
<p>TinyMCE only goes out of its way to disable spell-checking when you don't specify the <code>gecko_spellcheck</code> option (i verified this with their example code). Might want to double-check your <code>tinyMCE.init()</code> call - it should look something like this:</p> <pre><code>tinyMCE.init({ mode : "textareas", theme : "simple", gecko_spellcheck : true }); </code></pre>
Free or Open Source Collaboration/eLearning Software <p>I am looking for open source or free data collaboration software. Specifically this is for a non-profit organization that wants to teach remote students how a foreign language. The idea is that an instructor would teach a class and there would be up to 10 students in the class at a time. The instructor would be able to post slides or other teaching material and the students would be able to see it on their computers remotely. Video is not required but audio is a must. Any recommendations?</p> <p>Also if there have been any reviews or feature comparison amongst these products, I would be interested in hearing about them.</p>
<p>I know a few of the developers on the Carleton University developed <a href="http://code.google.com/p/blindside/" rel="nofollow">Blindside Project</a>. They are actively developing an open-source web conferencing and presentation tool for e-learning, with the intent of eventually offering university courses online.</p> <p>It's pretty fully featured software, and is meant to be installed as a server that can host many conference rooms at a time. It has voice, video, text, and a whiteboard/slideshow (<strong>Edit:</strong> supports PDF at the moment) capability. One feature I think it neat is that students can 'raise their hands' in the class to ask the instructor a question, where they can take the floor for a moment.</p> <p>Check out the demo on the site (if it's not working anymore I'll nudge the developers). Another pro is that the clients only need to have flash installed.</p> <p><strike><em>I just logged onto the online demo and created this preview:</em></strike></p> <p>This project is now called BigBlueButton : <a href="http://code.google.com/p/bigbluebutton/" rel="nofollow">http://code.google.com/p/bigbluebutton/</a></p> <p>Here is the demo: <a href="http://demo.bigbluebutton.org/" rel="nofollow">http://demo.bigbluebutton.org/</a></p>
Good strategy for leaving an audit trail/change history for DB applications? <p>What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc.</p> <p>Some info on the DB:</p> <ul> <li>Needs to have the capacity to grow by thousands of records per week</li> <li>50-60 Tables</li> <li>Main revisioned tables may have several million records each</li> <li>Reasonable amount of foreign keys and indexes set</li> <li>Using PostgreSQL 8.x</li> </ul>
<p>One strategy you could use is MVCC, Multi-Value Concurrency Control. In this scheme, you never do updates to any of your tables, you just do inserts, maintaining version numbers for each record. This has the advantage of providing an exact snapshot from any point in time, and it also completely sidesteps the update lock problems that plague many databases.</p> <p>But it makes for a huge database, and selects all require an extra clause to select the current version of a record.</p>
Factorial Algorithms in different languages <p>I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.</p> <h2>Ideas:</h2> <ul> <li>Procedural</li> <li>Functional</li> <li>Object Oriented</li> <li>One liners</li> <li>Obfuscated</li> <li>Oddball</li> <li>Bad Code</li> <li><a href="http://en.wikipedia.org/wiki/Polyglot_%28computing%29" rel="nofollow">Polyglot</a></li> </ul> <p>Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.</p> <p>Please limit it to one example per entry. I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.</p> <p>The only real requirement is it must find the factorial of a given argument, in all languages represented.</p> <h1>Be Creative!</h1> <h2>Recommended Guideline:</h2> <pre> # Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here </pre> <p>I will ocasionally go along and edit any answer that does not have decent formatting.</p>
<h1>Polyglot: 5 languages, all using bignums</h1> <p>So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources.</p> <ul> <li><b>Perl</b>: uses built-in bignum package. Run with <code>perl FILENAME</code>.</li> <li><b>Haskell</b>: uses built-in bignums. Run with <code>runhugs FILENAME</code> or your favorite compiler's equivalent.</li> <li><b>C++</b>: requires GMP for bignum support. To compile with g++, use <code>g++ -lgmpxx -lgmp -x c++ FILENAME</code> to link against the right libraries. After compiling, run <code>./a.out</code>. Or use your favorite compiler's equivalent.</li> <li><b>brainf*ck</b>: I wrote some bignum support in <a href="http://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages/432010#432010">this post</a>. Using <a href="http://aminet.net/package.php?package=dev/lang/brainfuck-2.lha" rel="nofollow">Muller's classic distribution</a>, compile with <code>bf &lt; FILENAME &gt; EXECUTABLE</code>. Make the output executable and run it. Or use your favorite distribution.</li> <li><b>Whitespace</b>: uses built-in bignum support. Run with <code>wspace FILENAME</code>.</li> </ul> <p><i>Edit:</i> added Whitespace as a fifth language. Incidentally, do <em>not</em> wrap the code with <code>&lt;code&gt;</code> tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width.</p> <pre>char&#32;//#&#32;b=0+0{-&#32;|0*/;&#32;#&gt;&gt;&gt;&gt;,----------[&gt;&gt;&gt;&gt;,-------- #define&#09;a/*#--]&gt;&gt;&gt;&gt;++&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;++++++[&lt;------&gt;-]&lt;-&lt;&lt;&lt; #Perl&#09;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&#09;&#32;&lt;&gt;&#32;&lt;&gt;&#32;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt; #C++&#09;--&gt;&lt;&gt;&lt;&gt;&#09;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&#09;&gt;&#32;&lt;&#32;&gt;&#32;&lt;&#09;+&lt;[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;-&lt;[-]]&gt;[-] #Haskell&#32;&gt;&gt;]&gt;[-&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&gt;&gt;] #Whitespace&#09;&gt;&gt;&gt;&gt;[-[&gt;+&lt;-]+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt; #brainf*ck&#32;&gt;&#32;&lt;&#32;]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[[&gt;&gt;&gt;&gt;*/ exp;&#32;;//;#+&lt;&lt;&lt;&lt;-]&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;][.POLYGLOT^5. #include&#32;&lt;gmpxx.h&gt;//]&gt;&gt;&gt;&gt;-[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt; #define&#09;eval&#32;int&#09;main()//&gt;+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-&gt; #include&#32;&lt;iostream&gt;//&lt;]&lt;-[&gt;&gt;+&lt;&lt;[-]]&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[&gt;[&gt;&gt;&gt; #define&#09;print&#32;std::cout&#09;&lt;&lt;&#32;//&#32;&gt;&#09;&lt;+&lt;-]&gt;[&lt;&lt;+&gt;+&gt;-]&lt;&lt;[&gt;&gt;&gt; #define&#09;z&#32;std::cin&gt;&gt;//&lt;&lt;&#32;+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-]&lt;-&gt;+++++ #define&#32;c/*++++[-&lt;[-[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;-]]&gt;&gt;&gt;&gt;[&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;*/ #define&#09;abs&#32;int&#32;$n&#32;//&gt;&lt;&#09;&lt;]&lt;[&gt;&gt;+&lt;&lt;&lt;&lt;[-]&gt;&gt;[&lt;&lt;+&gt;&gt;-]]&gt;&gt;]&lt; #define&#09;uc&#32;mpz_class&#32;fact(int&#09;$n){/*&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;[&lt;&lt; use&#32;bignum;sub#&lt;&lt;]&gt;&gt;&gt;&gt;-]&gt;&gt;&gt;&gt;]&gt;&gt;&gt;[&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-] z{$_[0+0]=readline(*STDIN);}sub&#32;fact{my($n)=shift;#&gt;&gt; #[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;-&lt;[-]]&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;+*/ uc;if($n==0){return&#32;1;}return&#32;$n*fact($n-1);&#09;}//;# eval{abs;z($n);print&#32;fact($n);print("\n")/*2;};#-]&lt;-&gt; '+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;-[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]+&lt;[&gt;-+++ -}--&#09;&lt;[-]]&gt;[-&lt;&lt;++++++++++&lt;&lt;&lt;&lt;-[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-++ fact&#32;0&#09;=&#32;1&#32;--&#32;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&#09;&gt;&#32;&lt;&gt;&lt;&gt;&lt;&#09;]+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;+&#32;+ fact&#09;n=n*fact(n-1){-&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+++&gt;+-} main=do{n&lt;-readLn;print(fact&#32;n)}--&#32;+&gt;-]&lt;-&gt;+&lt;[&gt;&gt;&gt;&gt;+&lt;&lt;+ {-x&lt;-&lt;[-]]&gt;[-]&gt;&gt;]&gt;]&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;+++++++[&lt;+++++++&gt;-] &lt;--.&lt;&lt;&lt;&lt;]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;} </pre>
Best method to get objects from a BlockingQueue in a concurrent program? <p>What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I'm currently doing the following and I'm not convinced it is the best method:</p> <pre><code>BlockingQueue&lt;Violation&gt; vQueue; /* in the constructor I pass in a BlockingQueue object full of violations that need to be processed - cut out for brevity */ Violation v; while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) ) != null ) { // do stuff with the violation } </code></pre> <p>I have yet to hit a race condition... but, I'm none too sure if this is truly safe.</p>
<pre><code>class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException ex) { ... handle ...} } void consume(Object x) { ... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } </code></pre> <p>This example was taken from the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html">JDK 1.6 docs of <code>BlockingQueue</code></a>. So You can see that you are doing it the right way. Here's the quote which tells you that it have to work:</p> <blockquote> <p>Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.</p> </blockquote>
How do I marshal a lambda (Proc) in Ruby? <p>Joe Van Dyk <a href="http://www.zenspider.com/pipermail/ruby/2008-August/004223.html">asked the Ruby mailing list</a>:</p> <blockquote> <p>Hi,</p> <p>In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages?</p> <p>What I was trying to do:</p> </blockquote> <pre><code>l = lamda { ... } Bj.submit "/path/to/ruby/program", :stdin =&gt; Marshal.dump(l) </code></pre> <blockquote> <p>So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran.</p> <p>Joe</p> </blockquote>
<p>You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)</p> <p>As Gaius pointed out though, you can use <a href="https://github.com/seattlerb/ruby2ruby" rel="nofollow">ruby2ruby</a> to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later. </p>
Is there a site for detailed unit testing samples? <p>Is there a site for unit testing as <a href="http://refactormycode.com/" rel="nofollow">RefactorMyCode</a> for refactoring? I think it would be a great help for beginners like me.</p>
<p>So far, from what I have seen, RMC seems to be one-of-a-kind, which is both cool, but sad :(</p> <p>It seems pretty inactive, but I have posted a couple of questions on there, and amazed at the response (a lot of people just have the RSS feed and wait for something to happen). So I would definately recommend just getting active on there..</p> <p>However, I have read some great books on Safari including <a href="http://safari.oreilly.com/0735619484">MS Press' "Test Driven Development"</a> which I found really <em>helped</em> . However I have to admit, I still need a lot of work in adjusting my brain for TDD etc.</p> <p>Following this question though! (+1) look forward to seeing if there is more out there! :)</p> <h3>Edit:</h3> <p>Just found <a href="http://codebetter.com/blogs/darrell.norton/pages/50337.aspx">this blog post</a> that outlines a number of good bits of software, websites and books :) I knew I had one somewhere!</p>
Classes vs 2D arrays <p>Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.</p> <pre><code>// Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -&gt; name = $name; $this -&gt; height = $height; $this -&gt; weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; </code></pre> <hr> <p>Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.</p> <p>I've not idea which answer I should accept to I've just upvoted all of them.</p> <hr> <p>And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.</p> <p>Thank you for helping to make me a better programmer.</p>
<p>The "class" that you've constructed above is what most people would use a <em>struct</em> for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit.</p> <p>That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion.</p> <p>I'm only saying the following based on the title and your question, but: Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the <code>weight</code> field private and provide some accessor methods, like <code>getWeight()</code> and <code>setWeight()</code>. Inside <code>setWeight()</code>, you could do some value checking, like so:</p> <pre><code>public function setWeight($weight) { if($weight &gt;= 0) { $this-&gt;weight = $weight; } else { // Handle this scenario however you like } } </code></pre>
What's the fastest way to bulk insert a lot of data in SQL Server (C# client) <p>I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.</p> <p>I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.</p> <p>I have a simple table that looks like this: </p> <pre><code> CREATE TABLE [BulkData]( [ContainerId] [int] NOT NULL, [BinId] [smallint] NOT NULL, [Sequence] [smallint] NOT NULL, [ItemId] [int] NOT NULL, [Left] [smallint] NOT NULL, [Top] [smallint] NOT NULL, [Right] [smallint] NOT NULL, [Bottom] [smallint] NOT NULL, CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED ( [ContainerIdId] ASC, [BinId] ASC, [Sequence] ASC )) </code></pre> <p>I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. </p> <p>The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.</p> <p>Does it help any if I:</p> <ol> <li>Drop the Primary key while I am doing the inserting and recreate it later</li> <li>Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small</li> <li>Anything else?</li> </ol> <p>-- Based on the responses I have gotten, let me clarify a little bit:</p> <p>Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?</p> <p>Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.</p> <p>Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps.</p>
<p>You're already using <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx">SqlBulkCopy</a>, which is a good start.</p> <p>However, just using the SqlBulkCopy class does not necessarily mean that SQL will perform a bulk copy. In particular, there are a few requirements that must be met for SQL Server to perform an efficient bulk insert.</p> <p>Further reading:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms190422.aspx">Prerequisites for Minimal Logging in Bulk Import</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms190421.aspx">Optimizing Bulk Import Performance</a></li> </ul> <p>Out of curiosity, why is your index set up like that? It seems like ContainerId/BinId/Sequence is <strong>much</strong> better suited to be a nonclustered index. Is there a particular reason you wanted this index to be clustered?</p>
What's the point of OOP? <p>As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace.</p> <p>I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does <em>exactly</em> what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible <em>in the right way</em>, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile.</p> <p>In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles).</p> <p>So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better?</p>
<blockquote> <p>The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed</p> </blockquote> <p>While this is true and has been observed by other people (take Stepanov, inventor of the STL), the rest is nonsense. OOP may be flawed and it certainly is no silver bullet but it makes large-scale applications much simpler because it's a great way to reduce dependencies. Of course, this is only true for “good” OOP design. Sloppy design won't give any advantage. But good, decoupled design can be modelled very well using OOP and not well using other techniques.</p> <p>There are much better, more universal models (<a href="http://stackoverflow.com/questions/16770/haskells-algebraic-data-types" rel="nofollow">Haskell's type model</a> comes to mind) but these are also often more complicated and/or difficult to implement efficiently. OOP is a good trade-off between extremes.</p>
Programming a simple IRC (Internet-Relay-Chat) Client <p>I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with <a href="http://www.shoooes.net/">Shoes</a> as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers?</p>
<p>An earlier post mentioned RFC1459. While it is a very good introduction to IRC, it has actually been superseded by RFCs 2810-2813. Here is a more complete list of documentation you need to program anything IRC-related:</p> <ul> <li><a href="http://tools.ietf.org/html/rfc1459">RFC1459</a> (original RFC; superseded, but still useful)</li> <li><a href="http://tools.ietf.org/html/rfc2810">RFC2810</a> (IRC architecture)</li> <li><a href="http://tools.ietf.org/html/rfc2811">RFC2811</a> (IRC channel management)</li> <li><a href="http://tools.ietf.org/html/rfc2812">RFC2812</a> (IRC client protocol)</li> <li><a href="http://tools.ietf.org/html/rfc2813">RFC2813</a> (IRC server protocol)</li> <li><a href="http://www.irchelp.org/irchelp/rfc/ctcpspec.html">CTCP specification</a></li> <li><a href="http://www.irchelp.org/irchelp/rfc/dccspec.html">DCC specification</a></li> <li><a href="http://www.invlogic.com/irc/ctcp.html">Updated CTCP specification</a> (not all clients support this)</li> <li><a href="http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt">ISupport (response code 005) draft</a> (almost all servers support this nowadays)</li> <li><a href="http://www.leeh.co.uk/draft-mitchell-irc-capabilities-02.html">Client capabilities (CAP command) draft</a> (supported by some servers/clients)</li> <li><a href="http://ircv3.org/">IRCv3 standards and proposals</a> (the future features of IRC, some of which are already widely supported)</li> </ul>
What are the best MVC web frameworks on the market? <p>I am looking for a Web Framework to move windows based applications to the web.</p> <p>The main requirements to WF are the following:</p> <ol> <li>unit tests support</li> <li>desktop and mobile browsers support</li> <li>long term viability</li> <li>maturity of the framework</li> </ol>
<p>In my opinion, with contributions from the SO community</p> <ul> <li><a href="http://zendframework.com/">Zend Fraemwork</a> for PHP</li> <li><a href="http://www.djangoproject.com/">Django</a> for Python</li> <li><a href="http://rubyonrails.org">Rails</a> for Ruby</li> <li><a href="http://merbivore.com/">Merb</a> for Ruby (for the experienced)</li> <li><a href="http://www.asp.net/mvc/">ASP.NET MVC</a> for .NET</li> <li><a href="http://www.seaside.st/">Seaside</a> for Smalltalk</li> <li><a href="http://catalystframework.org">Catalyst</a> for Perl</li> </ul>
SQL Server: Examples of PIVOTing String data <p>Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.</p> <pre><code>Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT </code></pre> <p>I would like to use PIVOT (if even possible) to make the results like so:</p> <pre><code>Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT </code></pre> <p>Is this even possible with the PIVOT functionality?</p>
<p>Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.</p> <pre><code>SELECT Action, MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol FROM t GROUP BY Action </code></pre>
How do you automate a Visual Studio build? <p>How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?</p>
<p>With VS2008 you can do this:</p> <pre><code>devenv solution.sln /build configuration </code></pre>
Vi editing for Visual Studio <p>I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work).</p> <p>Has anyone in my situation has found a solution (and/or tested ViEmu)?</p> <p>Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home).</p> <p>Edit: Since both answers were equivalent, I ended up accepting the first one that came in.</p>
<p>ViEmu works great with Visual Studio. I used Vi(m) strictly in Linux, but I was turned on to bringing the Vi(m) editing process into the Windows world by <a href="http://www.jpboodhoo.com/">JP Boodhoo</a>. JP <a href="http://blog.jpboodhoo.com/HookedOnVIM.aspx">praises</a> about it also.</p>
Why should you prevent a class from being subclassed? <p>What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class) Right now I can't think of any.</p>
<p>Because writing classes to be substitutably extended is <em>damn hard</em> and requires you to make accurate predictions of how future users will want to extend what you've written.</p> <p>Sealing your class forces them to use composition, which is much more robust.</p>
Using Subversion with Visual Basic 6 <p>My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions:</p> <ul> <li>What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...)</li> <li>Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.)</li> </ul>
<p>I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6.</p> <p>The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit". . . thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN (<a href="http://www.daveswebsite.com/software/tamtamsvn/index.shtml">http://www.daveswebsite.com/software/tamtamsvn/index.shtml</a>) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has <a href="http://svnvb6.tigris.org/">http://svnvb6.tigris.org/</a>, but I have not tried it.</p> <p>Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out.</p>
What is this 'Multiple-step OLE DB' error? <p>I'm doing a little bit of work on a horrid piece of software built by Bangalores best.</p> <p>It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(</p> <p>I'm getting this message when it tries to connect to my local database:</p> <p><strong>Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.</strong></p> <pre><code>Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) </code></pre> <p>Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:</p> <pre><code>PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true </code></pre> <p>Which is the connection string that it was initially using, I just repointed it at my database.</p> <p><strong>UPDATE:</strong></p> <p>The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.</p>
<p>I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem.</p> <p><a href="http://support.microsoft.com/kb/269495" rel="nofollow"><a href="http://support.microsoft.com/kb/269495" rel="nofollow">http://support.microsoft.com/kb/269495</a></a></p> <p>If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next:</p> <p>Remove:</p> <pre><code>DRIVER={SQL Server}; </code></pre> <p>Edit the Provider to this:</p> <pre><code>Provider=SQLOLEDB; </code></pre>
C#.NET Winforms: Is it possible to override Label.Autosize? <p>I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a <code>AutoSize = false</code> in my constructor, however, when I place it in design mode, the property always is True. </p> <p>I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?</p> <p>Here's the full source code of my Label in case anyone is interested.</p> <pre><code>using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel : UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width &gt; 0 ? width : 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth &gt; 0 ? heigth : 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth &gt; (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth; int roundedHeight = RoundedHeight &gt; (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick != null) { TextClick(this, e); } } } } </code></pre> <p>(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).</p> <hr> <p>I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)</p> <p>I basically hate the autosize property "on by default".</p>
<p>I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults.</p> <p>I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a <em>default</em> value of false?</p>
Inserting at the very end in FCKeditor <p>FCKeditor has InsertHtml API (<a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API" rel="nofollow">JavaScript API document</a>) that inserts HTML in the current cursor position. How do I insert at the very end of the document?</p> <p>Do I need to start browser sniffing with something like this</p> <pre><code>if ( element.insertAdjacentHTML ) // IE element.insertAdjacentHTML( 'beforeBegin', html ) ; else // Gecko { var oRange = document.createRange() ; oRange.setStartBefore( element ) ; var oFragment = oRange.createContextualFragment( html ); element.parentNode.insertBefore( oFragment, element ) ; } </code></pre> <p>or is there a blessed way that I missed?</p> <p>Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack.</p>
<p>It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and reinsert everything into the editor. Although it does say </p> <blockquote> <p>Note that when using this method, you will lose any listener that you may have previously registered on the editor.EditorDocument.</p> </blockquote> <p>Hope that helps!</p>
Abstraction away from CSS <p>Let me make something quite clear.</p> <p>I. <strong>Hate</strong>. CSS.</p> <p>It is a never-ending nightmare. Every minor layout change feels like a hack. Solutions to problems seem to often involve jiggering numbers around like some chef trying to work out exactly how much nutmeg to put in his soon-to-be famous rice pudding. Then comes the multiple browser issue, the multiple resolution issues..</p> <p>.. to cut a long story short, it's a pain. A PITA, if you will.</p> <p>Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.</p> <p>Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports caclulated fields (which are 'compiled' into CSS and JS), etc.</p> <p>Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole? </p>
<p>What I found works best is to really learn CSS. I mean <strong>really</strong> learn CSS.</p> <p>It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things.</p> <p>The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it.</p> <p>Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you <strong>really</strong> practice at it and learn what works and what doesn't, and how to get around problems.</p> <p>All it takes is practice and in time you can become good at it.</p>
Asynchronous Stored Procedure Calls <p>Is it possible to call a stored prodcedure from another stored procedure asynchronously?</p> <p><strong>Edit:</strong> Specifically I'm working with a DB2 database.</p>
<p>Executive summary: Yes, if your database has a message queue service.</p> <p>You can push a message onto a queue and the queue processor will consume it asynchronously.</p> <ul> <li>Oracle: queues</li> <li>Sql Server: service broker</li> <li>DB2: event broker</li> </ul> <p>For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have.</p> <p>However, if your database has a queuing mechanism, you can use that to get the same result.</p>
Best Method to run a Java Application as a *nix Daemon or Windows Service? <p>I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the <a href="http://wrapper.tanukisoftware.org/">Java Service Wrapper</a>, the <a href="http://commons.apache.org/daemon/jsvc.html">Apache Commons project 'jsvc'</a>, and the <a href="http://commons.apache.org/daemon/procrun.html">Apache Commons project 'procrun'</a>. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there.</p>
<p>I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are:</p> <ul> <li>Great x-platform support - I've used it on Windows and Linux, and found it easy on both</li> <li>Solid Documentation - The docs are clear and to the point, with great examples</li> <li>Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe".</li> <li>Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA.</li> </ul> <p>Anyway, just my 2 cents... :)</p>
What's the best way to import/read data from pdf files? <p>We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work.</p> <p>The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called <a href="http://tclab.kaist.ac.kr/ipe/" rel="nofollow">ipe</a>), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows.</p> <p>Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. </p> <p>pdftoipe output of <a href="http://brunndahl.navarro.se/sida_002/?CoMeT_function=get_file&amp;id=9_1" rel="nofollow" title="sample pdf file">this sample</a> looks like this:</p> <pre><code>&lt;ipe creator="pdftoipe 2006/10/09"&gt;&lt;info media="0 0 612 792"/&gt; &lt;-- Page: 1 1 --&gt; &lt;page gridsize="8"&gt; &lt;path fill="1 1 1" fillrule="wind"&gt; 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h &lt;/path&gt; &lt;path fill="1 1 1" fillrule="wind"&gt; 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h &lt;/path&gt; &lt;path fill="1 1 1" fillrule="wind"&gt; 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h &lt;/path&gt; &lt;text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 181.8 707.88"&gt;This is a sample PDF fil&lt;/text&gt; &lt;text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 356.28 707.88"&gt;e.&lt;/text&gt; &lt;text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 368.76 707.88"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 692.4"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 677.88"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 663.36"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 648.84"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 634.32"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 619.8"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 605.28"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 590.76"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 576.24"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 561.72"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 547.2"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 532.68"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 518.16"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 503.64"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 489.12"&gt; &lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 474.6"&gt; &lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 456.24"&gt;If you can read this&lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 214.92 456.24"&gt;,&lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 219.48 456.24"&gt; you already have A&lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 370.8 456.24"&gt;dobe Acrobat &lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 437.64"&gt;Reader i&lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 131.28 437.64"&gt;n&lt;/text&gt; &lt;text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 141.12 437.64"&gt;stalled on your computer.&lt;/text&gt; &lt;text stroke="0 0 0" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 337.92 437.64"&gt; &lt;/text&gt; &lt;text stroke="0 0.502 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 342.48 437.64"&gt; &lt;/text&gt; &lt;image width="800" height="600" rect="-92.04 800.64 374.4 449.76" ColorSpace="DeviceRGB" BitsPerComponent="8" Filter="DCTDecode" length="369925"&gt; feedcafebabe... &lt;/image&gt; &lt;/page&gt; &lt;/ipe&gt; </code></pre>
<p>We use <a href="http://www.foolabs.com/xpdf/about.html" rel="nofollow">Xpdf</a> in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project.</p>
What is the best free memory leak detector for a C/C++ program and its plug-in DLLs? <p>I have a .exe and many plug-in .dll modules that the .exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case).</p> <p>The built-in VS leak detector only gives the line where new/malloc was called from, but I have a wrapper for allocations, so a full symbolic stack trace would be best.</p> <p>The detector would also be able to detect for a leak in both the .exe and its accompanying plug-in .dll modules.</p>
<p>I personally use <a href="http://vld.codeplex.com">Visual Leak Detector</a>, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).</p>
Ruby Performance <p>I'm pretty keen to develop my first Ruby app, as my company has finally blessed its use internally.</p> <p>In everything I've read about Ruby up to v1.8, there is never anything positive said about performance, but I've found nothing about version 1.9. The last figures I saw about 1.8 had it drastically slower than just about everything out there, so I'm hoping this was addressed in 1.9.</p> <p>Has performance drastically improved? Are there some concrete things that can be done with Ruby apps (or things to avoid) to keep performance at the best possible level?</p>
<p>There are some benchmarks of 1.8 vs 1.9 at <a href="http://www.rubychan.de/share/yarv_speedups.html" rel="nofollow">http://www.rubychan.de/share/yarv_speedups.html</a>. Overall, it looks like 1.9 is a lot faster in most cases.</p>
What is the best way to connect and use a sqlite database from C# <p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
<p>I'm with, Bruce. I AM using <a href="http://system.data.sqlite.org/">http://system.data.sqlite.org/</a> with great success as well. Here's a simple class example that I created:</p> <pre><code>using System; using System.Text; using System.Data; using System.Data.SQLite; namespace MySqlLite { class DataClass { private SQLiteConnection sqlite; public DataClass() { //This part killed me in the beginning. I was specifying "DataSource" //instead of "Data Source" sqlite = new SQLiteConnection("Data Source=/path/to/file.db"); } public DataTable selectQuery(string query) { SQLiteDataAdapter ad; DataTable dt = new DataTable(); try { SQLiteCommand cmd; sqlite.Open(); //Initiate connection to the db cmd = sqlite.CreateCommand(); cmd.CommandText = query; //set the passed query ad = new SQLiteDataAdapter(cmd); ad.Fill(dt); //fill the datasource } catch(SQLiteException ex) { //Add your exception code here. } sqlite.Close(); return dt; } } </code></pre>
Revoke shared folders in windows <p>Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?</p>
<p>Using computer management (an MMC snap-in. See Control Panel Administrative tools) you can see a list of all folders that are shared. You could delete the shares or change the permissions on the share to only allow access for certain people or groups.</p>
Asp.net website first start is very slow <p>The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page).</p> <p>I precompiled the site, but nothing changes. </p> <p>I don't have any code at Application start. I don't have cached items.</p> <p>Any ideas? How can I find out what is happening?</p>
<p>It's just your app domain loading up and loading any binaries into memory. Also, it's initializing static variables, so if you have a static variable that loads up a lot of data from the db, it might take a bit.</p>
Hibernate saveOrUpdate with another object in the session <p>Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?</p> <ul> <li>Doing session.contains(obj) seems to only return true if the session contains that exact object, not another object with the same ID.</li> <li>Using merge(obj) throws an exception if the object is new</li> </ul>
<p>Have you tried calling .SaveOrUpdateCopy()? It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).</p> <p>Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object. This should be easy enough to do:</p> <pre><code>IPersistable entity = Whatever(); // This is the object we're trying to update // (IPersistable has an id field) session.Evict(session.Get(entity.GetType(), entity.Id)); session.SaveOrUpdate(entity); </code></pre> <p>Although the above code could probably do with some null checking for the .Get() call.</p>
sizeof() equivalent for reference types? <p>I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?</p>
<p>You need <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.sizeof.aspx">Marshal.SizeOf</a></p> <p><strong>Edit:</strong> This <em>is</em> for unsafe code, but then, so is sizeof().</p>
How to set encoding in .getJSON JQuery <p>In my web app, I submit some form fields with jQuery <code>$.getJSON()</code> Method. I am having some problems with the encoding. The character-set of my app is <code>charset=ISO-8859-1</code> but I think these fields are submitted with <code>UTF-8</code>. </p> <p>Does anyone know, how I can set encoding in <code>$.getJSON</code> calls? </p>
<p>If you want to use <code>$.getJSON()</code> you can add the following before the call :</p> <pre><code>$.ajaxSetup({ scriptCharset: "utf-8", contentType: "application/json; charset=utf-8" }); </code></pre> <p>You can use the charset you want instead of <code>utf-8</code>.</p> <p>The options are explained <a href="http://docs.jquery.com/Ajax/jQuery.ajax#toptions" rel="nofollow">here</a>.</p> <p><code>contentType :</code> When sending data to the server, use this <code>content-type</code>. Default is <code>application/x-www-form-urlencoded</code>, which is fine for most cases.</p> <p><code>scriptCharset :</code> Only for requests with <code>jsonp</code> or <code>script</code> dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.</p> <p>You may need one or both ...</p>
Why is my PDF footer text invisible? <p>I'm creating PDFs on-demand with ColdFusion's <a href="http://cfquickdocs.com/cf8/?getDoc=cfdocument" rel="nofollow">CFDocument</a> tag, like so:</p> <pre><code>&lt;cfdocument format="PDF" filename="#attributes.fileName#" overwrite="true"&gt; &lt;cfdocumentitem type="footer"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td align="left"&gt;&lt;font face="Tahoma" color="black"&gt;&lt;strong&gt;My Client's Corporation&lt;/strong&gt;&lt;br/&gt;Street address&lt;br/&gt;City, ST 55555&lt;/font&gt;&lt;/td&gt; &lt;td align="right"&gt;&lt;font face="Tahoma" color="black"&gt;Phone: 555.555.5555&lt;br/&gt;Fax: 555.555.5555&lt;br/&gt;Email: [email protected]&lt;/font&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/cfdocumentitem&gt; &lt;html&gt; &lt;body&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;!--- some content here ... ---&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;/cfdocument&gt; </code></pre> <p>The problem I'm having is that sometimes (actually, most of the time, but not always) <strong><em>some</em></strong> of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code.</p> <p><img src="http://i.stack.imgur.com/LHZ96.png" alt="screenshot of problem"></p> <p>Any ideas on how to correct this?</p>
<p>A PDF is what I'm after, so I'm not sure how outputting another format would help.</p> <p>As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem.</p> <p>I spent some time attempting to rewrite the footer code using DDX <a href="http://www.coldfusionjedi.com/index.cfm/2008/6/2/Changing-the-size-of-a-footer-in-CFDOCUMENT" rel="nofollow">as outlined here</a> and the <a href="http://cfquickdocs.com/cf8/?getDoc=cfpdf" rel="nofollow">CFPDF</a> tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new <a href="http://cfquickdocs.com/cf8/?getDoc=IsDDX" rel="nofollow">isDDX function</a>, the CFPDF tag reported that it was invalid DDX for some reason.</p> <p>At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough.</p>
Parse string to TimeSpan <p>I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?</p>
<p>This seems to work, though it is a bit hackish:</p> <pre><code>TimeSpan span; if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span)) MessageBox.Show(span.ToString()); </code></pre>
XPath and Selecting a single node <p>I'm using XPath in .NET to parse an XML document, along the lines of:</p> <pre class="lang-cs prettyprint-override"><code>XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); // ... etc } </code></pre> <p>The issue is that the XPath Query for <code>stuffChild</code> is always returning the child of the first <code>stuff</code> element, never the rest. Can XPath not be used to query against an individual <code>XMLElement</code>?</p>
<p><code>//</code> at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.</p> <p>So you have:</p> <pre><code>XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild"); </code></pre> <p>which translates to:</p> <p><strike>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");</strike></p> <pre><code>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild"); </code></pre> <p>In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:</p> <pre><code>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); </code></pre> <p>Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".</p> <pre><code>XmlNode stuffChild = stuff.SelectSingleNode("stuffChild"); </code></pre> <p>The <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">W3Schools</a> tutorial has helpful info in an easy to digest format.</p>
Limitations of screen readers <p>I'm a web developer, and I want to make the web sites I develop more accessible to those using screen readers. What limitations do screen readers have that I should be most aware of, and what can I do to avoid hitting these limitations.</p> <p>This question was sparked by reading another question about <a href="http://stackoverflow.com/questions/8472/best-non-image-based-captcha" rel="nofollow">non-image based captchas</a>. In there, a commenter said that honey pot form fields (form fields hidden with CSS that only a bot would fill in), are a bad idea, because screen readers would still pick them up. </p> <p>Are screen readers really so primitive that they would read text that isn't even displayed on the screen? Ideally, couldn't you make a screen reader that waited until the page was finished loading, applied all css, and even ran Javascript onload functions before it figured out what was actually displayed, and then read that off to the user? You could probably even identify parts of the page that are menus or table of contents, and give some sort of easy way for those parts to be read exclusively or skipped over. I would think that the programming community could come up with a better solution to this problem. </p>
<blockquote> <p>Are screen readers really so primitive that they would read text that isn't even displayed on the screen?</p> </blockquote> <p>What you have to remember is that any HTML parser doesn't read the screen - it reads the source markup. Whta you see on the screen is the browser's attempt to apply CSS to the source code. It's irrelevant.</p> <blockquote> <p>You could probably even identify parts of the page that are menus or table of contents, and give some sort of easy way for those parts to be read exclusively or skipped over.</p> </blockquote> <p>You could, if there were a standard for such a thing.</p> <p>I'm not very hot on the <em>limitations</em> of screen readers, however I've read a lot about them not being ideal. The best thing I can reccommend is to put your source in order - how you'd read it. </p> <p>There are a <a href="http://www.w3schools.com/css/css_ref_aural.asp" rel="nofollow">set of CSS properties</a> you should also look at for screen readers.</p>
Alternating coloring groups of rows in Excel <p>I have an Excel Spreadsheet like this</p> <pre> id | data for id | more data for id id | data for id id | data for id | more data for id | even more data for id id | data for id | more data for id id | data for id id | data for id | more data for id </pre> <p>Now I want to group the data of one id by alternating the background color of the rows</p> <pre> var color = white for each row if the first cell is not empty and color is white set color to green if the first cell is not empty and color is green set color to white set background of row to color </pre> <p>Can anyone help me with a macro or some VBA code</p> <p>Thanks</p>
<p>I use this formula to get the input for a conditional formatting:</p> <pre><code>=IF(B2=B1,E1,MOD(E1+1,2)) [content of cell E2] </code></pre> <p>Where column B contains the item that needs to be grouped and E is an auxiliary column. Every time that the upper cell (B1 on this case) is the same as the current one (B2), the upper row content from column E is returned. Otherwise, it will return that content plus 1 MOD 2 (that is, the outupt will be 0 or 1, depending on the value of the upper cell).</p> <p><img src="http://i.stack.imgur.com/H6WP0.png" alt="enter image description here"></p> <p><img src="http://i.stack.imgur.com/sE57q.png" alt="enter image description here"></p> <p><img src="http://i.stack.imgur.com/4hadL.png" alt="enter image description here"></p>
Comparing Arrays of Objects in JavaScript <p>I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?</p>
<p>EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.</p> <p>To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">serialize the two arrays to JSON</a> and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to <em>each</em> of the objects within the arrays as well to see which ones were different.</p> <p>Another option is to use a library which has some nice facilities for comparing objects - I use and recommend <a href="http://www.mochikit.com/"><strong>MochiKit</strong></a>.</p> <hr> <p><strong>EDIT:</strong> <a href="http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932">The answer kamens gave</a> deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).</p> <p>Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:</p> <pre><code>function objectsAreSame(x, y) { var objectsAreSame = true; for(var propertyName in x) { if(x[propertyName] !== y[propertyName]) { objectsAreSame = false; break; } } return objectsAreSame; } </code></pre> <p>The assumption is that both objects have the same exact list of properties.</p> <p>Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)</p>
How to convert std::string to LPCWSTR in C++ (Unicode) <p>I'm looking for a method, or a code snippet for converting std::string to LPCWSTR</p>
<p>Thanks for the link to the MSDN article. This is exactly what I was looking for.</p> <pre><code>std::wstring s2ws(const std::string&amp; s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } std::wstring stemp = s2ws(myString); LPCWSTR result = stemp.c_str(); </code></pre>
Why aren't Enumerations Iterable? <p>In Java 5 and above you have the foreach loop, which works magically on anything that implements <code>Iterable</code>:</p> <pre><code>for (Object o : list) { doStuff(o); } </code></pre> <p>However, <code>Enumerable</code> still does not implement <code>Iterable</code>, meaning that to iterate over an <code>Enumeration</code> you must do the following:</p> <pre><code>for(; e.hasMoreElements() ;) { doStuff(e.nextElement()); } </code></pre> <p>Does anyone know if there is a reason why <code>Enumeration</code> still does not implement <code>Iterable</code>?</p> <p><strong>Edit:</strong> As a clarification, I'm not talking about the language concept of an <a href="http://en.wikipedia.org/wiki/Enumerated_type" rel="nofollow">enum</a>, I'm talking a Java-specific class in the Java API called '<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html" rel="nofollow">Enumeration</a>'. </p>
<p>As an easy and <strong>clean</strong> way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.</p> <pre><code>for (TableColumn col : Collections.list(columnModel.getColumns()) { </code></pre> <p>(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)</p> <p>Note, this may be very slightly less efficient.</p>
Find number of files with a specific extension, in all subdirectories <p>Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:</p> <pre><code>int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll"); </code></pre> <p>I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.</p> <p><strong>EDIT:</strong> If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?</p>
<p>You should use the <a href="http://msdn.microsoft.com/en-us/library/ms143316.aspx" rel="nofollow">Directory.GetFiles(path, searchPattern, SearchOption)</a> overload of Directory.GetFiles().</p> <p>Path specifies the path, searchPattern specifies your wildcards (e.g., *, *.format) and SearchOption provides the option to include subdirectories.</p> <p>The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:</p> <pre><code>string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories); return files.Length; </code></pre> <p><strong>EDIT:</strong> Alternatively you can use <a href="https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx" rel="nofollow">Directory.EnumerateFiles method</a></p> <pre><code>return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count(); </code></pre>
How to add (simple) tracing in C#? <p>I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:</p> <ul> <li>App.config / Web.config stuff to add for registering TraceListeners</li> <li>how to set it up in the calling application</li> </ul> <p>Do you know the uber tutorial that we should link to?</p> <p><strong>EDIT:</strong> Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside <code>&lt;configuration/&gt;</code>:</p> <pre><code>&lt;system.diagnostics&gt; &lt;trace autoflush="true"&gt; &lt;listeners&gt; &lt;add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter" initializeData="trace.log" /&gt; &lt;/listeners&gt; &lt;/trace&gt; &lt;/system.diagnostics&gt; </code></pre> <p>This will add a <code>TextWriterTraceListener</code> that will catch everything you send to with <code>Trace.WriteLine</code> etc.</p> <p><strong>EDIT:</strong> @DanEsparza pointed out that you should use <code>Trace.TraceInformation</code>, <code>Trace.TraceWarning</code> and <code>Trace.TraceError</code> instead of <code>Trace.WriteLine</code>, as they allow you to format messages the same way as <code>string.Format</code>.</p> <p><strong>Tip:</strong> If you don't add any listeners, then you can still see the trace output with the SysInternals program DebugView (<code>Dbgview.exe</code>): <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx">http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx</a></p>
<p>I wrote a short article on using the Trace Listener - maybe it will be of some help, especially for beginners - <a href="http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/">http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/</a></p>
Integrating Qt into legacy MFC applications <p>We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems. We make use of quite a few custom controls that handle all their own drawing (all written using MFC).</p> <p>Recently I've been doing more research into Qt and the benefits it provides (cross-platform and supports what you might call a more "professional" looking framework for UI development).</p> <p>My question is - <strong>what would be the best approach to perhaps moving to the Qt framework</strong>? Does Qt play nice with MFC? Would it be better to start porting some of our custom controls to Qt and gradually integrate more and more into our existing MFC apps? (is this possible?).</p> <p>Any advice or previous experience is appreciated.</p>
<p>In my company, we are currently using Qt and are very happy with it.</p> <p>I personnally never had to move a MFC-app into using the Qt framework, but here is something which might be of some interest for you :</p> <p><strike><a href="http://www.qtsoftware.com/products/appdev/add-on-products/catalog/3/Windows/qtwinmigrate/" rel="nofollow">Qt/MFC Migration Framework</a></strike></p> <p><a href="http://doc.qt.nokia.com/solutions/4/qtwinmigrate/index.html" rel="nofollow">Qt/MFC Migration Framework</a></p> <p>It's part of Qt-Solutions, so this means you'll have to buy a Qt license along with a Qt-Solutions license. (edit: <a href="http://www.qtsoftware.com/about/news/lgpl-license-option-added-to-qt" rel="nofollow">not any more</a>)</p> <p>I hope this helps !</p>
Microsoft .Net framework 3.5 SP1 Setup Fails <p>On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that: </p> <pre><code>[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1 [08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed. </code></pre> <p>First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.</p> <p>The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.</p> <p>Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?</p> <p>Thanks</p>
<p><a href="http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx" rel="nofollow">Here is an article describing what might be your problem.</a></p>
C++ : Opening a file in non exclusive mode <p>I have to develop an application which parses a log file and sends specific data to a server. It has to run on both Linux and Windows. </p> <p>The problem appears when I want to test the log rolling system (which appends .1 to the name of the creates a new one with the same name). On Windows (haven't tested yet on Linux) I can't rename a file that I have opened with std::ifstream() (exclusive access?) even if I open it in "input mode" (ios::in).</p> <p>Is there a cross-platform way to open file in a non-exclusive way?</p>
<blockquote> <p>Is there a way to open file in a non-exclusive way,</p> </blockquote> <p>Yes, using Win32, passing the various FILE_SHARE_Xxxx flags to CreateFile.</p> <blockquote> <p>is it cross platform?</p> </blockquote> <p>No, it requires platform-specific code.</p> <p>Due to annoying backwards compatibility concerns (DOS applications, being single-tasking, assume that nothing can delete a file out from under them, i.e. that they can fclose() and then fopen() without anything going amiss; Win16 preserved this assumption to make porting DOS applications easier, Win32 preserved this assumption to make porting Win16 applications easier, and it's awful), Windows defaults to opening files exclusively.</p> <p>The underlying OS infrastructure supports deleting/renaming open files (although I believe it does have the restriction that memory-mapped files cannot be deleted, which I think isn't a restriction found on *nix), but the default opening semantics do not.</p> <p>C++ has no notion of any of this; the C++ operating environment is much the same as the DOS operating environment--no other applications running concurrently, so no need to control file sharing.</p>
What are models for storing tree structures and what are their characteristics? <p>So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another.</p> <p>What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic?</p> <p>I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a <i>bad</i> choice in other contexts?</p>
<p>A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value.</p> <p>ie. for a directory tree consisting of the following:</p> <pre><code>C:\ Temp Windows System32 </code></pre> <p>You would have the following nodes</p> <pre><code>Key Name Parent Path 1 C: *1* 2 Temp 1 *1*2* 3 Windows 1 *1*3* 4 System32 3 *1*3*4* </code></pre> <p>Path is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges.</p> <p>ie. to find C:\Temp and all its children:</p> <pre><code>WHERE Path LIKE '*1*2*%' </code></pre> <p>This representation is the only place I can think of where storing <em>id's</em> in a string like this is ok.</p>
Finding a DOI in a document or page <p>The <a href="http://doi.org/">DOI</a> system places basically no useful limitations on what constitutes <a href="http://doi.org/handbook_2000/enumeration.html#2.2">a reasonable identifier</a>. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.</p> <p>Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)</p>
<p>Ok, I'm currently extracting thousands of DOIs from free form text (XML) and I realized that <a href="http://stackoverflow.com/a/10300246/89771">my previous approach</a> had a few problems, namely regarding encoded entities and trailing punctuation, so I went on reading <a href="http://www.doi.org/doi_handbook/2_Numbering.html">the specification</a> and this is the best I could come with.</p> <hr> <blockquote> <p>The DOI prefix shall be composed of a directory indicator followed by a registrant code. These two components shall be separated by a full stop (period).</p> <p>The directory indicator shall be "10". The directory indicator distinguishes the entire set of character strings (prefix and suffix) as digital object identifiers within the resolution system.</p> </blockquote> <p>Easy enough, the initial <code>\b</code> prevents us from "matching" a "DOI" that doesn't start with <code>10.</code>:</p> <pre><code>$pattern = '\b(10[.]'; </code></pre> <hr> <blockquote> <p>The second element of the DOI prefix shall be the registrant code. The registrant code is a unique string assigned to a registrant.</p> </blockquote> <p>Also, all assigned registrant code are numeric, and at least 4 digits long, so:</p> <pre><code>$pattern = '\b(10[.][0-9]{4,}'; </code></pre> <hr> <blockquote> <p>The registrant code may be further divided into sub-elements for administrative convenience if desired. Each sub-element of the registrant code shall be preceded by a full stop.</p> </blockquote> <pre><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*'; </code></pre> <hr> <blockquote> <p>The DOI syntax shall be made up of a DOI prefix and a DOI suffix separated by a forward slash.</p> </blockquote> <p>However, this isn't absolutely necessary, section 2.2.3 states that uncommon suffix systems may use other conventions (such as <code>10.1000.123456</code> instead of <code>10.1000/123456</code>), but lets cut some slack.</p> <pre><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/'; </code></pre> <hr> <blockquote> <p>The DOI name is case-insensitive and can incorporate any printable characters from the legal graphic characters of Unicode. The DOI suffix shall consist of a character string of any length chosen by the registrant. Each suffix shall be unique to the prefix element that precedes it. The unique suffix can be a sequential number, or it might incorporate an identifier generated from or based on another system.</p> </blockquote> <p>Now this is where it gets trickier, from all the DOIs I have processed, I saw the following characters (besides <code>[0-9a-zA-Z]</code> of course) in their <strong>suffixes</strong>: <code>.-()/:-</code> -- so, while it doesn't exist, the DOI <code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code> is completely plausible.</p> <p>The logical choice would be to use <code>\S</code> or the <code>[[:graph:]]</code> PCRE POSIX class, so lets do that:</p> <pre><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\S+'; // or $pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+'; </code></pre> <hr> <p>Now we have a difficult problem, the <code>[[:graph:]]</code> class is a super-set of the <code>[[:punct:]]</code> class, which includes characters easily found in free text or any markup language: <code>"'&amp;&lt;&gt;</code> among others.</p> <p>Lets just filter the markup ones for now using a negative lookahead:</p> <pre><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&amp;\'&lt;&gt;])\S)+'; // or $pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&amp;\'&lt;&gt;])[[:graph:]])+'; </code></pre> <hr> <p>The above should cover encoded entities (<code>&amp;</code>), attribute quotes (<code>["']</code>) and open / close tags (<code>[&lt;&gt;]</code>).</p> <p>Unlike markup languages, free text usually doesn't employ punctuation characters unless they are bounded by at least one space <strong><em>or</em></strong> placed at the end of a sentence, for instance:</p> <blockquote> <p>This is a long DOI: <code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code><strong>!!!</strong></p> </blockquote> <p>The solution here is to close our capture group and assert another word boundary:</p> <pre><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&amp;\'&lt;&gt;])\S)+)\b'; // or $pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&amp;\'&lt;&gt;])[[:graph:]])+)\b'; </code></pre> <p>And <em>voilá</em>, <a href="http://regexpal.com/?flags=g&amp;regex=%5Cb%2810%5B.%5D%5B0-9%5D%7B4%2C%7D%28%3F%3A%5B.%5D%5B0-9%5D%2B%29%2a%2F%28%3F%3A%28%3F!%5B%22%26%5C%27%3C%3E%5D%29%5CS%29%2B%29%5Cb&amp;input=This%20is%20a%20short%20DOI%3A%2010.1000%2F123456.%0AThis%20is%20NOT%20a%20DOI%3A%204210.1000%2F123456.%0AThis%20is%20a%20long%20DOI%3A%2010.1016.12.31%2Fnature.S0735-1097%2898%292000%2F12%2F31%2F34%3A7-7!!!%0A%0A10.1007%2F978-3-642-28108-2_19%0A10.1007.10%2F978-3-642-28108-2_19%20%28fictitious%20example%2C%20see%20%40Ju9OR%20comment%29%0A10.1016%2FS0735-1097%2898%2900347-7%0A10.1579%2F0044-7447%282006%2935%5C%5B89%3ARDUICP%5C%5D2.0.CO%3B2%0A%0AAlso%2C%20correctly%20discards%20some%20falsy%20%28X%7CHT%29ML%20stuff%20like%3A%0A%0A%3Cgeo%20coords%3D%2210.4515260%2C51.1656910%22%3E%3C%2Fgeo%3E">here is a demo</a>.</p>
How bad is dynamic casting? <p>We often hear/read that one should avoid dynamic casting. I was wondering what would be 'good use' examples of it, according to you?</p> <p>Edit:</p> <p>Yes, I'm aware of <a href="http://stackoverflow.com/questions/28002/regular-cast-vs-staticcast-vs-dynamiccast">that other thread</a>: it is indeed when reading one of the first answers there that I asked my question!</p>
<p>This recent thread gives an example of where it comes in handy. There is a base Shape class and classes Circle and Rectangle derived from it. In testing for equality, it is obvious that a Circle cannot be equal to a Rectangle and it would be a disaster to try to compare them. While iterating through a collection of pointers to Shapes, dynamic_cast does double duty, telling you if the shapes are comparable and giving you the proper objects to do the comparison on.</p> <p><a href="http://stackoverflow.com/questions/301959/vector-iterator-not-dereferencable">http://stackoverflow.com/questions/301959/vector-iterator-not-dereferencable</a></p>
SQL Server DateTime conversion failure <p>I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a <code>varchar(50)</code> field.</p> <p>I need to do a simple date comparison -</p> <pre><code>datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <p>But it fails on the <code>convert()</code>:</p> <pre><code>Conversion failed when converting datetime from character string. </code></pre> <p>Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the <code>convert()</code>? Here is what I have now:</p> <pre><code>select count(*) from MyTable where isdate(lastUpdate) &gt; 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <hr> <p><a href="http://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <p>I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option.</p> <p><a href="http://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28139">@Jon Limjap</a></p> <p>I've tried adding the third argument, and it makes no difference.</p> <hr> <p><a href="http://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <blockquote> <p>The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces)</p> </blockquote> <p>Wouldn't the <code>isdate()</code> check take care of this?</p> <p>I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days.</p> <hr> <p><a href="http://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <pre><code>select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 </code></pre> <hr> <p><a href="http://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@Brian Schkerke</a></p> <blockquote> <p>Place the CASE and ISDATE inside the CONVERT() function.</p> </blockquote> <p>Thanks! That did it.</p>
<p>Place the <code>CASE</code> and <code>ISDATE</code> inside the <code>CONVERT()</code> function.</p> <p><code> SELECT COUNT(*) FROM MyTable WHERE DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate) when 1 then lastUpdate ELSE '12-30-1899' end), getDate()) &lt; 31 </code></p> <p>Replace '<code>12-30-1899</code>' with the default date of your choice.</p>
Create an Attribute to Break the Build <p>OK, this kind of follows on from <a href="http://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method" rel="nofollow">my previous question</a>.</p> <p>What I would really like to do is create some sort of attribute which allows me to decorate a method that will <strong>break the build</strong>. Much like the <em>Obsolete("reason", true)</em> attribute, but without falsely identifying obsolete code.</p> <p><strong>To clarify</strong>: I dont want it to break the build on <em>ANY</em> F6 (Build) press, I only want it to break the build if a method decorated with the attribute is called somewhere else in the code. Like I said, <em>similar</em> to obsolete, but not the same.</p> <p>I know I am not alone in this, since <a href="http://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method#27796" rel="nofollow">other users want to use it for other reasons</a>. I have never created custom attributes before so it is all new to me!</p>
<p>If this is for XML serialization and NHibernate, where you want the parameterless constructor to be accessible (as is the case in the <a href="http://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method#27796" rel="nofollow">example</a> you referenced), then use a private or protected parameterless constructor for serialization, or a protected constructor for NHibernate. With the protected version, you are opening yourself up to inherited classes being able to call that code.</p> <p>If you don't want code calling a method, don't make it accessible.</p> <p>EDIT: To perhaps answer the deeper question, AFAIK the compiler only knows about three attributes: <a href="http://msdn.microsoft.com/en-us/library/aa664620(VS.71).aspx" rel="nofollow">Obsolete, Conditional, and AttributeUsage</a>. To add special handling for other attributes would require modifying the compiler.</p>
Multiple classes in a header file vs. a single header file per class <p>For whatever reason, our company has a coding guideline that states:</p> <p><code>Each class shall have it's own header and implementation file.</code></p> <p>So if we wrote a class called <code>MyString</code> we would need an associated <strong>MyStringh.h</strong> and <strong>MyString.cxx</strong>.</p> <p>Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable?</p> <p>[We code C++ and use GCC 3.4.4 as our everyday compiler]</p>
<h2>Overwhelmed by thousands lines of code?</h2> <p>Having one set of header/source files per class in a directory can seem overkill. And if the number of classes goes toward 100 or 1000, it can even be frightening.</p> <p>But having played with sources following the philosophy "let's put together everything", the conclusion is that only the one who wrote the file has any hope to not be lost inside. Even with an IDE, it is easy to miss things because <strong>when you're playing with a source of 20,000 lines, you just close your mind for anything not exactly refering to your problem.</strong></p> <p><i>Real life example: the class hierarchy defined in those thousand lines sources closed itself into a diamond-inheritance, and some methods were overridden in child classes by methods with exactly the same code. This was easily overlooked (who wants to explore/check a 20,000 lines source code?), and when the original method was changed (bug correction), the effect was not as universal as excepted.</i></p> <h2>Dependancies becoming circular?</h2> <p>I had this problem with templated code, but I saw similar problems with regular C++ and C code.</p> <p>Breaking down your sources into 1 header per struct/class lets you:</p> <ul> <li>Speed up compilation because you can use symbol forward-declaration instead of including whole objects</li> <li>Have circular dependencies between classes (§) (i.e. class A has a pointer to B, and B has a pointer to A)</li> </ul> <p>In source-controlled code, class dependencies could lead to regular moving of classes up and down the file, just to make the header compile. You don't want to study the evolution of such moves when comparing the same file in different versions.</p> <p><strong>Having separate headers makes the code more modular, faster to compile, and makes it easier to study its evolution through different versions diffs</strong></p> <p><i>For my template program, I had to divide my headers into two files: The .HPP file containing the template class declaration/definition, and the .INL file containing the definitions of the said class methods.</p> <p>Putting all this code inside one and only one unique header would mean putting class definitions at the begining of this file, and the method definitions at the end.</p> <p>And then, if someone needed only a small part of the code, with the one-header-only solution, they still would have to pay for the slower compilation.</i></p> <p>(§) Note that you can have circular dependencies between classes if you know which class owns which. This is a discussion about classes having knowledge of the existence of other classes, not shared_ptr circular dependencies antipattern.</p> <h2>One last word: Headers should be self-sufficients</h2> <p>One thing, though, that must be respected by a solution of multiple headers and multiple sources.</p> <p><strong>When you include one header, no matter which header, your source must compile cleanly.</strong></p> <p>Each header should be self-sufficient. You're supposed to develop code, not treasure-hunting by greping your 10,000+ source files project to find which header defines the symbol in the 1,000 lines header you need to include just because of <em>one</em> enum.</p> <p>This means that either each header defines or forward-declare all the symbols it uses, or include all the needed headers (and only the needed headers).</p>
Can I maintain state between calls to a SQL Server UDF? <p>I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. </p> <p>I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. </p> <p>Currently my script looks like this: </p> <pre> declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id </pre> <p>But I would like it to look like this: </p> <pre> --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) </pre> <p>Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. </p> <p>We're using SQL Server 2005 at the moment. </p> <p><em>edits for clarification:</em></p> <p>Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. </p> <p>The actual sproc isn't prefixed with sp_, fixed the example code. </p> <p>In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db. </p>
<p>If you have 2 users hitting it at the same time they will get the same id. Why didn't you use an id table with an identity instead, insert into that and use that as the unique (which is guaranteed) id, this will also perform much faster</p> <blockquote> <blockquote> <p>sp_getNextID </p> </blockquote> </blockquote> <p>never ever prefix procs with sp_, this has performance implication because the optimizer first checks the master DB to see if that proc exists there and then th local DB, also if MS decide to create a sp_getNextID in a service pack yours will never get executed</p>
Proxy which requires authentication with Android Emulator <p>Has anybody managed to get the Android Emulator working behind a proxy which requires authentication?</p> <p>I've tried setting the -http-proxy argument to </p> <pre><code>http://DOMAIN/USERNAME:PASSWORD@IP:PORT </code></pre> <p>but am having no success. </p> <p>I've tried following the docs to no avail. I've also tried the <code>-verbose-proxy</code> setting but this no longer seems to exist.</p> <p>Any pointers?</p>
<p>I Managed to do it in the Adndroid 2.2 Emulator.</p> <pre><code>Go to "Settings" -&gt; "Wireless &amp; Networks" -&gt; "Mobile Networks" -&gt; "Access Point Names" -&gt; "Telkila" </code></pre> <p>Over there set the proxy host name in the property "Proxy" and the Proxy port in the property "Port"</p>
Corporate-Friendly Open Source Licenses <p>What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product?</p>
<p>I recommend the Apache License (specifically, version 2). It is not a “copy left” license and it addresses several matters that are important to established companies and their lawyers.</p> <p>“Copy left” is the philosophy of the free software foundation requiring anything incorporating the licensed opens source code to also be licensed as open source. That philosophy is regarded as poison by established companies that want to keep their products proprietary.</p> <p>Aside from not having “copy left” provisions, the Apache license specifically addresses the grant of rights from project contributors and it expressly addresses the fact that modern companies are typically made up for more than one legal entity (for example, a parent company and its subsidiaries). Most open source licenses don’t address these points.</p> <p>Whatever license you choose, if you want your code to be “corporate friendly,” in the sense that you want it to be incorporated into commercial, non-open source products, it is essential that you avoid GPL and other “copy left” type licenses. While it would be best to consult with your own lawyer before investing time or money in a project for which this is an important factor, a quick shorthand for licenses that are and are not “copy left” can be found on the Free Software Foundation’s website. They identify which licenses they don’t find meet their standards as “copy left.” The ones FSF rejects are most likely the ones that will be corporate friendly in this sense.</p> <p>(Although the question didn’t ask this, it is worth mentioning that, with very few exceptions, even GPL and other “copy left” type licenses are perfectly corporate friendly if they are only used internally by the commercial entities and not incorporated into their products.)</p>
Is it possible to use nHibernate with Paradox database? <p>Is it possible to configure nHibernate to connect to Paradox database (<code>*.db</code> files)?</p>
<p>Yes, sort of. </p> <p>There is no support included in the trunk, you need to write your own dialect. Or you can port the <a href="http://www.hxtt.com/hibernate.html" rel="nofollow">Paradox dialect created for Hibernate</a>.</p>
Why is it bad practice to make multiple database connections in one request? <p>A discussion about Singletons in <strong>PHP</strong> has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient?</p> <p>How about some answers (with evidence, folks) from some people in the know?</p>
<p>Database connections are a limited resource. Some DBs have a very low connection limit, and wasting connections is a major problem. By consuming many connections, you may be blocking others for using the database.</p> <p>Additionally, throwing a ton of extra connections at the DB doesn't help anything unless there are resources on the DB server sitting idle. If you've got 8 cores and only one is being used to satisfy a query, then sure, making another connection might help. More likely, though, you are already using all the available cores. You're also likely hitting the same harddrive for every DB request, and adding additional lock contention.</p> <p>If your DB has anything resembling high utilization, adding extra connections won't help. That'd be like spawning extra threads in an application with the blind hope that the extra concurrency will make processing faster. It <em>might</em> in some certain circumstances, but in other cases it'll just slow you down as you thrash the hard drive, waste time task-switching, and introduce synchronization overhead.</p>
Windows Mobile - What scripting platforms are available? <p>We have a number of users with Windows Mobile 6 and need to apply minor changes. eg. update a registry setting. One option is push and execute an executable file using our device management software.</p> <p>I'd like this to be a little more friendly for the admins who are familiar with scripting in VBScript/JScript etc. What are the options for scripting on Windows Mobile devices?</p>
<p>I work on windows mobile full time and have never really come across a good Windows Mobile scripting implementation unfortunately. For some reason MS has never seen the need for it. For example, even though you can actually get a command console on WM, it does not support running batch files, even though all the commands are still there and it would be relatively easy. There is definitely not a VBScript engine I've ever heard of nor JScript. There is <a href="http://pythonce.sourceforge.net/" rel="nofollow">PythonCE</a> but the WM specific support is minimal and you don't get access to a lot of WM only things.</p> <p>Also, I've done a lot of work with a company called <a href="http://soti.net/" rel="nofollow">SOTI</a> which has a product called MobiControl that does incorporate a basic scripting engine. Though most of the commands are specific to their system and actually have to be run from a desktop-side management console.</p> <p>Given all of the times I have tried to find a good scripting engine for WM myself you would think I would've just written one ;)</p> <p>So, sorry, but the basic answer is <em>no</em>, there is not a scripting engine available for VB in the context that you specified.</p>
Scrum - How to get better input from the functional/commercial team <p>We are a small team of 3 developers (2 experienced but new to this particular business sector) developing a functionally complex product. We're using Scrum and have a demo at the end of each sprint. Its clear that the functional team have plenty of ideas but these are not well communicated to the development team and the demo poses more questions than answers. </p> <p>Have you any recommendations for improving the the quality of input from the functional people?</p> <p><strong>Further info:</strong> I think part of the problem is that there are no <em>specs</em> or User Stories as such. Personally I think they need to be writing down some sort of requirements - what sort of things should they be writing down and to what complexity given its an agile process?</p> <p>TIA</p>
<p>Have you tried working with your customer to define / formulate <strong>acceptance tests</strong>?<br /> Using something like Fit to come up with these tests - would result in better specs as well as force the customer to think about what is really required. The icing on the cake is instant-doc-executable specs at the end of this process.</p> <p>That is of course, if your customers are available and open to this approach. Give it a try!</p> <p>If not (and that seems to be the majority - because it is less work) - calendar flash 'em - schedule meetings/telecons every week until they sing like canaries :) +1 to Dana </p>
Guide to choosing between REST vs SOAP services? <p>Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other.</p>
<p><a href="http://www.prescod.net/rest/rest_vs_soap_overview/">Google first hit</a> seems pretty comprehensive.</p> <p>I think the problem here is there are too many advocates of one or the other, may be better of googling and getting more of a handle of the pro's/con's yourself and making your own decision.</p> <p>I know that sounds kinda lame, but ultimately these sort of design decisions fall down to the developer/architect working on it, and <strong>99% of the time, the problem domain will be the deciding factor</strong> (or at least it should be), not a guide on the net.</p>
SharePoint SPContext.List in a custom application page <p>I have a custom SharePoint application page deployed to the _layouts folder. It's a custom "new form" for a custom content type. During my interactions with this page, I will need to add an item to my list. When the page first loads, I can use SPContext.Current.List to see the current list I'm working with. But after I fill in my form and the form posts back onto itself and IsPostBack is true, then SPContext.Current.List is null so I can't find the list that I need to add my stuff into.</p> <p>Is this expected?</p> <p>How should I retain some info about my context list across the postback? Should I just populate some asp:hidden control with my list's guid and then just pull it back from that on the postback? That seems safe, I guess.</p> <p>FWIW, this is the MOSS 2007 Standard version.</p>
<p>I would be surprised if you could do something in a _Layouts file that you can't do in a forms template. You have pretty much the same technologies at your disposal. </p> <p>Looking at the way SharePoint works with ListItems and Layouts pages (for example "Manage Permissions" on a list item), I can see that they pass some variables in via querystrings: ?obj={76113B3A-FABA-4389-BC85-4BB2CC5AB423},6,LISTITEM&amp;List={76113B3A-FABA-4389-BC85-4BB2CC5AB423}</p> <p>Perhaps they grab the context back each time programmatically using these values.</p>
Linq To SQL: Can I eager load only one field in a joined table? <p>I have one table "orders" with a foreing key "ProductID".</p> <p>I want to show the orders in a grid with the <strong>product name</strong>, without <strong>LazyLoad</strong> for better performance, but I if use <strong>DataLoadOptions</strong> it retrieves <strong>all</strong> Product fields, which seams like a <strong>overkill</strong>.</p> <p>Is there a way to retrieve <strong>only</strong> the Product name in the first query? Can I set some attribute in the DBML?</p> <p>In this <a href="http://visualstudiomagazine.com/listings/list.aspx?id=566" rel="nofollow">table</a> says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means.</p> <p><strong>Edit</strong>: Changed the title, because I'm not really sure the there is no solution.<br /> Can't believe no one has the same problem, it is a very common scenario.</p>
<p>What you are asking for is a level of optimisation the linq-to-sql does not provide. I think your best bet is to create a query that returns exactly the data you want, possibly as an anonymous type:</p> <pre><code>from order in DB.GetTable&lt;Orders&gt;() join product in DB.GetTable&lt;Products&gt;() on order.ProductID = product.ID select new { ID = order.ID, Name = order.Name, ProductName = product.Name }; </code></pre>