instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>The VSTO bit I understand. Visual Studio has the project templates to get you started with creating nice .NET based add-ins.</p> <p>But where is VSTA? I installed the SDK but it seems to be gears towards adding extensibility to your own applications.</p> <p>I had thought that VSTA was like the new VBA for Office 2007. Infopath 2007 seems to be VSTA enabled but I cannot seem to find where Excel 2007 is also VSTA enabled.</p> <p>Am I missing something ?</p>
<p>As I understand it, VSTA is not a 'new VBA' nor built into Office 2007, but a separate 'Super-VBA with .NET' that must be licensed from Summit, and distributed as part of an external application. I think it's just targeted at ISVs wishing to extend Office, but the blurb about it also contains this gem:</p> <blockquote> <p>Perhaps the feature most applauded by enterprise BDMs and SI’s is that VSTA customizations are seamlessly opened by any version of Visual Studio enabling professional developers to continue to enhance applications originally created by end user developers – a feature requested by many enterprises because applications often grow in sophistication over time.</p> </blockquote> <p>I've not bothered googling BDMs and SI means le Système International d'Unités to me, but I took this mean that you can take the horrible mess of excel VBA that your traders used to turn worthless morgages into goldmine CDOs (and then bailouts), and your 'real developers' can open it in Visual Studio and sort the mess out (or just quit...).</p> <p>also VBA and VSTA can exist together: <a href="http://blogs.msdn.com/vsta/archive/2006/07/31/684514.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vsta/archive/2006/07/31/684514.aspx</a></p>
<p>If I understand correctly, VSTA is a new technology that provides a "standard" short-cut route to extensibility for application vendors. So it may appear in Office apps in the future or it may not, but it's not there now.</p> <p>If it becomes supported by Excel, Word and the like, then the UI (Visual Studio Shell?) should be distributed as part of the package.</p> <p>But I may be miles off-base...</p>
32,080
<p>I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.</p> <p>I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.</p> <p>As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.</p> <p>What configuration gotchas should I look out for with this type of setup?</p>
<p>I would probably just move all the apps to mod_rails, as the performance seems comparable to Mongrel and there's less administration overhead.</p> <p>With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing:</p> <pre><code>&lt;Directory "/var/www/app/current/public"&gt; Options FollowSymLinks AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; </code></pre> <p>Aside from that, if you know how to configure Apache, mod_rails is very painless.</p>
<p>Ended up moving everything to mod_rails.</p> <p>Works like a champ!</p>
13,576
<p>I know that in the end it, can't be done.</p> <p>But, what are the options to: </p> <p>&nbsp; a) limit the options for persons to create multiple accounts,<br> &nbsp; b) increase the chance of detecting multiple accounts / person </p> <p>for a blog-like web service?<br> (people can sign up for their own blog)</p> <p><strong>Update:</strong><br> I think the 'limit the options' has been answered nicely. (there is no reliable method, but we can raise the bar)<br> However, I would still like to know what other options there are to detect multiple accounts?</p>
<p>I'm assuming you're talking about a free service? I can't think of any ways that don't either have serious drawbacks or would be trivial to defeat. Things like setting a cookie, requiring a unique e-mail address are easy to defeat.</p> <p>Requiring a unique IP address is not foolproof but might work to some degree, up to the point that you have lots of users and get complaints from people behind proxies.</p> <p>The best ways are to charge money or require people provide some kind of personal information, like real name/phone/address that you verify, or a CC number, but that's invasive (then again maybe you only want serious users who are willing to provide this sort of info).</p> <p>I guess I would turn the question around and ask "Why don't you want to let people have multiple accounts?"</p> <p>There may be some other ways of mitigating whatever your underlying reason is, i.e. if you're worried about lots of orphaned blogs you could scan for a period of inactivity and disable them or at least schedule them to be looked at by a human. If you're worried about spam blogs you could periodically scan all blog content for spammy stuff. If you're worried about bots and are using some generic software like WordPress, change the names of the form variables and otherwise protect your forms from bots.</p> <p>Definitely think of other ways of dealing with the problem, because you are not going to be able to block people from registering multiple accounts if it's a typical free service like Blogger.</p> <p>As for detecting multiple accounts by one person, the first thing you need to do is have a log file store complete data on every user login (username, timestamp, IP, user-agent etc.), that you can then analyze later. I'll list a few things to look out for, but just by poring over the log file you will likely discover other patterns. Some ideas of things to look for are:</p> <ul> <li>Set a tracking cookie (i.e. random hash) and log its value on login, look for multiple logins from the same cookie value</li> <li>Logins from same IP address/user-agent combination</li> <li>Logins from same IP address only (less reliable than the previous two bullets)</li> <li>Accounts with email addresses from free webmail services (Gmail etc.)</li> <li>Accounts with same password</li> </ul> <p>If you're worried about spam blogs, you could try doing some analysis of blog content, i.e. extract all the <code>&lt;a href&gt;</code>s and look for correlations between blogs. You could run the blog content itself though something like SpamAssassin or otherwise filter for spammy words like "viagra" and "rolex."</p>
<p>One common option is to verify the persons identity through their e-mail. Actually make them respond to an e-mail sent to their account. Some sites take this a step further and don't allow addresses from domains such as yahoo, g-mail, hotmail, etc ...</p>
20,535
<p>I have a form whose controls I want to enable/disable depending on the values in a ComboBox control. This ComboBox control is linked, like all the other controls in the form, to a table. Inside the ComboBox's Change event, I placed the code that enables/disables the other controls.</p> <p>The problem I have is that when I open the form, the controls are not enabled/disabled. I have to re-choose the ComboBox value to make all other controls enable or disable.</p> <p>One thing I noticed is that the RecordSet control inside the ComboBox often does not change to the value shown in the value property of the ComboBox.</p> <p>I tried using <br> <code>combobox.recordset.filter = "Key = " &amp; combobox.value</code><br> but I get the error <br> <code>Operation is not supported for this type of object.</code></p> <hr> <h2>Update</h2> <p>I think my problem has to do more in how I'm accessing the values in the combobox.recordset. I was under the impression that combobox.recordset held the value received from the table. But, it seems to hold the first record from the recordsource.</p> <p>I'm guessing that I will need to search those values I need by using another recordset object.</p>
<p>Most Access control events are not triggered by programmatic changes to the control. You may wish to call the code to enable the control(s) from the load event of the form.</p> <p>You do not mention the version of Access that you are using, but I do not believe that any version has a Recordset property for comboboxes. </p> <p>Did you wish to set the combobox to a specific value?</p>
<p>Can you explain what type of combobox you have and what you want to do, please? For example, have you an unbound combobox that is used to find records for your form, or have you a bound combobox that is used to update fields in a table? This is controlled by the RowSource and ControlSource properties, Comboboxes do not have a recordset property. An unbound combobox will not have a value when you open the form, nor will the value change when you move from record to record, but it is easy enough to assign a value using the current event. </p> <p>EDIT I am still not clear on what you want to do. Are you having problems modifying the controls when an option is chosen, as per your comment, or are you having problems setting the value of the combo when the form opens? Do you want to change the RowSource of the combo, perhaps, as implied by your original post?</p>
34,207
<p>I can't seem to find the _findfirst / findfirst, _findnext / findnext API on gcc for Linux, and would actually rather use the Standard Template Library (STL) for that if it is included there.</p> <p>Does anyone know what API there is available for listing files in a directory under Linux for C++ (gcc)?</p>
<p>Check out the <a href="http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm" rel="noreferrer">Boost.Filesystem</a> library.</p> <p>In particular, the <a href="http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/reference.html#Class-template-basic_directory_iterator" rel="noreferrer">basic_directory_iterator</a>.</p>
<p>The STL does not, yet, have functions for listing files in a directory. But it does have functions for opening files you are already aware of.</p> <p>Aside from Boost.Filesystem, there is also <a href="http://stlsoft.org" rel="nofollow noreferrer">STLSoft</a></p>
29,145
<p>I find that quite often Visual Studio memory usage will average ~150-300 MB of RAM.</p> <p>As a developer who very often needs to run with multiple instances of Visual Studio open, are there any performance tricks to optimize the amount of memory that VS uses?</p> <p>I am running VS 2005 with one add-in (TFS)</p>
<p>From <a href="https://web.archive.org/web/20160817172313/http://geekswithblogs.net:80/sdorman/archive/2008/08/28/visual-studio-optimizations.aspx" rel="nofollow noreferrer">this blog post</a>:</p> <blockquote> <p>[...]<br /> These changes are all available from the Options dialog (Tools –&gt; Options):</p> <p><strong>Environment</strong></p> <ul> <li><em>General</em>: <ul> <li>Disable “Animate environment tools”</li> </ul> </li> <li><em>Documents</em>: <ul> <li>Disable “Detect when file is changed outside the environment”</li> </ul> </li> <li><em>Keyboard</em>: <ul> <li>Remove the F1 key from the Help.F1Help command</li> </ul> </li> <li><em>Help\Online</em>: <ul> <li>Set “When loading Help content” to “Try local first, then online” or “Try local only, not online”</li> </ul> </li> <li><em>Startup</em>: <ul> <li>Change the “At startup” option to “Show empty environment”</li> </ul> </li> </ul> <p><strong>Projects and Solutions</strong></p> <ul> <li><em>General</em>: <ul> <li>Disable “Track Active Item in Solution Explorer”</li> </ul> </li> </ul> <p><strong>Text Editor</strong></p> <ul> <li><em>General</em> (for each language you want): <ul> <li>Disable “Navigation bar” (this is the toolbar that shows the objects and procedures drop down lists allowing you to choose a particular object in your code.</li> <li>Disable “Track changes”</li> </ul> </li> </ul> <p><strong>Windows Forms Designer</strong></p> <ul> <li><em>General</em>: <ul> <li>Set “AutotoolboxPopulate” to false.</li> <li>Set “EnableRefactoringOnRename” to false.</li> </ul> </li> </ul> </blockquote>
<p>By uninstalling (and re-installing) Visual Assist the problem got solved for me.</p>
20,328
<p>I'm trying to get all property names / values from an Outlook item. I have custom properties in addition to the default outlook item properties. I'm using redemption to get around the Outlook warnings but I'm having some problems with the GetNamesFromIDs method on a Redemption.RDOMail Item....</p> <p>I'm using my redemption session to get the message and trying to use the message to get the names of all the properties.</p> <pre><code>Dim rMessage as Redemption.RDOMail = _RDOSession.GetMessageFromID(EntryID, getPublicStoreID()) Dim propertyList As Redemption.PropList = someMessage.GetPropList(Nothing) For i As Integer = 1 To propertyList.Count + 1 Console.WriteLine(propertyList(i).ToString()) Console.WriteLine(someMessage.GetNamesFromIDs(________, propertyList(i))) Next </code></pre> <p>I'm not totally sure what to pass in as the first parameter to getNamesFromIDs. The definition of GetNamesFromIDs is as follows:</p> <pre><code>GetNamesFromIDs(MAPIProp as Object, PropTag as Integer) As Redemption.NamedProperty </code></pre> <p>I'm not totally sure what should be passed in as the MAPIProp object. I don't see this property referenced in the documentation. <a href="http://www.dimastr.com/redemption/rdo/MAPIProp.htm#properties" rel="nofollow noreferrer">http://www.dimastr.com/redemption/rdo/MAPIProp.htm#properties</a></p> <p>Any help or insight would be greatly appreciated.</p>
<p>Ruby on Rails will do simple CRUD operations <strong>very</strong> easily - although doing more than that can be a little more complex (would require some reading about RoR's way of doing things). The latest version of Rails automatically uses sqlite databases, and in fact the whole database, and CRUD GUI code can be created with one command (<code>scaffold</code>).</p> <p>If this is to be deployed then that can be a bit more difficult (although I hear that Capistrano is good) - but for local or intranet use then that's what I'd do.</p>
<p>C# and WPF, it;s preatty easy and good to know (I've been playing with it for 1 week and fully wrote a twitter client in a few hours.</p> <p>now Cocoa, and the interface Builder, that is a cool approach even for a simple app.</p>
31,185
<p>I am using MVC architecture for a GUI application. The model class has some C functions. One of the C functions calls some methods of Objective-C class. I call those methods using an object of that class. The strange thing happening is that methods previously to the an xyz method are called perfectly but when that xyz method is called, that method and the methods after it aren't getting executed. I don't get any errors. So can't figure out what exactly is happening. Any ideas as to what might be the reason for this?</p>
<p>As Marc points out, you're probably using a reference to the OBJC object that is un-initialised outside the objective-c scope.</p> <p>Here's a working sample of C code calling an ObjC object's method:</p> <pre><code>#import &lt;Cocoa/Cocoa.h&gt; id refToSelf; @interface SomeClass: NSObject @end @implementation SomeClass - (void) doNothing { NSLog(@"Doing nothing"); } @end int otherCfunction() { [refToSelf doNothing]; } int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SomeClass * t = [[SomeClass alloc] init]; refToSelf = t; otherCfunction(); [pool release]; } </code></pre>
<p>There's a simple way to do this:</p> <pre><code>@implementation // Define a object ClassName *thisClass; </code></pre> <p>and then init with self</p> <pre><code>thisClass = self; </code></pre> <p>You can use any var and methods in C-Method</p>
39,201
<p>I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has</p> <pre><code>font-size: 11px; font-family: Arial, Helvetica, sans-serif; </code></pre> <p>I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms:</p> <pre><code>letter-spacing: -1.5px; </code></pre> <p>but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it.</p> <p>The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!</p>
<p>A List Apart has a pretty <a href="http://www.alistapart.com/articles/howtosizetextincss" rel="nofollow noreferrer">comprehensive article on sizing fonts in CSS</a>. Their conclusion is to use "<code>ems</code>" to size text, since it generally gives the most consistent sizing across browsers. They make no direct mention of different OSes, but you should try using ems. It might solve your problem.</p>
<p>I find the easiest way to solve font sizing problems between browsers is to simply leave room for error. Make divs slightly larger or fonts slightly smaller so that platform variation doesn't change wrapping or clipping considerably.</p>
6,977
<p>I am writing a webpage in C# .NET. In javascript there is a function called GetElementsByTagName... this is nice for javascript invoked from the .aspx page. My question is, is there any way I can have this kind of functionality from my C# code-behind?</p> <p>--</p> <p>The scenario for those curious: I used an asp:repeater to generate a lot of buttons, and now I'm essentially trying to make a button that clicks them all. I tried storing all the buttons in a list as I created them, but the list is getting cleared during every postback, so I thought I could try the above method.</p>
<p>FindControl(), or iterate through the controls on the page...</p> <pre><code>For each ctl as Control in Me.Controls If ctl.Name = whatYouWant Then do stuff Next 'ctl </code></pre> <p>--If you are creating the controls, you should be setting their ID's </p> <pre><code>Dim ctl as New Control() ctl.ID = "blah1" </code></pre> <p>etc...</p>
<p>Whenever you do any postback, <em>everything</em> is recreated, including your databound controls. </p> <p>If your list is gone, so are the button controls. Unless, of course, you've recreated them, and in that case you should have recreated the list as well.</p>
15,732
<p>I'm writing a web application that will have "plugins". The plugins will be .DLL files which will export their functionality through predefined interfaces 'n stuff. All the .DLL files are in a folder called "Plugins", and the ASP.NET application loads them all upon startup (by using Assembly.LoadFrom).</p> <p>The problem is that when developing, these plugins will change fairly often (all the functionality is in the plugins, the website itself is just a skeleton). Thus, I need a way to automatically restart the application when the .DLL files change.</p> <p>How do I do that?</p>
<p>IF the plugins directory is under your Bin directory, the web app will automatically be restarted when anything changes.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow noreferrer">FileSystemWatcher</a> class is a general solution to these kind of problems, and <code>HttpRuntime.UnloadAppDomain();</code> is one way to restart your app. I think more research/explanation is required: there are many possible solutions.</p> <p><strong>Edit</strong>: Probling Paths. Nice answer.</p>
42,800
<p>Out of the box SSRS reports cannot have data exposed in the page header. Is there a way to get this data to show?</p>
<p>One of the things I want in my reports is to have nice headers for my reports. I like to have a logo and the user's report parameters along with other data to show to give more information for the business needs the report needs to clarify. One of the things that Microsoft SQL Server 2005 Reporting Services cannot do natively is show data from a Dataset in the header. This post will explain how to work around this and how easy it is.</p> <p>Create the Report Server Project in the Business Intelligence Projects section and call it AdventureWorksLTReports. I use the AdventureWorksLT sample database from CodePlex.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb.png">alt text http://www.cloudsocket.com/images/image-thumb.png</a></p> <p>Next show the Page Header by right clicking in the Report area with the designer.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb1.png">alt text http://www.cloudsocket.com/images/image-thumb1.png</a></p> <p>The Page Header will appear. If you want to show the Page Footer this can be accessed from the same menu as the Page Header.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb2.png">alt text http://www.cloudsocket.com/images/image-thumb2.png</a></p> <p>I created a stored procedure that returns data for the Sales Order to be presented in the Page Header. I will show the following information about the Sales Order in the Page Header:</p> <ul> <li>Order Date</li> <li>Sales Order Number</li> <li>Company</li> <li>Sales Person</li> <li>Total Due</li> </ul> <p>I create a TextBox for each of my data fields in the Page Header along with a TextBox for the corresponding label. Do not change the Expression in the TextBoxes that you want the Sales Order data in.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb3.png">alt text http://www.cloudsocket.com/images/image-thumb3.png</a></p> <p>In the Report Body, place a TextBox for each data field needed in the Page Header. In the Visibility for each TextBox, select True for Hidden. This will be the placeholder for the data needed in the Page Header.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb4.png">alt text http://www.cloudsocket.com/images/image-thumb4.png</a></p> <p>Your report should look similar to the screenshot shown below.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb5.png">alt text http://www.cloudsocket.com/images/image-thumb5.png</a></p> <p>The last step and most important is to reference the Hidden TextBox in the TextBoxes located in the Page Header. We use the the following Expression to reference the needed TextBoxes:</p> <p>=ReportItems!.Value</p> <p>Your report should now look similar to the following:</p> <p><a href="http://www.cloudsocket.com/images/image-thumb6.png">alt text http://www.cloudsocket.com/images/image-thumb6.png</a></p> <p>Your Report preview should now have the Sales Order Header data in the Report Header.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb7.png">alt text http://www.cloudsocket.com/images/image-thumb7.png</a></p>
<p>Here are two possible <strong>workarounds</strong>:</p> <ol> <li><p>You can place the databound field within the body of the report as a hidden textbox, and then in the header place another textbox with it's value pointed at the the one hidden within the body.</p></li> <li><p>Try using report parameters to store the data, and use those parameters to access the data in the header.</p></li> </ol>
8,940
<p>The title pretty much says it all. I'm using a TClientDataset to store an array of objects, and one of the objects has a member defined as a <strong>set of</strong> an enumerated type. As I understand it, Delphi sets are bitfields whose size can vary from 1 to 32 bytes depending on how much data they contain, and Delphi doesn't define a TSetField. What sort of field should I use to load this value into?</p>
<p>You could use a TBytesField or a TBlobField</p> <p>ClientDataSet1MySet: TBytesField, Size=32</p> <pre><code>var MySet: set of Byte; Bytes: array of Byte; begin MySet := [1, 2, 4, 8, 16]; // Write Assert(ClientDataSet1MySet.DataSize &gt;= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1MySet.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1MySet.SetData(@Bytes[0]); ClientDataSet1.Post; // Read SetLength(Bytes, ClientDataSet1MySet.DataSize); if ClientDataSet1MySet.GetData(@Bytes[0]) then Move(Bytes[0], MySet, SizeOf(MySet)) else MySet := []; // NULL end; </code></pre>
<blockquote> <blockquote> <p>Based on the example of Andreas, but made somewhat simpler and clearer IMHO.</p> </blockquote> </blockquote> <p>Tested on XE2</p> <p>You could use a TBytesField or a TBlobField</p> <p>ClientDataSet1MySet: TBytesField, Size=32</p> <p>1) Writing </p> <pre><code>var MySet: set of Byte; Bytes: TBytes; begin MySet := [0]; // Write Assert(ClientDataSet1Test.DataSize &gt;= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1Test.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1Test.AsBytes := Bytes; ClientDataSet1.Post; end; </code></pre> <p>2) Reading</p> <pre><code>var MyResultSet: set of Byte; begin Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize); end; </code></pre>
45,235
<p>I produce a report as an CSV file. When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly.</p> <p>For example, if the CSV file contains</p> <pre><code>...,005,... </code></pre> <p>Then Excel shows it as 5. Is there a way to override this and display 005?</p> <p>I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it.</p> <p>I use Excel 2003.</p>
<p>There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.</p> <p>My preference is the first option.</p> <p><strong>Option 1 – Change the data in the file</strong></p> <p>You could change the data in the .csv file as follows ...,<strong>=”005”</strong>,... This will be displayed in Excel as ...,<strong>005</strong>,...</p> <p>Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting</p> <p><strong>Option 2</strong> – Format the data</p> <p>If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format <strong>000</strong></p> <p><strong>Option 3</strong> – Change the file extension to .dif (Data interchange format)</p> <p>Change the file extension and use the file import wizard to control the formats. Files with a .dif extension are automatically opened by Excel when double clicked on.</p> <p><em>Step by step:</em></p> <ul> <li>Change the file extension from <strong>.csv</strong> to <strong>.dif</strong></li> <li>Double click on the file to open it in Excel.</li> <li>The 'File Import Wizard' will be launched.</li> <li>Set the 'File type' to 'Delimited' and click on the 'Next' button.</li> <li>Under Delimiters, tick 'Comma' and click on the 'Next' button.</li> <li>Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.</li> <li>Click on the finish button, the file will be opened by Excel with the formats that you have specified.</li> </ul>
<p>When opening a CSV, you get the text import wizard. At the last step of the wizard, you should be able to import the specific column as text, thereby retaining the '00' prefix. After that you can then format the cell any way that you want.</p> <p>I tried with with Excel 2007 and it appeared to work.</p>
16,612
<p>I'd like to drop a user in a SQL Server script but I'll need to test for existence first or I'll get script errors. When dropping tables or stored procs, I check the sysobjects table like so:</p> <pre><code>IF EXISTS ( SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[up_SetMedOptions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) Drop Procedure up_SetMedOptions; GO </code></pre> <p>What is the corollary for checking for a user? Note that I am NOT asking about a database login to the server! The question pertains to a User in a specific database.</p>
<p>SSMS scripts it in the following way:</p> <p>For SQL 2005/2008 and later:</p> <pre><code>IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'username') DROP USER [username] </code></pre> <p>For SQL 2000:</p> <pre><code>IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username') EXEC dbo.sp_revokedbaccess N'username' </code></pre>
<p>The code below worked for me.</p> <pre><code>IF EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyUserName') DROP LOGIN [MyUserName] </code></pre>
46,417
<p>Here's a problem I keep running into:</p> <p>I have a lot of situations where I need to display some text with a styled container like so:</p> <pre><code>&lt;mx:Canvas&gt; &lt;mx:Text text="{text}" left="5" verticalCenter="0" right="5" /&gt; &lt;/mx:Canvas&gt; </code></pre> <p>As you can see - the text in constrained by the left and right margins of the canvas and I have not specified a height for the text control because I want it to grow vertically when I add text to it. Reason being - if there is one line of text I want it to display in the center of the canvas but if there are two or three lines of text I want the text control to show those two or three lines of text.</p> <p>What keeps happening however, is that it will only display one line of text - no matter how many times I call invalidateSize() on it or the container. What do I do?</p> <p>CAVEAT: The canvas height and width is set by the component that instantiates it (this is all wrapped up in a custom component) so I can't explicitly set the width or height of the text control...</p> <p>NOTE: Ok, maybe it's an easy fix because as I was typing this question I figured it out - but, here's a chance to answer an easy question!?</p>
<p>The Text component needs a width if you want it to automatically wrap for you. If you used a string with newlines in it it will work grow as you expected without a width. For you, use:</p> <p><strong>Edit:</strong> Ok, you want it centered in a canvas of varying size. Then you can:</p> <pre><code>&lt;mx:HBox width="500" paddingLeft="5" paddingRight="5"&gt; &lt;mx:Spacer width="100%" /&gt; &lt;mx:Text width="100%" text="{text}" /&gt; &lt;mx:Spacer width="100%" /&gt; &lt;/mx:HBox&gt; </code></pre>
<p>Take a look at the TextArea component.</p>
23,758
<p>I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons:</p> <ul> <li>JavaScript Shell from <a href="https://www.squarefree.com/bookmarklets/webdevel.html" rel="nofollow noreferrer">https://www.squarefree.com/bookmarklets/webdevel.html</a></li> <li>Firefox Dom Inspector</li> <li>Firebug</li> <li>Greasemonkey</li> <li>Stylish</li> </ul> <p>I plan to use <a href="http://www.hacksrus.com/~ginda/venkman/" rel="nofollow noreferrer">Venkman Javascript debugger</a> as well as <a href="https://github.com/pivotal/jsunit" rel="nofollow noreferrer">jsunit</a> and <a href="http://jslint.com/" rel="nofollow noreferrer">js-lint</a>.</p> <p>For programming I'm stick with vim.</p> <p>So what other tools do you use when developing JavaScript?</p>
<p>I use both Firefox and IE for Web Development and a few add-ons in each:</p> <p><strong>Firefox:</strong></p> <ul> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a></li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="nofollow noreferrer">Web Developer Toolbar</a></li> </ul> <p><strong>Internet Explorer:</strong></p> <ul> <li><a href="http://www.microsoft.com/en-us/download/details.aspx?id=18359" rel="nofollow noreferrer">IE Developer Toolbar</a></li> <li><a href="http://www.fiddlertool.com/" rel="nofollow noreferrer">Fiddler</a></li> <li>Visual Studio for JS Debugging</li> </ul>
<p>A couple more::</p> <ol> <li>IE Explorer Toolbar </li> <li>Firefox Developer Toolbar </li> </ol>
5,470
<p>Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.</p>
<p>Following the approach <a href="https://stackoverflow.com/questions/308650/select-x-most-recent-non-consecutive-days-worth-of-data#308670">Tony Andrews</a> suggested, here is a way of doing it in T-SQL:</p> <pre><code>SELECT Value, ValueDate FROM Data WHERE ValueDate &gt;= ( SELECT CONVERT(DATETIME, MIN(TruncatedDate)) FROM ( SELECT DISTINCT TOP 5 CONVERT(VARCHAR, ValueDate, 102) TruncatedDate FROM Event ORDER BY TruncatedDate DESC ) d ) ORDER BY ValueDate DESC </code></pre>
<p>I don't know the SQL Server syntax, but you need to:</p> <p>1) Select the dates (with time component truncated) in descending order</p> <p>2) Pick off top 5</p> <p>3) Obtain 5th value</p> <p>4) Select data where the datetime >= 5th value</p> <p>Something like this "pseudo-SQL":</p> <pre><code>select * from data where datetime &gt;= ( select top 1 date from ( select top 5 date from ( select truncated(datetime) as date from data order by truncated(datetime) desc ) order by date ) ) </code></pre>
39,762
<p>Has anyone managed to get PDFCreator running on an ASP.NET 2.0 website ?</p> <p>On my development machine with Visual Studio webserver, it works just fine after following this procedure :</p> <ul> <li>create a com interop dll with tlbimp</li> <li>reference this dll</li> <li>write some code to use it</li> </ul> <p>However, when I deploy it to our test server, it fails miserably with this error :</p> <pre><code>Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005. </code></pre> <p>And I can't find this component in DCOMCNFG.msc.</p> <p>Our server configuration : </p> <ul> <li>Windows 2003</li> <li>Asp.net 2.0</li> <li>MS Office XP</li> <li>PDFCreator 0.9.0</li> </ul>
<p>The following Microsoft Knowledgebase article describes the problem and a solution:</p> <p><a href="http://support.microsoft.com/kb/q184291/" rel="nofollow noreferrer">COM objects fail to print when called from ASP</a></p>
<p>The following Microsoft Knowledgebase article describes the problem and a solution:</p> <p><a href="http://support.microsoft.com/kb/q184291/" rel="nofollow noreferrer">COM objects fail to print when called from ASP</a></p>
27,243
<p>I have the following table schema;</p> <pre><code>CREATE TABLE `db1`.`sms_queue` ( `Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error', `CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None', `Phone` VARCHAR(14) DEFAULT NULL, `Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, `TriesLeft` tinyint NOT NULL DEFAULT 3, PRIMARY KEY (`Id`) ) ENGINE = InnoDB; </code></pre> <p>It fails with the following error:</p> <pre><code>ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause. </code></pre> <p>My question is, can I have both of those fields? or do I have to manually set a LastUpdated field during each transaction?</p>
<p><a href="http://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html" rel="noreferrer">From the <strong>MySQL 5.5</strong> documentation</a>:</p> <blockquote> <p>One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. <strong>It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.</strong></p> </blockquote> <p><a href="http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html" rel="noreferrer">Changes in <strong>MySQL 5.6.5</strong></a>:</p> <blockquote> <p>Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. <strong>This restriction has been lifted.</strong> Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.</p> </blockquote>
<p>My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions: </p> <p><a href="http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/" rel="nofollow noreferrer">http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/</a></p>
33,569
<p>So I want to start using RSpec stories, but I am not sure where writing controller, model and view specs fit in. </p> <p>For example, you have the story "Logging in" with "User provides wrong password" scenario, don't you end up testing the same stuff than controller/model specs (response.should render..., user.should be_nil, etc.)</p> <p>So my question is: for those who are used to doing bdd (or story dd) with RoR, do you still write model/controller specs? If so, how is the workflow you follow ("first story, then narrow to specific specs")?</p>
<p>If you are starting with stories now (as opposed to having a lot of legacy stories) you may want to look at <a href="http://github.com/aslakhellesoy/cucumber/wikis/migration-from-rspec-stories" rel="noreferrer">Cucumber</a> which is the long term replacement for the RSpec story runner.</p> <p>The easiest way of splitting between specs and stories is to use stories for full-stack testing of business requirements and specs for isolated low-level specifications of the components (views, helpers, controllers and models). 'Full stack' can a range from controller/model/database through client simulation with Webrat to in-browser testing with Watir or Selenium.</p> <p>The ultimate 'outside in' BDD way of doing things is to start with stories based on customer requirements and then add in specs for the components you find you need when implementing the stories. Ideally you will fully cover the individual components with specs and have stories for the most important workflows of your users so you can check at the highest level that your app is delivering the functionality you have been asked for.</p>
<p>What about skipping view spec if you've got Cucumber+Capybara on it. I tend to find view spec not needed.</p>
20,193
<p>I want to parse some HTML in order to find the values of some attributes/tags etc.</p> <p>What HTML parsers do you recommend? Any pros and cons?</p>
<p><a href="http://sourceforge.net/projects/nekohtml/" rel="nofollow noreferrer">NekoHTML</a>, <a href="http://home.ccil.org/~cowan/XML/tagsoup/" rel="nofollow noreferrer">TagSoup</a>, and <a href="http://sourceforge.net/projects/jtidy/" rel="nofollow noreferrer">JTidy</a> will allow you to parse HTML and then process with XML tools, like XPath.</p>
<p>Do you need to do a full parse of the HTML? If you're just looking for specific values within the contents (a specific tag/param), then a simple regular expression might be enough, and could very well be faster.</p>
4,618
<p>Hopefully this is a really quick one ;) I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target. The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.</p> <p>The relevant section of the Grammar file is as follows:</p> <pre><code>grammar MyGrammar; options { language = CSharp2; output = AST; ASTLabelType = CommonTree; } </code></pre> <p>To generate the correct namespace, I have tried:</p> <pre><code>@namespace { MyNamespace } </code></pre> <p>and</p> <pre><code>@lexer::namespace { MyNamespace } @parser::namespace { MyNamespace } </code></pre> <p>but both of these generate errors, claiming that the file has no rules.</p> <p>Any help is appreciated.</p>
<p>I use this for a combined lexer and parser (and it generates the namespace correctly):</p> <pre><code>grammar Test; options { language=CSharp2; } @lexer::namespace { My.Name.Space } @parser::namespace { My.Name.Space } DIGIT : '0'..'9'; simple : DIGIT EOF; </code></pre> <p>So i wonder why your version didn't work - maybe you want to try this simple example and see if it works for you.</p>
<p>It seems that the @namespace directive needs to be placed AFTER the tokens{} block. All good now...</p>
40,845
<p>I've been looking for profiling tools for Rails for a while. I'm currently playing and testing ruby-prof and railsbench, but I kinda frustrated with the amount of tweaking and mangling required to make then work.</p> <p>Althought I don't mind (much) the tweaking, I'd like to know if is there any other, more straight-forward and easy to use, tools to profile a Rails app? Which tools you recommend?</p>
<p><a href="http://www.newrelic.com/ruby" rel="nofollow noreferrer">New Relic</a> offers Rails profiling including a <a href="http://www.newrelic.com/ruby" rel="nofollow noreferrer">free 'Lite'</a> version.</p>
<p>You should also take a look at FiveRuns' <a href="http://www.fiveruns.com/products/tuneup" rel="nofollow noreferrer">TuneUp</a>. It is completely free, installs as a plugin into your Rails application. Keep in mind that it does send data back to their server (mostly very harmless information), but that might bother some people (namely government agencies would be very unhappy about that). I think you'll be surprised how great the tool is considering it is free.</p> <p>Another nice feature of it is that you can post your run data for others to comment and help you diagnose your long queries, or bad code.</p>
45,619
<p>What open source projects would you recommend as a good place for a starting open source developer? Factors that I think would be important are some obvious ones like well written code and a community that is helpful to newbies. But it might be nice if the code base is such that I can start hacking some small problems without really understanding the details of how everything works.</p> <p>I'd prefer something that can be developed on Linux using C/C++/Java/Python/Scala.</p>
<p>Trying to pick a project like that will never work because it's not something you're passionate about. What's an open source project that you use daily or enjoy using? Go work with that one.</p>
<p><strong>sourceforge</strong> has a list of projects seeking a new developer. Therer are several for your requested programming languages:</p> <p><a href="http://sourceforge.net/people/?category_id=1" rel="nofollow noreferrer">http://sourceforge.net/people/?category_id=1</a></p> <p>Apart from developers they have more help requests:</p> <p><a href="http://sourceforge.net/people/" rel="nofollow noreferrer">http://sourceforge.net/people/</a></p>
29,790
<p>Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates?</p> <p>Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.</p> <pre><code>AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101)) &lt;= Convert(datetime, Convert(char(10), GetDate(), 101)) AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101)) &gt;= Convert(datetime, Convert(char(10), GetDate(), 101)) </code></pre>
<p>That is terrible, take a look at <a href="http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr" rel="nofollow noreferrer">Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code</a> to see how you can optimize this since that is not sargable</p> <p>Also check out <a href="http://wiki.lessthandot.com/index.php/Get_Datetime_Without_Time" rel="nofollow noreferrer">Get Datetime Without Time</a> and <a href="http://wiki.lessthandot.com/index.php/Query_Optimizations_With_Dates" rel="nofollow noreferrer">Query Optimizations With Dates</a></p>
<p>try</p> <pre><code>ep.EffectiveStartDate BETWEEN @date1 AND @date2 </code></pre> <p>where you would do something like</p> <pre><code>declare @date1 datetime, @date2 datetime; set @date1 = cast('10/1/2000' as datetime) set @date2 = cast('10/1/2020' as datetime) </code></pre>
4,283
<p>I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.</p> <p>I want to call the <code>help</code> function on each one. In Ruby I can do something like <code>ClassName.methods</code> to get a list of all the methods available on that class. Is there something similar in Python?</p> <p>e.g. something like:</p> <pre><code>from somemodule import foo print(foo.methods) # or whatever is the correct method to call </code></pre>
<p>You can use <code>dir(module)</code> to see all available methods/attributes. Also check out PyDocs.</p>
<p>This will append all the functions that are defined in your_module in a list.</p> <pre><code>result=[] for i in dir(your_module): if type(getattr(your_module, i)).__name__ == "function": result.append(getattr(your_module, i)) </code></pre>
16,842
<p>I am currently using CuteFTP Secure Sever 3.3 but it has problems. It seems to muck up connection management, drop connections occasionally and die on large files.</p> <p>I am looking for a replacement that supports XCRC because I use the <em>Synchronize Folders</em> function in the CuteFTP client. I would prefer to detect file similarity by XCRC rather than a simple size/name/modification date if possible.</p> <p>Are there any other servers that support XCRC and SSL? I am looking for recommendations, not a regular list scraped from Google. I am hoping to save my self the time of trying each one out individually.</p>
<p><a href="http://www.smartftp.com/support/kb/2549" rel="nofollow noreferrer">SmartFTP</a> supports XCRC, and works quite well. It isn't open source or free, but it is a decent product. The linked page also shows some FTP Servers that support it as well.</p>
<p>FileZilla is always good if that's truly what you want. <a href="http://filezilla-project.org/" rel="nofollow noreferrer">http://filezilla-project.org/</a></p> <p>SmartFTP also has a list of FTP servers supporting XCRC <a href="http://www.smartftp.com/support/kb/2549" rel="nofollow noreferrer">http://www.smartftp.com/support/kb/2549</a></p>
28,667
<p>Can anyone explain to me what this means?</p> <p>"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."</p>
<p>When calling a function, the compiler has to push some arguments on the stack, or put them in some registers. The function body will change some memory location (or a register) to contain the return value. Then it will return to a block of code at a location stored 'somewhere' on the stack.</p> <p>The calling convention specifies the concrete details: e.g. first push the return address, then push arguments (input or output) on the stack from left to right, then execute the function, pop the arguments off again, then pop the return address and jump to that location.</p> <p>If the caller does this differently than the function expects, things can go wrong (return location is not at the expected stack position).</p> <p>ESP is typically the register containing the address of the current stack frame. This register is used in combination with indexes to obtain arguments in the function body. When returning, the stack top is typically reset to ESP, and the processor jumps to the location at e.g. ESP+1.</p> <p>Things that may cause this to happen:</p> <ul> <li>someone wrote over the values of the stack and changed the return location (e.g. buffer overflow)</li> <li>the caller had a different calling convention than the callee</li> </ul>
<p>This is typically the case when casting a function pointer to shut up the compiler when calling a Windows API, such as DialogBox:</p> <pre><code>DialogBox(hInstance, MAKEINTRESOURCE(MY_DIALOG), hWnd, &amp;dlgProc); </code></pre> <p>Windows is a bit odd in that all functions are defined with the stdcall calling-convention, contrary to cdecl, the default in C. Therefor all functions that should be passed to a Windows API should be defined with WINAPI (a define for stdcall):</p> <pre><code>INT_PTR WINAPI dlgProc(HWND, UINT, WPARAM, LPARAM); </code></pre> <p>If you miss that and instead define your dlgProc as:</p> <pre><code>INT_PTR dlgProc(HWND, UINT, WPARAM, LPARAM); </code></pre> <p>Your code won't compile and you might be sorely tempted to just shut the frikkin' compiler up:</p> <pre><code>DialogBox(hInstance, MAKEINTRESOURCE(MY_DIALOG), hWnd, (DLGPROC)&amp;dlgProc); // be a DLGPROC already, dammit!! </code></pre> <p>Don't do that. The program will crash. The compiler is your friend. The C-style cast operator is not. The compiler tried to tell you this was going to happen. And it was right. Listen to it.</p>
38,714
<p>I'm trying out the following query:</p> <pre><code>SELECT A,B,C FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C FROM table WHERE field LIKE '%query' UNION SELECT A,B,C FROM table WHERE field LIKE '%query%' GROUP BY B ORDER BY B ASC LIMIT 5 </code></pre> <p>That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.</p> <p>Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).</p>
<p>Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:</p> <pre><code>SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query' UNION SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%' GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5 </code></pre>
<p>If there isn't a sort that makes sense to order them you desire, don't union the results together - just return 3 separate recordsets, and deal with them accordingly in your data tier.</p>
2,588
<p>Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships.</p> <p>We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). </p> <p>There is currently no intra-jvm cache involved - so we manually signal one jvm from the other.</p> <p>Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. </p> <p>Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads.</p> <p>Thanks, Chris</p>
<p>A Hibernate session loads all data it reads from the DB into what they call the <i>first-level cache</i>. Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Session. </p> <p>From what I understand, your read-only server application never closes its Hibernate session. So when the DB gets updated by the read-write application, the Session on read-only server is unaware of the change. Effectively, your read-only application is loading an in-memory copy of the database and using that copy, which gets stale in due course.</p> <p>The simplest and best course of action I can suggest is to close and open Sessions as needed. This sidesteps the whole problem. Hibernate Sessions are intended to be a window for a short-lived interaction with the DB. I agree that there is a performance gain by not reloading the object-graph again and again; but you need to measure it and convince yourself that it is worth the pains.</p> <p>Another option is to close and reopen the Session periodically. This ensures that the read-only application works with data not older than a given time interval. But there definitely is a window where the read-only application works with stale data (although the design guarantees that it gets the up-to-date data eventually). This might be permissible in many applications - you need to evaluate your situation. </p> <p>The third option is to use a <i>second level cache</i> implementation, and use short-lived Sessions. There are various caching packages that work with Hibernate with relative merits and demerits.</p>
<p>The most used practice is to have a <a href="http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#d0e129" rel="nofollow">Container-Managed Entity Manager</a> so that two or more applications in the same container (ie Glassfish, Tomcat, Websphere) can share the same caches. But if you don't use an Application container, because you use Play! for instance, then I would build some webservices in the <em>primary Application</em> to read/write consistently in the cache.</p> <p>I think using stale data is an open door for disaster. Just like Singletons become Multitons, read-only applications are often a <em>write sometimes</em>.</p> <p><em>Belt and braces</em> :)</p>
7,117
<p>This is in reference to my other question <a href="https://stackoverflow.com/questions/16110/c-auto-clearing-winform-textbox">Auto Clearing Textbox</a>.<br> If I choose to derive a new TextBox control from TextBox instead of implement a user control just containing my Textbox, how would I include that in the toolbox.</p>
<blockquote> <p>Right-click the toolbox, click "Choose Items" from the context menu, browse to your DLL, and select it.</p> </blockquote> <p>To extend on Greg's answer... Just to clarify, you cannot add a user control to the tool box if the code for it is in the same project that you want to use it in. For some reason MS has never added this ability, which would make sense since we don't want to always have to create a User Control Library DLL everytime we want to use a user control. So, to get it in your tool box, you have to first create a separate "User Control Library" project (which <em>can</em> be in the same solution!) and then do what Greg said.</p>
<p>Right-click the toolbox, click "Choose Items" from the context menu, browse to your DLL, and select it.</p>
3,685
<p>I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the <em>Comments</em> tab enabled. The problem is that when I format a document comment that contains:</p> <pre><code>* @see &lt;a href="test.html"&gt;test&lt;/a&gt; </code></pre> <p>the code formatter inserts a space in the closing HTML, breaking it:</p> <pre><code>* @see &lt;a href="test.html"&gt;test&lt; /a&gt; </code></pre> <p>Why? How do I stop this happening?</p> <p>This is not fixed by disabling any of the options on the <em>Comments</em> tab, such as <em>Format HTML tags</em>. The only work-around I found is to disable Javadoc formatting completely by disabling both the <em>Enable Javadoc comment formatting</em> and <em>Enable block comment formatting</em> options, which means I then have to format comment blocks manually.</p>
<p>I can only assume it's a bug in Eclipse. It only happens with <em>@see</em> tags, it happens also for all 3 builtin code formatter settings.</p> <p>There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for <em>@see</em> in the <a href="https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&amp;order=relevance+desc&amp;bug_status=__all__&amp;product=JDT&amp;content=%40see" rel="nofollow noreferrer">Eclipse Bugzilla</a>.</p>
<p>Strict XML specifications require that the self closing tags should have a space before the closing slash like so:</p> <pre><code>&lt;gcServer enabled="true" /&gt; &lt;!-- note the space just after "true" --&gt; </code></pre> <p>I can only assume, like Bart said, that there is a bug in Eclipse's reformatter that thinks the closing tag is actually a self-closing tag. Another idea: Can you verify that your <strong>a</strong> tags are balanced (i.e. no unclosed tags higher up in the document)?</p>
6,729
<p>I'd like to build a CMS site based on Asp.Net Mvc and I want to choose my starting point.</p> <p>I have seen that there is a lot of interest in the new Microsoft Oxite project also if it seems to be pretty early to adopt it in a production project.<br> I've also looked at S#arp Architecture but it does not properly compare to Oxite as is just a starting point for general Asp.Net Mvc sites.</p> <p>For me S#arp Architecture has some advantages over Oxite as is far less complex and it uses Nhibernate for the data access layer.<br> Oxite code uses Linq2Sql for it's DAL and has already a project in the solution that requires the DB version for VS2008.<br> Oxite seems to me more blog oriented than CMS oriented but I haven’t looked the code deeply.</p> <p>Here are some of the choices that would point me to S#arp Ar. for starting.</p> <ul> <li>Simple clean architecture</li> <li>Nhibernate Dal</li> <li>Community supported</li> </ul> <p>Oxite:</p> <ul> <li>Microsoft project </li> <li>Potential huge community </li> <li>Early stages but very good code quality </li> <li>Provider model that permits to easily switch the DAL </li> </ul> <p>If anyone has looked at the code of these two projects please advice on your opinions.</p> <p>Thanks</p>
<p>Oxite might be feature rich, but the code quality is very low.</p> <p>I was very surprised when I checkout the code and found controller actions with 100+ lines of very unclean code, tagsoup views, no unit tests, etc.</p> <p>The criticism has been well summed up in these blog posts:</p> <p><a href="http://blog.wekeroad.com/blog/some-thoughts-on-oxite/" rel="nofollow noreferrer">http://blog.wekeroad.com/blog/some-thoughts-on-oxite/</a></p> <p><a href="http://codebetter.com/blogs/karlseguin/archive/2008/12/15/oxite-oh-dear-lord-why.aspx" rel="nofollow noreferrer">http://codebetter.com/blogs/karlseguin/archive/2008/12/15/oxite-oh-dear-lord-why.aspx</a></p>
<p>Oxite is well detailed already, entirely negatively.</p> <p>I'll just add that I've been using <a href="http://sharparchitecture.net/" rel="nofollow noreferrer">S#arp architecture</a> for several months and found it very maintainable and flexible. There's also a very solid, growing and active community of users around it.</p> <p>It is very clean, and quite easily upgraded to Fluent NHibernate RC 1.0</p>
46,903
<p>Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.</p>
<p>If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.</p> <pre><code>SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1 </code></pre> <p>The newId() will generate a new GUID for you that you can use as your automatically generated id column.</p>
<p>Is this perhaps what you are looking for?</p> <blockquote> <p>select NEWID() * from TABLE</p> </blockquote>
16,668
<p>Anyone have any idea how much power it takes to run a Creality Ender 3 3D printer every day for several hours at a time? Like what does it eat up per hour? A rough estimate of power use per hour would be nice, then I can figure out how much it costs me. Can anyone help me?</p>
<p>If it is really important to you to know how much you are spending per any given print, your best bet is not to guess, <em>but to know</em> how much power you're using. To that end, you could purchase a power meter which monitors your power usage. Given the right one, it can even calculate the cost of the power usage all in one little package. This link, <a href="https://wiki.ezvid.com/best-electricity-usage-monitors" rel="nofollow noreferrer">The 10 Best Electricity Usage Monitors</a>, should provide you some ideas as to what you might find, but I'm sure there are plenty more out there (NOTE: I have no affiliation to the link provided ... it was just a random one I found through a Google search ... Go Go Google-Fu!). </p> <p>As 0scar pointed out in his comment, there are just too many variables to try and guess what the power consumption <em>might be</em>. If you are looking for a real answer, I believe something along the lines as I've linked above is going to be your best solution to getting a real answer. Anything else is more or less just a guess.</p>
<p>Other answers include good estimates, and show that for one printer the electricity costs are not very significant. If you are using many printers and want a concrete answer, then it would be wise to purchase a power monitor (for continuous monitoring) or multimeter with clamp.</p> <p>With a clamp-on multimeter, you can clamp the meter on to the 3D printer's plug and read the Amps being drawn. Assuming a 120 VAC single phase supply (typical for North America), the power consumption is 120 VAC multiplied by the Amps drawn by the 3D printer (P=VI), which you can read from the multimeter.</p> <p>The amps drawn by the 3D printer will vary throughout your print, but for a longer print, you should be able to get a good average amps read during a middle print layer. Total energy cost of printing per day would then be:</p> <pre><code> C = (V*I/1000)*t*E*n C, Total printer energy costs per day (<span class="math-container">$/day) V, AC Voltage (V) I, Average current draw during print (Amps) t, time printers are running per day (Hours/day) E, Energy cost from utility ($</span>/kWh) n, number of printers </code></pre>
1,268
<p>Which libraries for Java are there that have a fast implementation for floating point or fixed point operations with a precision of several thousands of digits? How performant are they?</p> <p>A requirement for me is that it implements a multiplication algorithm that is better than the naive multiplication algorithm that takes 4 times as much time for a 2 times larger number of digits (compare <a href="http://en.wikipedia.org/wiki/Multiplication_algorithms" rel="noreferrer">Multiplication algorithms</a>).</p>
<p>There are three libraries mentioned on the <a href="http://en.wikipedia.org/wiki/Bignum" rel="noreferrer">Arbitrary Precision Arithmetic</a> page: java.math (containing the mentioned BigDecimal), <a href="http://www.apfloat.org/" rel="noreferrer">Apfloat</a> and <a href="http://jscience.org/" rel="noreferrer">JScience</a>. I run a little speed check on them which just uses addition and multiplication. </p> <p>The result is that for a relatively small number of digits BigDecimal is OK (half as fast as the others for 1000 digits), but if you use more digits it is way off - JScience is about 4 times faster. But the clear performance winner is Apfloat. The other libraries seem to use naive multiplication algorithms that take time proportional to the square of the number of digits, but the time of Apfloat seems to grow almost linearly. On 10000 digits it was 4 times as fast as JScience, but on 40000 digits it is 16 times as fast as JScience.</p> <p>On the other hand: JScience provides EXCELLENT functionality for mathematical problems: matrices, vectors, symbolic algorithms, solution of equation systems and what not. So I'll probably go with JScience and later write a wrapper to integrate Apfloat into the algorithms of JScience - due to the good design this seems easily possible.</p> <p>(UPDATE: I wrote a test suite for the number package of JScience and fixed a number of bugs. This went into release 4.3.1. So I can recommend checking it out.)</p>
<p>Apfloat offers high precision on the mantissa, but appears to give less-than-usual precision on the exponent (based on the fact that it crashes with "Logarithm of zero" for values that double can handle). So it is not useful for big numbers.</p> <p>Also, the documentation says:</p> <p>"A pitfall exists with the constructors Apfloat(float,long) and Apfloat(double,long). Since floats and doubles are always represented internally in radix 2, the conversion to any other radix usually causes round-off errors, and the resulting apfloat won't be accurate to the desired number of digits.</p> <p>For example, 0.3 can't be presented exactly in base 2. When you construct an apfloat like new Apfloat(0.3f, 1000), the resulting number won't be accurate to 1000 digits, but only to roughly 7 digits (in radix 10). In fact, the resulting number will be something like 0.30000001192092896... "</p> <p>This appears to make Apfloat minimally useful.</p> <p>BigDecimal does not have a logarithm function, and the documentation does not say whether it allows you to make bigger numbers than a double; the exponent is 32 bits, sort of.</p>
34,991
<p>On my blog I use some CSS classes which are defined in my stylesheet, but in RSS readers those styles don't show up. I had been searching for <code>class="whatever"</code> and replacing with <code>style="something: something;"</code>. But this means whenever I modify my CSS I need to modify my RSS-generating code too, and it doesn't work for a tag which belongs to multiple classes (i.e. <code>class="snapshot accent"</code>). Is there any way to point to my stylesheet from my feed?</p>
<p>The popular RSS readers WILL NOT bother downloading a style sheet, even if you provide one and link to it using <code>&lt;?xml-stylesheet?&gt;</code>.</p> <p>Many RSS readers simply strip all inline <code>style</code> attributes from your tags. From testing today, I discovered that Outlook 2007 seems to strip out all styles, for example, even if they are inline.</p> <p>Good RSS readers allow a limited set of inline <code>style</code> attributes. See, for example, <a href="http://www.bloglines.com/help/css-support" rel="noreferrer">this article at Bloglines</a> about what CSS they won't strip. From experimentation, Google Reader seems to pass through certain styles unharmed.</p> <p>The philosophy of RSS is indeed that the reader is responsible for presentation. Many people think that RSS should be plain text and that CSS in RSS feeds is inappropriate. It's probably not appropriate to impose a different font on your RSS feeds. However, certain types of content (for example, images floated on the left, with captions positioned carefully) require a minimal amount of styling in order to maintain their semantic meaning.</p>
<p>Because RSS is (supposed to be) XML, you can use XML stylesheets.</p> <p><a href="http://www.w3.org/TR/xml-stylesheet/" rel="nofollow noreferrer"><a href="http://www.w3.org/TR/xml-stylesheet/" rel="nofollow noreferrer">http://www.w3.org/TR/xml-stylesheet/</a></a></p>
14,450
<p>I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.</p> <p>I've seen <a href="http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952" rel="noreferrer">this gamedev article</a>, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.</p> <p>I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.</p>
<p>Calculate a powerspectrum with a sliding window FFT: Take 1024 samples: </p> <pre><code>double[] signal = stream.Take(1024); </code></pre> <p>Feed it to an FFT algorithm: </p> <pre><code>double[] real = new double[signal.Length]; double[] imag = new double[signal.Length); FFT(signal, out real, out imag); </code></pre> <p>You will get a real part and an imaginary part. Do NOT throw away the imaginary part. Do the same to the real part as the imaginary. While it is true that the imaginary part is pi / 2 out of phase with the real, it still contains 50% of the spectrum information.</p> <p>EDIT:</p> <p>Calculate the power as opposed to the amplitude so that you have a high number when it is loud and close to zero when it is quiet:</p> <pre><code>for (i=0; i &lt; real.Length; i++) real[i] = real[i] * real[i]; </code></pre> <p>Similarly for the imaginary part.</p> <pre><code>for (i=0; i &lt; imag.Length; i++) imag[i] = imag[i] * imag[i]; </code></pre> <p>Now you have a power spectrum for the last 1024 samples. Where the first part of the spectrum is the low frequencies and the last part of the spectrum is the high frequencies.</p> <p>If you want to find BPM in popular music you should probably focus on the bass. You can pick up the bass intensity by summing the lower part of the power spectrum. Which numbers to use depends on the sampling frequency:</p> <pre><code>double bassIntensity = 0; for (i=8; i &lt; 96; i++) bassIntensity += real[i]; </code></pre> <p>Now do the same again but move the window 256 samples before you calculate a new spectrum. Now you end up with calculating the bassIntensity for every 256 samples. </p> <p>This is a good input for your BPM analysis. When the bass is quiet you do not have a beat and when it is loud you have a beat. </p> <p>Good luck!</p>
<p>The easy way to do it is to have the user tap a button in rhythm with the beat, and count the number of taps divided by the time.</p>
10,478
<p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:</p> <pre><code> SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } </code></pre> <p>Then, when WorkerMethod() is complete, run this:</p> <p><pre><code> void SomeOtherMethod() // Also member of AClass{} { ... } </pre></code></p> <p>Can anyone please give an example of that? </p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a> class was added to .NET 2.0 for this exact purpose.</p> <p>In a nutshell you do:</p> <pre><code>BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { myBClass.DoHardWork(); } worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod); worker.RunWorkerAsync(); </code></pre> <p>You can also add fancy stuff like cancellation and progress reporting if you want :)</p>
<p>Ok, I'm unsure of how you want to go about this. From your example, it looks like WorkerMethod does not create its own thread to execute under, but you want to call that method on another thread. </p> <p>In that case, create a short worker method that calls WorkerMethod then calls SomeOtherMethod, and queue that method up on another thread. Then when WorkerMethod completes, SomeOtherMethod is called. For example:</p> <pre><code>public class AClass { public void SomeMethod() { DoSomething(); ThreadPool.QueueUserWorkItem(delegate(object state) { BClass.WorkerMethod(); SomeOtherMethod(); }); DoSomethingElse(); } private void SomeOtherMethod() { // handle the fact that WorkerMethod has completed. // Note that this is called on the Worker Thread, not // the main thread. } } </code></pre>
10,050
<p>I have a table with many millions of rows. I need to find all the rows with a specific column value. That column is not in an index, so a table scan results.</p> <p>But would it be quicker to add an index with the column at the head (prime key following), do the query, then drop the index?</p> <p>I can't add an index permanently as the user is nominating what column they're looking for.</p>
<p>I'm no DBA, but I would guess that building the index would require scanning the table anyway. </p> <p>Unless there are going to be multiple queries on that column, I would recommend not creating the index.</p> <p>Best to check the explain plans/execution times for both ways, though!</p>
<p>Adding an index requires a table scan, so if you can't add a permanent index it sounds like a single scan will be (slightly) faster.</p>
4,996
<p>I'm developing my first ASP.NET MVC application. This application tracks events, users, donors, etc. for a charitable organization. In my events controller I support standard CRUD operations with New/Edit/Show views (delete is done via a button on Show view). But I also want to list all of the events.</p> <p>Is it better to have a List view that you navigate to from an Index view or have the "List" view be the Index view. The Index view is my default view for the controller. If you keep Index/List separate, what would you put in the Index view?</p> <p>Right now I'm leaning toward keeping them separate and putting basic help information on the Index view. Should I consider changing this and have the List view become the default view and rename Index to Help?</p> <p>TIA for the collective wisdom of SO.</p>
<p>I've decided to have the Index action redirect to the List action. This saves me from having to create and maintain an Index view, but leaves open the possibility that I can implement an Index action that is something other than the list of models.</p> <pre><code>public ActionResult Index() { return RedirectToAction( "List" ); } </code></pre>
<p>Your Index view page could include</p> <pre><code>&lt;body&gt; &lt;% RenderPartial("List", "Events") %&gt; &lt;/body&gt; </code></pre> <p>which is equivalent to calling</p> <pre><code>/Views/Events/List.ascx </code></pre> <p>with the List view being an asp.net mvc user control. That will give you an Index view which contains a list of events. </p>
46,507
<p>In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?</p> <p>Am I going to get myself into trouble if I change this:</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset variables.foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #variables.foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <p>to this?</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre>
<p>It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset foo = "a private instance variable"&gt; &lt;cffunction name="doSomething"&gt; &lt;cfargument name="foo" required="yes"/&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;cffunction name="doAnotherThing"&gt; &lt;cfargument name="foo" required="yes"/&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #variables.foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <p>doSomething("args") returns "I have <strong>args</strong> and a <strong>function local variable</strong>"</p> <p>doAnotherThing("args") returns "I have <strong>a private instance of a variable</strong> and a <strong>function local variable</strong>."</p>
<p>After reading your answers here's what I'm thinking:</p> <p><strong>Yes, it's safe. In general, it's not necessary or useful to explicitly specify the variables scope. It just adds clutter to an already verbose language.</strong></p> <p>Granted, there is one minor exception, as <a href="https://stackoverflow.com/users/3420/soldarnal">Soldarnal</a> pointed out, where qualifying a variables-scoped variable is required. That is if you have a function local variable with the same name. (But you probably shouldn't do that anyway.)</p>
8,394
<p>I'm trying to make a select that calculates affiliate payouts.</p> <p>my approach is pretty simple.</p> <pre><code>SELECT month(payments.timestmap) ,sum(if(payments.amount&gt;=29.95,4,0)) As Tier4 ,sum(if(payments.amount&gt;=24.95&lt;=29.94,3,0)) As Tier3 ,sum(if(payments.amount&gt;=19.95&lt;=24.94,2,0)) As Tier2 FROM payments GROUP BY month(payments.timestamp) </code></pre> <p>The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.</p> <p>Before the above I tried what I was assuming would work like "<code>amount between 24.94 AND 29.94</code>" this caused an error. so then I tried "<code>amount &gt;= 24.94 AND &lt;= 29.94</code>" </p> <p>So is it possible to have a range comparison using IF in MySql?</p>
<p>The second part of the expression evaluates when you use <code>AND</code> - </p> <pre><code>SELECT month(payments.timestmap) ,sum(if(payments.amount&gt;=29.95,4,0)) As Tier4 ,sum(if(payments.amount&gt;=24.95 AND payments.amount&lt;=29.94,3,0)) As Tier3 ,sum(if(payments.amount&gt;=19.95 AND payments.amount&lt;=24.94,2,0)) As Tier2 FROM payments GROUP BY month(payments.timestamp) </code></pre> <p>I'm not entirely sure why the <code>between</code> clause didn't work for you, but the above should do the job.</p>
<p>What error did your first attempt give you? It should definitely work. However, note that the second form you have is incorrect syntax. It should be <code>amount >= 24.94 and amount &lt;= 29.94</code>.</p>
22,678
<p><code>CGI.escapeHTML</code> is pretty bad, but <code>CGI.unescapeHTML</code> is completely borked. For example:</p> <pre><code>require 'cgi' CGI.unescapeHTML('&amp;#8230;') # =&gt; "…" # correct - an ellipsis CGI.unescapeHTML('&amp;hellip;') # =&gt; "&amp;hellip;" # should be "…" CGI.unescapeHTML('&amp;#162;') # =&gt; "\242" # correct - a cent CGI.unescapeHTML('&amp;cent;') # =&gt; "&amp;cent;" # should be "\242" CGI.escapeHTML("…") # =&gt; "…" # should be "&amp;#8230;" </code></pre> <p>It appears that <code>unescapeHTML</code> knows about all of the numeric codes plus <code>&amp;amp;</code>, <code>&amp;lt;</code>, <code>&amp;gt;</code>, and <code>&amp;quot;</code>. And <code>escapeHTML</code> only knows about those last four -- it doesn't do any of the numeric codes. I understand that escaping doesn't generally need to be as robust since HTML will allow the literal versions of most characters except the four that <code>CGI.escapeHTML</code> knows about. But unescaping should really be better.</p> <p>Is there a better tool out there, at least for unescaping?</p>
<p>The htmlentities gem should do the trick:</p> <pre><code>require 'rubygems' require 'htmlentities' coder = HTMLEntities.new coder.decode('&amp;#8230;') # =&gt; "…" coder.decode('&amp;hellip;') # =&gt; "…" coder.decode('&amp;#162;') # =&gt; "¢" coder.decode('&amp;cent;') # =&gt; "¢" coder.encode("…", :named) # =&gt; "&amp;hellip;" coder.encode("…", :decimal) # =&gt; "&amp;#8230;" </code></pre>
<pre><code>require 'rubygems' require 'hpricot' Hpricot('&amp;#8230;', :xhtml_strict =&gt; true).to_plain_text </code></pre> <p>Though you might have to fiddle around with the character encoding.</p>
49,626
<p>I've seen some horrific code written in Perl, but I can't make head nor tail of this one:</p> <pre><code>select((select(s),$|=1)[0]) </code></pre> <p>It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets <code>$|</code>).</p> <p>But I can't figure out why there's multiple <code>select</code> calls or the array reference. Can anyone help me out?</p>
<p>It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT. </p> <p><code>select()</code> takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done. </p> <p>So <code>(select($s),$|=1)</code> redirects the filehandle (remember <code>select</code> returns the old one), and sets autoflush (<code>$| = 1</code>). It does this in a list (<code>(...)[0]</code>) and returns the first value (which is the result of the <code>select</code> call - the original STDOUT), and then passes <em>that</em> back into another <code>select</code> to reinstate the original STDOUT filehandle. Phew.</p> <p>But now you understand it (well, maybe ;)), do this instead:</p> <pre><code>use IO::Handle; $fh-&gt;autoflush; </code></pre>
<p>please check <a href="http://perldoc.perl.org/functions/select.html" rel="nofollow noreferrer">perldoc -f select</a>. For the meaning of <code>$|</code>, please check <a href="http://perldoc.perl.org/perlvar.html" rel="nofollow noreferrer">perldoc perlvar</a></p>
23,908
<p>This <strike>is clearly not</strike> appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.</p> <pre><code>//The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } </code></pre> <p>The value that is output is the second value <em>"Modified"</em>. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?</p> <p>[Edit]: Given some of the comments, changing the original sentence some...</p>
<p>currentValue is no longer a local variable: it is a <em>captured</em> variable. This compiles to something like:</p> <pre><code>class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); } } ... public Page_Index() { Foo foo = new Foo(); foo.currentValue = "This is the FIRST value"; this.Load += foo.SomeMethod; foo.currentValue = "This is the MODIFIED value"; } </code></pre> <p>Jon Skeet has a really good write up of this in <a href="http://www.manning.com/skeet/" rel="noreferrer">C# in Depth</a>, and a separate (not as detailed) discussion <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="noreferrer">here</a>.</p> <p>Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.</p> <p>This is different to java: in java the <em>value</em> of a variable is captured. In C#, the <em>variable itself</em> is captured.</p>
<p>You need to capture the value of the variable within the closure/delegate, else it can be modified, like you saw.</p> <p>Assign currentValue to a variable local (inside) to the delegate.</p>
17,907
<p>Is it possible to add attributes at runtime or to change the value of an attribute at runtime?</p>
<p>Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the <code>System.Type</code> class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.</p>
<p>Like mentionned in a comment below by Deczaloth, I think that metadata is fixed at compile time. I achieve it by creating a dynamic object where I override GetType() or use GetCustomType() and writing my own type. Using this then you could...</p> <p>I tried very hard with System.ComponentModel.TypeDescriptor without success. That does not means it can't work but I would like to see code for that.</p> <p>In counter part, I wanted to change some Attribute values. I did 2 functions which work fine for that purpose.</p> <pre><code> // ************************************************************************ public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName, string description) { PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName]; var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute; if (att != null) { var fieldDescription = att.GetType().GetField(&quot;description&quot;, BindingFlags.NonPublic | BindingFlags.Instance); if (fieldDescription != null) { fieldDescription.SetValue(att, description); } } } // ************************************************************************ public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly) { PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName]; var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute; if (att != null) { var fieldDescription = att.GetType().GetField(&quot;isReadOnly&quot;, BindingFlags.NonPublic | BindingFlags.Instance); if (fieldDescription != null) { fieldDescription.SetValue(att, isReadOnly); } } } </code></pre>
15,719
<p>How would you, as a developer with little (or no) artistic inclination, design a GUI for an application? In particular, I'm thinking about desktop apps but anything that relates to Web apps is welcome as well. I find it extremely hard to design something that both I and potential users find pleasing. I can look up color schemes on the net, but how would I know where to place buttons/textboxes/etc.?</p> <p>Update: To clarify, I don't mean what controls and such to use. Rather, are there any guidelines/hints to when I should buttons, combos, textboxes and so on? How long should they be and where would I place them on the form?</p>
<p>The first thing you need to do is get out of your developer-point-of-view. We tend to think in terms of forms, controls, buttons, lists, grids etc. And this tends to push us to solutions that are not always optimal for the user.</p> <p>Users don't want to use our software. (except when you're programming games) They just want to get stuff done. So when desinging UI and user interactions it makes sense to start from there. Write down what a user wants to do with your software. Think about how a user would go about doing these things and what your application could do to make things easier.</p> <p>Try to work with different tools than you use for programming. These make you think in UI widgets again. Start with a pencil and a piece of paper to sketch things, also try to think about the behaviour as well as the layout etc. If you've got a clear picture of what you want to build you can start thinking about how you're going to build it. That's when the widgets, buttons and pages come in.</p>
<p>Just think about who your users are from the perspective of your application. Is there one kind? More? Then for each kind of user, think about the big overarching things they want to accomplish. Present them those general choices, and then go from there into more appropriate interfaces for each task.</p> <p>Finally, if you have a big set of steps, a wizard is nice because it lets you validate each step one at a time. This is obvious on a native app, but very handy on the web.</p>
20,405
<p>I'm trying to find a way to make a list of everything between <code>&lt;a&gt;</code> and <code>&lt;/a&gt;</code> tags. So I have a list of links and I want to get the names of the links (not where the links go, but what they're called on the page). Would be really helpful to me.</p> <p>Currently I have this:</p> <pre><code>$lines = preg_split("/\r?\n|\r/", $content); // content is the given page foreach ($lines as $val) { if (preg_match("/(&lt;A(.*)&gt;)(&lt;\/A&gt;)/", $val, $alink)) { $newurl = $alink[1]; // put in array of found links $links[$index] = $newurl; $index++; $is_href = true; } } </code></pre>
<p>The standard disclaimer applies: Parsing HTML with regular expressions is not ideal. Success depends on the well-formedness of the input on a character-by-character level. If you cannot guarantee this, the regex will fail to do the Right Thing at some point.</p> <p>Having said that:</p> <pre><code>&lt;a\b[^&gt;]*&gt;(.*?)&lt;/a&gt; // match group one will contain the link text </code></pre>
<p>Regex, the black magic, again :)</p> <p>I found one <a href="https://stackoverflow.com/questions/331426/common-regular-expressions">nice question</a> about common regex. There some interesting links where you will find very common regexpressions like yours.</p> <blockquote> <p>Grabbing HTML Tags</p> <p>&lt; TAG\b[^>]<em>>(.</em>?) Analyze this regular expression with RegexBuddy matches the opening and closing pair of a specific HTML tag. Anything between the tags is captured into the first backreference. The question mark in the regex makes the star lazy, to make sure it stops before the first closing tag rather than before the last, like a greedy star would do. This regex will not properly match tags nested inside themselves, like in onetwoone.</p> <p>&lt;([A-Z][A-Z0-9]<em>)\b[^>]</em>>(.*?) Analyze this regular expression with RegexBuddy will match the opening and closing pair of any HTML tag. Be sure to turn off case sensitivity. The key in this solution is the use of the backreference \1 in the regex. Anything between the tags is captured into the second backreference. This solution will also not match tags nested in themselves.</p> </blockquote> <p>Otherwise: Browse this link: <a href="http://regexlib.com/Search.aspx?k=links" rel="nofollow noreferrer">keyword "link"</a>. There are some interesting approaches to filter links.</p> <p>I hope this helps :)</p> <p>Good luck!</p>
44,615
<p>What's the most efficient way to concatenate strings?</p>
<p>The <code>StringBuilder.Append()</code> method is much better than using the <code>+</code> operator. But I've found that, when executing 1000 concatenations or less, <code>String.Join()</code> is even more efficient than <code>StringBuilder</code>.</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.Append(someString); </code></pre> <p>The only problem with <code>String.Join</code> is that you have to concatenate the strings with a common delimiter.</p> <p><strong>Edit:</strong> as <em>@ryanversaw</em> pointed out, you can make the delimiter <code>string.Empty</code>.</p> <pre><code>string key = String.Join("_", new String[] { "Customers_Contacts", customerID, database, SessionID }); </code></pre>
<p>It would depend on the code. StringBuilder is more efficient generally, but if you're only concatenating a few strings and doing it all in one line, code optimizations will likely take care of it for you. It's important to think about how the code looks too: for larger sets StringBuilder will make it easier to read, for small ones StringBuilder will just add needless clutter.</p>
4,140
<p>I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why?</p>
<p>If I would do anything, then it would be to create an structure that holds all parameters to get nice intellisence and strong names.</p> <pre><code>public struct user { public string FirstName; public string LastName; public string zilionotherproperties; public bool SearchByLastNameOnly; } public user[] GetUserData(user usr) { //search for users using passed data and return an array of users. } </code></pre>
<p>Do not pass them as an array unless the function acts on an array, I wouldn't create a new data structure either to group the parameters for the following reasones</p> <ol> <li><p>Passing a new data structure hides what the function really needs as input (does it need all the data structure/part of it?)</p></li> <li><p>Related to 1 it makes UTs more difficult (when writing a UT you need to recreate the entire data structure)</p></li> <li><p>If the input parameters are not related you end up with a new data structure that groups unrelated data types for no other reason than to make a function call look neater</p></li> <li><p>If you chose to pass the new data structure to your function the function can not be used in a scope where the new datastructure was defined</p></li> </ol> <p>Really the only disadvantage to passing each paramater to the function is that you might not be able to fit the function in one line of code, but don't forget the lines you need before the function call in which you will fill up your data structure.</p>
43,167
<p>I'm trying to insert a comment character into a string something similar to this:</p> <pre><code>-CreateVideoTracker VT1 "vt name" </code></pre> <p>becomes</p> <pre><code>-CreateVideoTracker VT1 # "vt name" </code></pre> <p>The VT1 word can actually be anything, so I'm using the regex</p> <pre><code>$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g; </code></pre> <p>which gives me the result:</p> <pre><code>-CreateVideoTracker w #T1 "vt name" </code></pre> <p>Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?</p>
<pre><code>$line =~ s/^(\-CreateVideoTracker)\s+(\w+)/$1 $2 #/; </code></pre> <p>The bracketed expressions (known as "capture buffers") in the first half of the regexp are referenced as <code>$1</code>, <code>$2</code>. etc in the second half.</p>
<p>You have two problems in:</p> <pre><code>$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g; </code></pre> <p>First, you want to match multiple character words, so in the left side, \w should be \w+. Second, you can't use patterns like \w on the right side; instead capture what you want on the left with () and put it on the right with $1, $2, etc.:</p> <pre><code>$line =~ s/\-CreateVideoTracker (\w+)/\-CreateVideoTracker $1 # /g; </code></pre>
36,125
<p>So I'm having a path issue on OS X Leopard. It seems OS X is adding other paths that I'm not stating and it's messing with my path priority. I only have a <code>.bash_login</code> file, I don't have a <code>.bashrc</code> or a .profile file. My <code>.bash_login</code> file is as such:</p> <pre><code>export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH" </code></pre> <p>When I run export this is the path it returns:</p> <pre><code>PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/local/bin:/usr/local/git/bin" </code></pre> <p>Any ideas on what could be putting /usr/bin in there and how I could get <code>/usr/local/bin</code> to be a higher priority.</p> <p>I'm tagging this for Rails too because that's what I'm working on right now... it seems the Mac built-in Ruby, Rails, and Gems are taking priority over the one I have installed at <code>/usr/local/bin</code>, figured maybe you fellow Rubyists could help too.</p>
<p>Have you looked inside these two directories:</p> <pre><code>/etc/paths.d/ /etc/manpaths.d </code></pre> <p>Any paths defined in files in those directories get appended automatically to PATH variable -- I mostly use those two directories to put third-party installed applications in the PATH. Also, do have a look at the man page of <code>path_helper</code> on OS X.</p> <p><strong>EDIT</strong>: Looking at the contents of <code>/etc/profile</code>, I can see that <code>path_helper</code> is executed first. The man page for <code>path_helper</code> says that prior to reading files in <code>/etc/paths.d/</code> and <code>/etc/manpaths.d/</code> directories, <code>path_helper</code> reads and sets up the paths defined in the files <code>/etc/paths</code> and <code>/etc/manpaths</code>. A look at <code>/etc/paths</code> reveals this:</p> <pre><code>$ cat /etc/paths /usr/bin /bin /usr/sbin /sbin /usr/local/bin </code></pre> <p>And, I believe, those account for the half of what you are seeing as set in PATH.</p>
<p>I've also come across an interesting article on Apple's support forums:</p> <p><a href="http://discussions.apple.com/thread.jspa?messageID=7976259&amp;tstart=0" rel="nofollow noreferrer">.bash_login no longer executed</a></p> <p>With that information I found an overlooked blank .bash_profile file that I had that was loading - and killing all of the information I was trying to set in my path.</p> <p>So I guess it looks like we could have several "correct" answers depending on the situation.</p>
45,187
<p>Sometimes we deploy applications behind customer firewall and we need read only access to their DB for debugging issues as sometimes their IT people are not SQL savvy. We want to bundle our application with some web based application that will expose the database and allow us to fire adhoc SQL queries and show their output in HTML table. We dont want to write home grown code and we can bundle Java/JSP based applications.</p> <p>Our backend is Oracle so we need a solution that can connect to oracle server and expose it over the web.</p>
<p>If you want the database behind a firewall, and believe me, you do want your database behind a firewall, see if you can have a VPN for going directly into the box. Once you are on the VPN, you can use whichever management tool you currently use for managing the database. So if you use SQL Server, you can connect via the VPN, and use Enterprise Manager to manage the database. Oracle probably has a similar tool, although I'm not that familiar. While having a VPN does incur an extra cost, it will probably make things many times easier.</p>
<p>On my current project, we use <a href="http://www.quest.com/sql-navigator/" rel="nofollow noreferrer">SQL Navigator</a> in order to run queries on our Oracle database. I've also heard decent things about <a href="http://www.toadsoft.com/toad_oracle.htm" rel="nofollow noreferrer">TOAD</a>. I would advise against writing a web application just to run ad hoc SQL queries, because it seems to me that plenty of tools can support your debugging needs.</p>
17,365
<p>I have an image of a basic game map. Think of it as just horizontal and vertical walls which can't be crossed. How can I go from a png image of the walls to something in code easily?</p> <p>The hard way is pretty straight forward... it's just if I change the image map I would like an easy way to translate that to code.</p> <p>Thanks!</p> <p>edit: The map is not tile-based. It's top down 2D.</p>
<p>I dabble in video games, and I personally would not want the hassle of checking the boundaries of pictures on the map. Wouldn't it be cleaner if these walls were objects that just happened to have an image property (or something like it)? The image would display, but the object would have well defined coordinates and a function could decide whether an object was hit every time the player moved.</p>
<p>If you don't need to precompute anything using the map info. You can just check in runtime logic using getPixel(x,y) like function.</p>
16,625
<p>I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do </p> <pre><code>Obj *obj = libname_newDevice(); </code></pre> <p>Now, should I use delete or should I do <code>obj-&gt;deleteMe();</code>? I ask because I am not exactly doing new so I shouldn't be doing the delete?</p> <p>I have <code>obj-&gt;create(theType);</code> which returns a class with the Obj interface. My real question is do I need a <code>libname_deleteDevice();</code> or is <code>obj-&gt;deleteMe()</code> fine since I have a deleteMe in the interface?</p>
<p>Since you are abstracting the creation inside <code>libname_newDevice()</code> (which I have to say isn't a good approach), you should destroy using something like <code>libname_destroyDevice (obj)</code>.</p> <p>And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.</p>
<p>You definitely don't want to implement Obj::deleteMe(). It would have to do something like: </p> <pre><code>delete this; </code></pre> <p>while you were still inside this->deleteMe(). Follow Jaywalker's suggestion and make the destroy function take an Obj* as a parameter.</p>
36,106
<p>I am having some trouble with the <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps API</a>. I have an array which holds a ojbect I created to store points.</p> <p>My array and class:</p> <pre><code>var tPoints = []; function tPoint(name) { var id = name; var points = []; var pointsCount = 0; ... this.getHeadPoint = function() { return points[pointsCount-1]; } } </code></pre> <p>tPoint holds an array of <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng" rel="nofollow noreferrer">GLatLng</a> points. I want to write a function to return a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> object which is extended from the current map bounds to show all the HeadPoints.</p> <p>Heres what I have so far..</p> <pre><code>function getBounds() { var mBound = map.getBounds(); for (var i = 0; i &lt; tPoints.length; i++) { alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng()); alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng()); currPoint = trackMarkers[i].getHeadPoint(); if (!mBound.containsLatLng(currPoint)) { mBound.extend(currPoint); } } return mBound; } </code></pre> <p>Which returns these values for the alert. (Generally over the US)<br /></p> <blockquote> <p>"19.64258,NaN"<br /> "52.69636,NaN"<br /> "i=0"<br /> "19.64258,NaN"<br /> "52.69636,-117.20701"<br /> "i=1"<br /></p> </blockquote> <p>I don't know why I am getting NaN back. When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> incorrectly?</p>
<p>Maybe a CLR stored procedure is what you are looking for. These are generally used when you need to interact with the system in some way.</p>
<p>I still believe that a CLR procedure might be the best bet. So, I'm accepting that answer. However, either I'm not that bright or it's extremely difficult to implement. Our SQL Server service is running under a local account because, according to Mircosoft, that's the only way to get an iSeries linked server working from a 64-bit SQL Server 2005 instance. When we change the SQL Server service to run with a domain account, the xp_fileexist command works fine for files located on the network.</p> <p>I created this CLR stored procedure and built it with the permission level set to External and signed it:</p> <pre><code>using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Security.Principal; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void FileExists(SqlString fileName, out SqlInt32 returnValue) { WindowsImpersonationContext originalContext = null; try { WindowsIdentity callerIdentity = SqlContext.WindowsIdentity; originalContext = callerIdentity.Impersonate(); if (System.IO.File.Exists(Convert.ToString(fileName))) { returnValue = 1; } else { returnValue = 0; } } catch (Exception) { returnValue = -1; } finally { if (originalContext != null) { originalContext.Undo(); } } } } </code></pre> <p>Then I ran these TSQL commands:</p> <pre><code>USE master GO CREATE ASYMMETRIC KEY FileUtilitiesKey FROM EXECUTABLE FILE = 'J:\FileUtilities.dll' CREATE LOGIN CLRLogin FROM ASYMMETRIC KEY FileUtilitiesKey GRANT EXTERNAL ACCESS ASSEMBLY TO CLRLogin ALTER DATABASE database SET TRUSTWORTHY ON; </code></pre> <p>Then I deployed CLR stored proc to my target database from Visual Studio and used this TSQL to execute from SSMS logged in with windows authentication:</p> <pre><code>DECLARE @i INT --EXEC FileExists '\\\\server\\share\\folder\\file.dat', @i OUT EXEC FileExists 'j:\\file.dat', @i OUT SELECT @i </code></pre> <p>Whether I try a local file or a network file, I always get a 0. I may try again later, but for now, I'm going to try to go down a different road. If anyone has some light to shed, it would be much appreciated.</p>
3,736
<p>Suppose I have a page that I am writing a javascript plugin for on the domain <code>first.com</code>. The javascript plugin injects an iframe pointing to a login page (of domain <code>second.com</code>) into the <code>first.com</code> page and displays it as a popup so that the user can login.</p> <p>Is there anyway for me to hide/close the iframe after the user logs in with it? I can inject any javascript necessary into the <code>first.com</code> page and I control both the client and server side code on the login page within the iframe.</p> <p>The main issue is that the iframe cannot access it's parent window to hide itself and the parent window cannot see any changes made in the contents of the iframe because of the same origin policy. Is there anyway around this or should I just lose the iframe idea and instead open a new window?</p>
<p>If the developer of second.com can be convinced to load an iframe in their login page, which loads a page at first.com, the the inner iframe can call javascript on the outer, since they are both from first.com. You can pass parameters in this way too, through the url of the inner iframe. An <a href="http://mcknut.googlepages.com/iframetest.html" rel="nofollow noreferrer">example</a> here.</p>
<p>I think the issue you're running into is the browser stopping the cross-domain communication from happening. There is a way to <a href="http://www.mozilla.org/projects/security/components/signed-scripts.html" rel="nofollow noreferrer">sign your javascript</a> but it is pretty much breaking the browser security model and isn't suggested unless absolutely necessary.</p> <p>Is there any way that the login form is based on URL submition? You could create a simple sign in form and use AJAX to get your response back to ensure a successful login. This solution depends on having a RESTful login and again, I'm not sure about the implementation of your second.com.</p> <p>If you're wondering about how to use the ajax to submit a form, I'd check <a href="http://be.twixt.us/jquery/formSubmission.php" rel="nofollow noreferrer">this</a> out (it is in jQuery but it applies to just about any framework.) View the source on that and see if that could work in your situation.</p>
37,203
<p>Publishing and/or collaborative applications often involve the sharing of access to resources. In a portal a user may be granted access to certain content as a member of a group or because of explicit access. The complete set of content could include public content, group membership content, and private user content. Or, with collaborative applications, we may want to pass along resources as part of a workflow or share custody of a document for editing purposes. </p> <p>Since most applications store these resources in a database you typically create queries like 'Get all the documents that I can edit' or 'Get all the content I can see'. Where 'can edit' and 'can see' are the user's privileges.</p> <p>I have two questions: </p> <ol> <li><p>It's quite easy to authorize the user once you've retrieved a resource, but how do you efficiently perform authorization on the list of available resources? And, </p></li> <li><p>Can this kind of authorization be separated from the core of the application? Perhaps into a separate service? Once separated, how could you filter queries like 'Get me all the documents I can see with title like [SomeSearchTerm]'? It seems to me your separate system would have to copy over a lot of reference data.</p></li> </ol>
<p>You may be interested in reading <a href="http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/" rel="noreferrer" title="Rails authorization plugins">this article by Steffen Bartsch</a>. It summarizes all authorization plugins for Ruby on Rails, and I am sure it will help you find your solution (although this article is about Rails plugins, the concepts are easily exportable outside Rails).</p> <p>Steffen also built his own plugin, called "Declarative Authorization" which seems to match your needs, IMHO:</p> <ul> <li>on the one hand, you define <strong>roles</strong> (such as "visitor", "admin"...). Your <strong>users</strong> are associated to these roles (in a many-to-many relationship). You map these roles to <strong>privileges</strong> (again in a many-to-many relationship). Each privilege is linked to a given <strong>context</strong>. For example, the role "<em>visitor</em>" may have privilege "<em>read documents</em>". In this example, "<em>read</em>" is the privilege, and it is applied to the "<em>documents</em>" context. <ul> <li>Note: in Steffen's plugin, you can define a hierarchy of roles. For example you might want to have the "<em>global_admin</em>" role include the "<em>document_admin</em>" role, as well as the "<em>comment_admin</em>" role, etc.</li> <li>You can also defines hierarchies of privileges: for example, the "<em>manage</em>" privilege could include the "<em>read</em>", "<em>update</em>", "<em>add</em>" and "<em>delete</em>" privileges.</li> </ul></li> <li>on the other hand, you code your application thinking in terms of <strong>privileges</strong> and <strong>contexts</strong>, not in terms of roles. For example, the action to display a document should only check whether the user has the privilege to "<em>read</em>" in the "<em>documents</em>" context (no need to check whether the user has the "<em>visitor</em>" role or any other role). This greatly simplifies your code, since most of the authorization logic is extracted elsewhere (and perhaps even defined by someone else).</li> </ul> <p>This separation between the definition of the user roles and the definition of the application-level privileges guarantees that your code will not change every time you define a new role. For example, here is how simple the access-control would look like in a controller :</p> <pre><code>class DocumentController [...] filter_access_to :display, :require =&gt; :read def display ... end end </code></pre> <p>And inside a view:</p> <pre><code>&lt;html&gt; [...] &lt;% permitted_to?(:create, :documents) do %&gt; &lt;%= link_to 'New', new_document_path %&gt; &lt;% end %&gt; &lt;/html&gt; </code></pre> <p>Steffen's plugin also allows for object-level (ie. row-level) access-control. For example, you might want to define a role such as "<em>document_author</em>" and give it "<em>manage</em>" privilege on "<em>documents</em>", but <strong>only</strong> if the user is the author of the document. The declaration of this rule would probably look like this:</p> <pre><code>role :document_author do has_permission.on :documents do to :manage if_attribute :author =&gt; is {user} end end </code></pre> <p>That's all there is to it! You can now get all the documents that the user is allowed to update like this:</p> <pre><code>Document.with_permissions_to(:update) </code></pre> <p>Since the "<em>manage</em>" privilege includes the "<em>update</em>" privilege, this will return the list of documents whose author is the current user.</p> <p>Of course, not every application will need this level of flexibility... but yours might.</p>
<p>I generally have a schema like this</p> <p>Users &minus;&minus;&isin; UserDocuments &ni;&minus;&minus; Documents</p> <p>Then I create a view "ProfiledDocuments"</p> <pre><code>SELECT &lt;fields&gt; FROM Documents d INNER JOIN UserDocuments ud on ud.DocumentId = d.Id INNER JOIN Users u ON u.Id = ud.UserId </code></pre> <p>Then run the search queries on ProfiledDocuments always using a UserId filter. With appropriate indexes it works well enough.</p> <p>If you need more complex permissions, you can do it with an extra field in the UserDocuments many to many table which specifies the kind of permission.</p>
20,582
<p>Are there any easy, smart ways to keep your client and server-side validation-rules synchronized?</p> <p>On the client side we have JavaScript, maybe some kind of framework like jQuery or YUI.</p> <p>On the server-side we have ASP.NET WebForms or ASP.NET MVC.</p> <p>What is validated are things like:</p> <ul> <li>Correct e-mail-addresses</li> <li>Correct home-addresses and postal codes</li> <li>Correct credit-card numbers</li> </ul> <p>And so on.</p>
<p>&lt;asp:RegularExpressionValidator ...&gt; (and the other asp.net validators) implement client side javascript and server side checking to the same rules.</p>
<p>write a large, common corpus of test data that embodies the validation rules, and unit test your validators against this common data.</p> <p>When your rules change, you reflect this by updating the test data and testing until everything goes green again.</p>
12,622
<p>How do I get the full width result for the *nix command "<strong>ps</strong>"?<br /> I know we can specify something like <code>--cols 1000</code> but is there anyway I can the columns and just print out everything?</p>
<p>Try <code>ps -w -w aux</code>. The -w option sets the output to wide, and doing it twice makes the width unlimited. The "aux" part makes it show more information, and is (afaik) pretty standard mode to use. This is of course platform-dependant, the above works with procps version 3.2.7 on Linux.</p>
<p>Specify the <code>w</code> option twice, if you're using BSD-style <code>ps</code>. e.g., <code>ps auwwx</code>. A different set of options apply when using System V <code>ps</code>.</p>
25,479
<p>I'm relatively new in the field of 3D printing and design. By now I've created and printed some technical objects with TinkerCAD, but now I've a task, which I don't know how to solve.</p> <p>I have the following model as STL-file: <a href="https://i.stack.imgur.com/o8Bn1.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/o8Bn1.jpg" alt="enter image description here"></a></p> <p>Now I want to "adjust" the arms of the model, as shown in the picture. I want the arms to hang besides the body. </p> <p>I know that I could cut and rotate the arms and then merge them again with TinkerCAD but the outcome dosn't look good and the workflow feels wrong.</p> <p>So what is the right tool/way to get this task done?</p> <p>*Disclaimer: I'm not Denis Almaral, but he released this model unter CC license. So I kept his name on the image to credit him, as requested via CC.</p>
<p>Basically there's no good easy way to do this.</p> <p>At this point you only have the mesh - a list of triangles - the 3D model you have does not contain the concept of joints or moving parts so it can't regenerate the shoulder after the rotation.</p> <p>The original author may or may not have the ability to do this, depending on his workflow and software.</p> <p>If all you have is the STL your only choice is to rotate the arm and then rebuild the shoulder from scratch and manually fix anything that doesn't look good</p>
<p>Basically there's no good easy way to do this.</p> <p>At this point you only have the mesh - a list of triangles - the 3D model you have does not contain the concept of joints or moving parts so it can't regenerate the shoulder after the rotation.</p> <p>The original author may or may not have the ability to do this, depending on his workflow and software.</p> <p>If all you have is the STL your only choice is to rotate the arm and then rebuild the shoulder from scratch and manually fix anything that doesn't look good</p>
788
<p>A common mistake when configuring the compilation/linking/etc. settings in VC++ 2008 is to set them in Release but not Debug (or vice versa) rather than setting them for "All Configurations". Any suggestions on how to avoid this kind of mistake?</p> <p>Some beginnings of ideas that I have:</p> <ul> <li><p>Find a way to make VC++ go to the "All Configurations" settings by default when you open the property pages rather than the active (Release / Debug) settings.</p></li> <li><p>Have a VB script that can be run (inside or outside VC++) to check the project settings and raise any inconsistencies detected.</p></li> </ul>
<p>I just ran a quick test and noticed the following, which may help you:</p> <ul> <li>When run from an open command prompt, the %0 variable does not have double quotes around the path. If the script resides in the current directory, the path isn't even given, just the batch file name.</li> <li>When run from explorer, the %0 variable is always enclosed in double quotes and includes the full path to the batch file.</li> </ul> <p>This script will not pause if run from the command console, but will if double-clicked in Explorer:</p> <pre><code>@echo off setlocal enableextensions set SCRIPT=%0 set DQUOTE=" @echo do something... @echo %SCRIPT:~0,1% | findstr /l %DQUOTE% &gt; NUL if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1 :EXIT if defined PAUSE_ON_CLOSE pause </code></pre> <p>EDIT: There was also some weird behavior when running from Explorer that I can't explain. Originally, rather than </p> <pre><code>@echo %SCRIPT:~0,1% | findstr /l %DQUOTE% &gt; NUL if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1 </code></pre> <p>I tried using just an <code>if</code>:</p> <pre><code>if %SCRIPT:0,1% == ^" set PAUSE_ON_CLOSE=1 </code></pre> <p>This would work when running from an open command prompt, but when run from Explorer it would complain that the <code>if</code> statement wasn't correct.</p>
<p>Just add pause regardless of how it was opened? If it was opened from command prompt no harm done apart from a harmless pause. (Not a solution but just thinking whether a pause would be so harmful / annoying )</p>
49,422
<p>Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. </p> <p>It happens where you see this line '&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' in the code </p> <p>What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out.<br> Also one more question. </p> <p>Sum up:<br> * How to handle a stalled Open Office instance?<br> * How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory.<br> * also any general suggestions on code quality, optimizations and general coding standards will be most appreciated.</p> <hr> <p>Traceback (innermost last):<br> File "dcmail.py", line 184, in ?<br> File "dcmail.py", line 174, in main<br> File "C:\DCMail\digestemails.py", line 126, in process_inbox<br> File "C:\DCMail\digestemails.py", line 258, in _convert<br> File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type<br> File "C:\DCMail\digestemails.py", line 287, in _open_office_convert<br> File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert<br> com.sun.star.lang.DisposedException: java.io.EOFException<br> at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi spatcher.run(java_remote_bridge.java:176) </p> <p>com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i o.EOFException </p> <p>Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely </p> <hr> <p>The Code (with non functional code tags) </p> <p>[code] </p> <blockquote> <blockquote> <pre><code>#ghost script handles these file types GS_WHITELIST=[".pdf"] #Open Office handles these file types OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"] #whitelist is used to check against any unsupported files. WHITELIST=GS_WHITELIST + OO_WHITELIST </code></pre> </blockquote> </blockquote> <pre><code>def _get_service_manager(self): try: self._context=Bootstrap.bootstrap(); self._xMultiCompFactory=self._context.getServiceManager() self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context)) except: raise OpenOfficeException("Exception Occurred with Open Office") def _choose_conversion_type(self,fn): ext=os.path.splitext(fn)[1] if ext in GS_WHITELIST: self._ghostscript_convert_to_tiff(fn) elif ext in OO_WHITELIST: self._open_office_convert(fn) def _open_office_convert(self,fn): self._load_attachment_to_convert(fn) self._save_as_pdf(fn) self._ghostscript_convert_to_tiff(fn) def _load_attachment_to_convert(self, file): file=self._create_UNO_File_URL(file) properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) properties=tuple(properties) self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; here is line 299 def _create_UNO_File_URL(self, filepath): try: file=str("file:///" + filepath) file=file.replace("\\", "/") except MalformedURLException, e: raise e return file def _save_as_pdf(self, docSource): dirName=os.path.dirname(docSource) baseName=os.path.basename(docSource) baseName, ext=os.path.splitext(baseName) dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR) if not os.path.exists(dirTmpPdfConverted): os.makedirs(dirTmpPdfConverted) pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf") url_save=self._create_UNO_File_URL(pdfDest) properties=self._create_properties(ext) try: try: self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc); self._xstorable.storeToURL(url_save, properties) except AttributeError,e: self.logger.info("pdf file already created (" + str(e) + ")") raise e finally: try: self._doc.dispose() except: raise def _create_properties(self,ext): properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" if ext==".doc": p.Value='writer_pdf_Export' elif ext==".rtf": p.Value='writer_pdf_Export' elif ext==".xls": p.Value='calc_pdf_Export' elif ext==".tif": p.Value='draw_pdf_Export' elif ext==".tiff": p.Value='draw_pdf_Export' properties.append(p) return tuple(properties) def _ghostscript_convert_to_tiff(self, docSource): dest, source=self._get_dest_and_source_conversion_file(docSource) try: command = ' '.join([ self._ghostscriptPath + 'gswin32c.exe', '-q', '-dNOPAUSE', '-dBATCH', '-r500', '-sDEVICE=tiffg4', '-sPAPERSIZE=a4', '-sOutputFile=%s %s' % (dest, source), ]) self._execute_ghostscript(command) self.convertedTifDocList.append(dest) except OSError, e: self.logger.info(e) raise e except TypeError, (e): raise e except AttributeError, (e): raise e except: raise </code></pre> <p>[/code]</p>
<p>First of all, a model class shall not talk to a view class. A TextView is part of the view.</p> <p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif">alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif</a></p> <p>The controller talks to view classes and view classes provide feedback to the controller. The model classes get updated by the controller and provide feedback to it. The model classes never talk to a view class, they don't even know about the existence of any view classes. So I think you have a basic design problem here. You probably implemented MVC as in this model:</p> <p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif">alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif</a></p> <p>However this is not the way it is done in Mac OS X, this is not the way Apple does it and this is not the way how the whole Cocoa object structure has been designed! So the answer to your question is: You don't, because you should not.</p> <p>Aside from the fact, that you have a design flaw, you access it like you access all data members in Objective-C. If it is public, you can access it directly:</p> <pre><code>MyController * c = [[MyController alloc] init]; // c has a member name textView, let's access it [c-&gt;textView ...]; </code></pre> <p>You should already know, that this is actually very bad programming style. You should not access data members of another object directly. You should actually not even make them public. If you declare them private, the code above will fail (the compiler enforces that you don't do this). The other way is to implement a getter and access it via the getter:</p> <pre><code>// This goes into the controller - (NSTextView) textView { return textView; } // This is called in the modell [[c textView] ...]; </code></pre> <p>However, this is also bad design. The model might do whatever it wants with this object and your controller won't see it! Why doesn't you model just tell the controller what it wants to happen?</p> <pre><code>// In the controller - (void) notifyContentHasChanged:(NSString *)name { // update the text view here ... } // In the modell [c notifyContentHasChanged:...]; </code></pre> <p>And voila, you have MVC the way Apple wants it to be. The model only notifies the controller of what's going on and the controller updates the view accordingly.</p>
<p>Re: the recursive <code>#import</code> problem, what you're looking for is the <code>@class</code> directive. In most cases, all your class interface needs to know about other classes is their names, since all of the actual implementation-specific stuff is in your <code>*.m</code> files. The <code>@class</code> directive therefore provides a way for an interface definition to tell the compiler "hey, when you come across this word, it's a class name, so don't freak out." When you use <code>@class</code> in your interface declaration, you shouldn't need to import that class's header file.</p> <p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_3_section_3.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF124" rel="nofollow noreferrer" title="The Objective-C 2.0 Programming Language: Class Interface (Referring to Other Classes)">The Objective-C 2.0 Programming Language: Class Interface (Referring to Other Classes)</a>.</p>
38,634
<p>I have a client/server application that communicates with .Net remoting. I need my clients to be able to find the server(s) on the network without requiring client-side configuration. </p> <p>As far as I know, there is no support for discovery in remoting. I am prepared to implement a UDP solution where the clients will be able to find the servers via broadcast messages. </p> <p>I want to hear the collective SO wisdom before I go ahead. Is this the best way? Any other suggestions?</p>
<p>I've looked at both SSDP and UPnP for this type of functionality, but I'd recommend going with a custom UDP <a href="http://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">multicast</a> solution. Basically, multicast is very similar to a broadcast, but only machines that have joined the multicast group (i.e. requested the broadcast) are contacted. </p> <p>IMHO, SSDP and UPnP and bloated and overly complicated for resource discovery... but hey, it's a standard. ;) </p>
<p>The best solution I have found in my remoting work was to keep the server list in a config file on the client systems and make it updateable. Not the easiest to maintain but was fast and no broadcasting.</p>
4,231
<p>I want to get the name of internet connection type in iPhone?</p> <p>Any help would be appreciated.</p> <p>Regards</p> <p>Uddhalaka</p>
<p>Take a look at the <a href="http://developer.apple.com/iphone/library/samplecode/Reachability/index.html" rel="nofollow noreferrer">Reachability</a> sample. Figure that it'll use the best available connection (WiFi, 3G, or Edge).</p>
<p>Take a look at the <a href="http://developer.apple.com/iphone/library/samplecode/Reachability/index.html" rel="nofollow noreferrer">Reachability</a> sample. Figure that it'll use the best available connection (WiFi, 3G, or Edge).</p>
40,412
<p>I seem to often find myself wanting to store data of more than one type (usually specifically integers and text) in the same column in a MySQL database. I know this is horrible, but the reason it happens is when I'm storing responses that people have made to questions in a questionnaire. Some questions need an integer response, some need a text response and some might be an item selected from a list.</p> <p>The approaches I've taken in the past have been:</p> <ol> <li><p>Store everything as text and convert to int (or whatever) when needed later.</p></li> <li><p>Have two columns - one for text and one for int. Then you just fill one in per row per response, and leave the other one as null.</p></li> <li><p>Have two tables - one for text responses and one for integer responses.</p></li> </ol> <p>I don't really like any of those, though, and I have a feeling there must be a much better way to deal with this kind of situation.</p> <p>To make it more concrete, here's an example of the tables I might have:</p> <pre><code>CREATE TABLE question ( id int(11) NOT NULL auto_increment, text VARCHAR(200) NOT NULL default '', PRIMARY KEY ('id') ) CREATE TABLE response ( id int(11) NOT NULL auto_increment, question int (11) NOT NULL, user int (11) NOT NULL, response VARCHAR(200) NOT NULL default '' ) </code></pre> <p>or, if I went with using option 2 above:</p> <pre><code>CREATE TABLE response ( id int(11) NOT NULL auto_increment, question int (11) NOT NULL, user int (11) NOT NULL, text_response VARCHAR(200), numeric_response int(11) ) </code></pre> <p>and if I used option 3 there'd be a responseInteger table and a responseText table.</p> <p>Is any of those the right approach, or am I missing an obvious alternative?</p>
<p>[Option 2 is] NOT the most normalized option [as @Ray claims]. The most normalized would have no nullable fields and obviously option 2 would require a null on every row.</p> <p>At this point in your design you have to think about the usage, the queries you'll do, the reports you'll write. Will you want to do math on all of the numeric responses at the same time? i.e. WHERE numeric_response IS NOT NULL? Probably unlikely.</p> <p>More likely would be, What's the average response WHERE Question = 11. In those cases you can either choose the INT table or the INT column and neither would be easier to do than the other.</p> <p>If you did do two tables, you'd more than likely be constantly unioning them together for questions like, what % of questions have a response etc.</p> <p>Can you see how the questions you ask your database to answer start to drive the design?</p>
<p>Option 2 is the correct, most normalized option.</p>
41,593
<p>My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: </p> <pre><code>writeln(file, exportRealvalue:30); //using excess width of field .... readln(file, importRealvalue); </code></pre> <p>When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): </p> <pre><code>-1.23456789012E-0002 -1.23456789034E-0002 </code></pre> <p>This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this?</p> <p>This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on.</p>
<p>You might try switching to <strong>extended</strong> for greater precision. As was pointed out though, floating point numbers only have so many significant digits of precision, so it is still possible to display more digits then are accurately stored, which could result in the behavior you specified.</p> <p>From the Delphi help:</p> <p>Fundamental Win32 real types</p> <pre> | Significant | Size in Type | Range | digits | bytes ---------+----------------------------------+-------------+---------- Real | -5.0 x 10^–324 .. 1.7 x 10^308 | 15–16 | 8 Real48 | -2.9 x 10^–39 .. 1.7 x 10^38 | 11-12 | 6 Single | -1.5 x 10^–45 .. 3.4 x 10^38 | 7-8 | 4 Double | -5.0 x 10^–324 .. 1.7 x 10^308 | 15-16 | 8 Extended | -3.6 x 10^–4951 .. 1.1 x 10^4932 | 10-20 | 10 Comp | -2^63+1 .. 2^63–1 | 10-20 | 8 Currency | -922337203685477.5808.. | | 922337203685477.5807 | 10-20 | 8 </pre> <blockquote> <p><strong>Note</strong>: The six-byte <strong>Real48</strong> type was called <strong>Real</strong> in earlier versions of Object Pascal. If you are recompiling code that uses the older, six-byte Real type in Delphi, you may want to change it to <strong>Real48</strong>. You can also use the {$REALCOMPATIBILITY ON} compiler directive to turn <strong>Real</strong> back into the six-byte type. The following remarks apply to fundamental real types.</p> <ul> <li><strong>Real48</strong> is maintained for backward compatibility. Since its storage format is not native to the Intel processor architecture, it results in slower performance than other floating-point types.</li> <li><strong>Extended</strong> offers greater precision than other real types but is less portable. Be careful using Extended if you are creating data files to share across platforms.</li> </ul> </blockquote> <p>Notice that the range is greater then the significant digits. So you can have a number larger then can be accurately stored. I would recommend rounding to the significant digits to prevent that from happening.</p>
<p>When using floating point types, you should be aware of the precision limitations on the specified types. A 4 byte IEEE-754 type, for instance, has only about 7.5 significant digits of precision. An eight byte IEEE-754 type has roughly double the number of significant digits. Apparently, the delphi real type has a precision that lies around 11 significant digits. The result of this is that any extra digits of formatting that you specify are likely to be noise that can result in conversions between base 10 formatted values and base 2 floating point values. </p>
18,072
<p>I have an old C++ COM component which has to stay in Visual Studio 6.0 format. I can't for the life of me figure out how to debug the code in the actual COM component.</p> <p>I'm able to build it in debug mode, add breakpoints and attach it to the dllhost.exe process, but the Visual Studio environment will only show me the disassembly from dllhost.exe and not my source code (It also doesn't stop on the breakpoints).</p> <p>I remember a while ago there was a way to make IIS (or inetinfo.exe) the <em>target</em> of your debug action (i.e. when Visual Studio 6.0 asks you for the executable to launch your dll) and IIS would run in a single process mode. There was a registry key you needed to change, but googling hasn't helped.</p>
<p>If it is a VB6 based COM component, you can open the project in VB6 and run it (a DLL project cannot be run). The project properties has some option whereby it can be asked to run so that it runs &amp; registers itself.</p> <p>Now, try hitting the ASP page, which makes a call to COM component. The breakpoints set in the class files will be hit, as the calls are made from ASP page.</p>
<p>First of all, PDB file (produced during the compilation) should be in the same directory with DLL (can be set in project properties).</p> <p>If your object does not use some ASP-specific functionality (Request, Response, Session objects) you can copy its invocation code to .vbs file and debug via setting <em>cscript.exe your.vbs</em> as debug target program.</p> <p>There are explanations (<a href="http://support.microsoft.com/default.aspx/kb/183480" rel="nofollow noreferrer">for example</a>) how to debug ISAPI DLLs - they are applicable to your COM object too (from OS/debugger point of view both are DLLs loaded into IIS process). Put attention to your IIS version and in/out-of-process stuff. </p> <p>And finally, if nothing other helps, you can add some logging via <a href="http://msdn.microsoft.com/en-us/library/aa363362%28VS.85%29.aspx" rel="nofollow noreferrer">OutputDebugString</a> function and see it in free <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="nofollow noreferrer">DebugView</a> program.</p>
48,363
<p>I want to store some information in the EPROCESS structure of the process in windows NT kernel. My aim is that when winlogon is called I want to assign a unique value to the next process based on which user logs in. But I do not know where to store this unique ID. I have tried and succeeded in modifying some information (like the tokens) in the EPROCESS block of a process by the method of Direct kernel object modification and I wonder if there is any structure in this EPROCESS block where some other information can be stored.</p> <p>p.s. For modifying the EPROCESS block I used a device driver.</p>
<p>The EPROCESS structure is opaque and undocumented, meaning you shouldn't be messing with its internals. Doing so requires you, among other things, to test on every OS version and service pack you plan on supporting.</p>
<p>Do not modify EPROCESS. It will bring you great sorrow.</p> <p>Furthermore, if you do, do not install it on anyone elses machine. It is absolutely wrong to impose such a profoundly damaging, system destabilizing change on another persons computer. How would like it if I gave you tuberculosis?</p>
46,322
<p>PHP has a great function called <a href="http://us2.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer">htmlspecialcharacters()</a> where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's <em>almost</em> a one stop shop for sanitizing input. Very nice right?</p> <p>Well is there an equivalent in any of the .NET libraries?</p> <p>If not, can anyone link to any code samples or libraries that do this well?</p>
<p>Try this.</p> <pre><code>var encodedHtml = HttpContext.Current.Server.HtmlEncode(...); </code></pre>
<p>In an addition to the given answers: When using <a href="http://en.wikipedia.org/wiki/ASP.NET_Razor_view_engine" rel="nofollow">Razor view engine</a> (which is the default view engine in ASP.NET), using the '@' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.</p> <p>On the other hand, when you <strong>don't</strong> want the text being encoded, you have to specify that explicitly (by using <a href="https://msdn.microsoft.com/en-us/library/gg480740%28v=vs.118%29.aspx" rel="nofollow">@Html.Raw</a>). Which is, in my opinion, a good thing from a security point of view.</p>
3,747
<p>So, i'm running emacs over a crappy ssh connection and I have it set up to use cscope. I can not use X because of this...hence I'm running emacs inside putty. However, when I search for something with cscope and it opens up the other buffer, I can not follow the links where cscope tells me which file and line number the item is on. When I go t a line number and hit enter, emacs tells me 'buffer is read-only' (it is trying to actually put in a new line instead of following the link). anyone know how I can follow those links?</p>
<p>I don't know about cscope for sure - but you should be able to find out the appropriate key binding by doing a "Ctrl-h m" in the buffer with all the links. This should open another buffer showing you help/key bindings on all the active modes. </p> <p>E.g. if you do the same thing in a grep result buffer it indicates the key binding "C-c C-c compile-goto-error" which is used to open file at the grep line number (so it may be the same keys for cscope).</p>
<p>Could you use cscope with Tramp mode? I'm not familiar with cscope, but I've had great results using tramp mode to read/write files remotely over an SSH connection. </p>
47,585
<p>I bought an Anet A8 over christmas. When I bought my printer from Gearbest, I also bought the inductive sensor that they <a href="http://www.gearbest.com/3d-printer-parts/pp_591321.html" rel="nofollow noreferrer">sell</a>.</p> <p>It doesn't seem to work, and I think it might be broken. However, I have no idea how I can test if it is broken. This is what the wiring <a href="http://rotjes.bangblog.eu/reddit/DSC_0112.JPG" rel="nofollow noreferrer">looks</a> like and how it's connected to the <a href="http://rotjes.bangblog.eu/reddit/DSC_0113.JPG" rel="nofollow noreferrer">board</a></p> <p>I'm not sure if I need to modify the wiring in order to hook it up to the A8's motherboard. I have no idea what the pinout is on the A8's mobo, and it's not indicated either. Most guides deal with using RAMPS when it comes to installing such a sensor. I'd like to know how to connect this to my board, if possible.</p> <p>The printer works fine otherwise, so I don't think the board is broken or anything. For now I've resumed using the normal endstop, but I would like to enable bed levelling by installing this sensor. (or a different one if necessary)</p> <p>How do I get this working?</p>
<p>I am not entirely familiar with the ANET A8 electronics, but it's very unlikely it's any different from how any other mainboard works, so any instructions that work for RAMPS should work for your board as well.</p> <p>The sensor you linked to has an operating voltage range of &quot;6V to 36V&quot;. However, the endstop connectors (on any mainboard I've come across) only provide 5V - not enough for the sensor to work. You could verify that this is also the case for your ANET board with a multimeter.</p> <p>(Assuming the colour coding is standard) you'll need to connect the black wire to GND, the red wire to 12V, and the yellow wire <strong>through a diode</strong> to the signal pin of the endstop connector. The anode of the diode should connect to the signal pin and the cathode to the wire coming from the sensor.</p> <p>The diode is required, because otherwise the 12V signal from the sensor will damage your electronics, which can only accept 5V. Any ordinary diode will do (for instance 1N4148). You should enable endstop pullups in your firmware when using this method (though if your board already has physical pullups this is not necessary but won't hurt either).</p> <p>Note that if the sensor is inductive, it will also need an appropriate (metal) surface to trigger off. Unfortunately, it is not clear from the product description what type of sensor you have bought, and (amusingly) gearbest doesn't know either:</p> <blockquote> <p>Question:</p> <p>Hello, is this Sensor capazitiv or induktiv? Thank you verry much.</p> <p>Reply:</p> <p>It is an auto leveling sensor for 3D printers</p> </blockquote>
<p>You will have to:</p> <ol> <li><p>Find and print something on Thingiverse to mount sensor;</p></li> <li><p>Change firmware to Skynet and change the offset values accordingly, in order for the new sensor to recognize the bed.</p></li> </ol> <p>There is official Facebook page of Anet A8 printers as well as Skynet firmware. You can ask there if you need further help. Though the above steps are easy. </p>
480
<p>We have a need to take dozens of different protocols from systems such as security systems, fire alarms, camera systems etc.. and integrate them into a single common protocol.</p> <p>I would like this to be a messaging server that many systems could subscribe to and or communicate through.</p> <ul> <li>polling and non-polling "drivers" (protocol converters)</li> <li>handle RS232 / RS485 / tcp</li> <li>programmable "drivers" in a managed language like Java or C#</li> <li>rules engine capability</li> </ul> <p>Does biztalk fit this? </p> <p>Are there open source alternatives?</p> <p>Is there a Java / Java EE way to do this?</p> <p>At one end the system would be a SCADA system at the other is is kind of a middleware / messaging server.</p> <p>Any thoughts on the best way to proceed would be appreciated. I know that there will be a considerable amount of programming involved on the driver side, however as tempted as I am, building the whole system from scratch would not be appropriate.</p>
<p>If you don't mind working on the Java platform there's a lightweight protocol switcher and implementation of the <a href="http://activemq.apache.org/camel/enterprise-integration-patterns.html" rel="nofollow noreferrer">Enterprise Integration Patterns</a> in an open source project called <a href="http://activemq.apache.org/camel/" rel="nofollow noreferrer">Apache Camel</a>.</p> <p>Camel can already speak most of the <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">common protocols and technologies</a> like <a href="http://activemq.apache.org/camel/file.html" rel="nofollow noreferrer">files</a>, <a href="http://activemq.apache.org/camel/mail.html" rel="nofollow noreferrer">email</a>, <a href="http://activemq.apache.org/camel/jms.html" rel="nofollow noreferrer">JMS</a>, <a href="http://activemq.apache.org/camel/xmpp.html" rel="nofollow noreferrer">XMPP</a> and so forth so there'd be no actual coding required for those things.</p> <p>To add new custom protocols the simplest route is to build on top of the <a href="http://activemq.apache.org/camel/mina.html" rel="nofollow noreferrer">MINA component</a> which takes care of all the networking, socket handling, threading and so forth (e.g. NIO versus BIO et al).</p> <p>Then you just extend it to add your own protocol codec (how to marshal/unmarshal messages on the socket with possibly using framing etc).</p> <p>The <a href="http://activemq.apache.org/camel/hl7.html" rel="nofollow noreferrer">HL7 component</a> is an example of doing this. More <a href="http://mina.apache.org/tutorial-on-protocolcodecfilter.html" rel="nofollow noreferrer">detail on writing MINA codecs here</a>.</p> <p>Then once you've got your camel component (lets call it foo) you could then bridge from any protocol to any other protocol using simple URIs to implement any of the <a href="http://activemq.apache.org/camel/enterprise-integration-patterns.html" rel="nofollow noreferrer">Enterprise Integration Patterns</a> such as <a href="http://activemq.apache.org/camel/content-based-router.html" rel="nofollow noreferrer">Content Based Router</a>, <a href="http://activemq.apache.org/camel/recipient-list.html" rel="nofollow noreferrer">Recipient List</a>, <a href="http://activemq.apache.org/camel/routing-slip.html" rel="nofollow noreferrer">Routing Slip</a> etc</p> <p>e.g. in Java code</p> <pre><code>// route all messages from foo // to a single queue on JMS from("foo://somehost:1234"). to("jms:MyQueue"); // route all messages from foo component // to a queue using a header from("foo://somehost:1234"). recipientList(). simple("activemq:MyPrefix.${headers.cheese}"); </code></pre>
<p>I suggest <a href="http://www.openscada.org" rel="nofollow noreferrer">OpenSCADA</a>. The website is at the moment a bit of a mess, but the software is actively in use and in active development. A explicit goal is to create a common, technology independent, interface for SCADA use cases (although at the moment the direction is more or less oriented towards java [but we experiment also with ikvm to create a .NET version]).</p> <p>So you could use OpenSCADA to communicate with all the "hardware" devices and then create a bridge to the rest of your middleware, or create a OpenSCADA bridge as a plugin within your middleware. We already have for instance drivers which connect to card readers linked via a serial server to the LAN.</p>
28,398
<pre><code>from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "single.py"}], zipfile = None, ) </code></pre> <p>in this setup file for py2exe where it says single.py is that where I place the name of my program?</p>
<p>I don't know your py2exe tool, but we usually use this way to convert py to exe:</p> <ol> <li><p>Download and install Standard Python Software: <a href="http://www.python.org/download/" rel="nofollow noreferrer">http://www.python.org/download/</a></p></li> <li><p>Download PyInstaller via link below: <a href="http://pyinstaller.python-hosting.com/" rel="nofollow noreferrer">http://pyinstaller.python-hosting.com/</a></p></li> <li><p>Unpack the archive, that you have downloaded! In this examople, the directory of the unpacked files: </p></li> <li><p>In the <code>&lt;UNPACKED_FILES_DIR&gt;</code> directory, run Configure.py. It must be run before trying to build anything.</p></li> <li><p>Create a spec file for your project:</p> <pre><code>python Makespec.py -F -p &lt;PYTHON_LIB_PATH&gt; &lt;PYTHON_SCRIPT&gt; -F: Produce a single file deployment. -p &lt;PYTHON_LIB_PATH&gt;: Set base path for import (like using PYTHONPATH). ( e.g.: C:\Program Files\Python24\Lib\ ) &lt;PYTHON_SCRIPT&gt;: Path to python script. </code></pre></li> </ol> <p>6 Build your project!</p> <pre><code> python Build.py &lt;SPECFILE&gt; &lt;SPECFILE&gt;: Path to the specfile, that have been created in step 4! The full path to &lt;SPECFILE&gt;: &lt;UNPACKED_FILES_DIR&gt;/&lt;PYTHON_SCRIPT&gt;/&lt;PYTHON_SCRIPT&gt;.spec </code></pre> <ol start="7"> <li>The binary file will be placed in the directory of <code>&lt;SPECFILE&gt;</code>.</li> </ol>
<p>Yes. Are you making a windowing application or a console application? See the example setup.py files that came with py2exe.</p>
36,401
<p>I have a string <code>User name (sales)</code> and I want to extract the text between the brackets, how would I do this? </p> <p>I suspect sub-string but I can't work out how to read until the closing bracket, the length of text will vary.</p>
<p>A very simple way to do it is by using regular expressions:</p> <pre><code>Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value </code></pre> <hr> <p>As a response to the (very funny) comment, here's the same Regex with some explanation:</p> <pre><code>\( # Escaped parenthesis, means "starts with a '(' character" ( # Parentheses in a regex mean "put (capture) the stuff # in between into the Groups array" [^)] # Any character that is not a ')' character * # Zero or more occurrences of the aforementioned "non ')' char" ) # Close the capturing group \) # "Ends with a ')' character" </code></pre>
<p>I came across this while I was looking for a solution to a very similar implementation.</p> <p>Here is a snippet from my actual code. Starts substring from the first char (index 0).</p> <pre><code> string separator = "\n"; //line terminator string output; string input= "HowAreYou?\nLets go there!"; output = input.Substring(0, input.IndexOf(separator)); </code></pre>
49,563
<p>Because I run a blog aggregator website which checks a large list of RSS feeds for new posts every hour so I will be happy if its possible to use google feed api or <a href="http://code.google.com/apis/ajaxfeeds/" rel="nofollow noreferrer">Google AJAX Feed API</a> instead of making the cron jobs to read the whole feed to know if its updated or not. like this <a href="http://getsatisfaction.com/rososo/topics/updates_dont_seem_to_be_dated_right" rel="nofollow noreferrer">link text</a></p>
<p>You can use the Google Feed API, however instead of polling the feed source every hour you will still need to poll the google feed API every hour. It doesn't notify you of feed updates. If you want to be notified when to update feeds, then you should look into using a ping server, <a href="http://en.wikipedia.org/wiki/Ping_blog" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Ping_blog</a> to determine when feeds are updated so that you know it is time to fetch the feed again. Not all feeds use a ping server, but it might help you for those that do.</p>
<p>As Nanek said, the Google Feed API won't notify you when a feed is changed... for this you'll have to use the <strong>PubSubHubbub</strong> protocol or services like <a href="https://superfeedr.com/subscriber" rel="nofollow">Superfeedr</a> which is a Google Feed API alternative.</p>
25,179
<p>I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS.</p>
<p>If you guys are still coding for IE6, you're making a mistake. </p> <p>I use <strong>IE7.js</strong> to get IE6 to render pages like IE7. IE7 is not perfect, but at least it has some semblance of standards. Since I only have to code for IE7 and FF it makes me 33% more efficient in terms of testing against browsers, something I think makes good business sense.</p> <p>Link: <a href="http://code.google.com/p/ie7-js/" rel="nofollow noreferrer">IE7.js</a></p>
<p>I write to the standards and both Firefox and IE7 follow a pretty good set in common. </p> <p>IE6 is dead as far as I am concerned but if I get back into professional web dev I'll probably have to revise that ;)</p>
4,570
<p>I upgraded my Ender 3 with a new Mobo, the 4.2.7 version.</p> <p>My current setup is:</p> <p>Printer Specifications:</p> <ul> <li>Ender 3</li> <li>Upgraded Motherboard 4.2.7 (Silent Stepper Drivers)</li> <li>Marlin FW Upgrade to Version 2.1.x</li> <li>New metal extruder handle</li> <li>Replacement bed springs</li> <li>New complete hot end</li> <li>Everything else is in stock</li> </ul> <p>Prior to the mobo upgrade, everything was working fine. Now I'm having problems with the extruder. I did use at first the Ender3 32bit 4.2.7 firmware, but it did happens too. The e-steps for the filament length have been adjusted. Once I start spinning the extruder, the extruder stepper starts grinding and jumping/rewinding the extruder wheel with the filament to the back; sometimes even 8-10 mm. Also, if I manually hold the filament back, it springs back. It seems that there is no power/power coming from the stepper motor.</p> <p>So I would like to check how much power the driver needs and gets. How or where can I find the required voltage for the drivers? How to adjust the drivers?</p> <p>Any tips or references are welcome.</p>
<p>There are different versions of the 4.2.7 main board. This is an excellent video made by <a href="https://www.youmaketech.com/how-to-adjust-stepper-motor-currents-on-ender-3-pro-v2/" rel="nofollow noreferrer">YouMakeTech</a>: <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/k2nm-WetPnU?start=0"></iframe> </div></div></p> <hr /> <p><em>To prevent the answer to become unusable due to <a href="https://en.wikipedia.org/wiki/Link_rot" rel="nofollow noreferrer">link rot</a>, a concise summary is shown below.</em></p> <p>The correct drivers can be &quot;read&quot; from the written letter on the card reader: <a href="https://i.stack.imgur.com/jwXQK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jwXQK.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/1gANf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1gANf.png" alt="enter image description here" /></a></p> <p>Depending on the driver, you need to find out what the maximum Vref for your stepper is (this depends on the maximum current rating of your stepper), e.g. for 2208, 2209 and 2225 drivers the Vref is calculated by the same equation: <a href="https://i.stack.imgur.com/lUWvp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lUWvp.png" alt="enter image description here" /></a></p> <p>The Imax (maximum curretn) is depending on the used stepper: <a href="https://i.stack.imgur.com/TUVYP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUVYP.png" alt="enter image description here" /></a></p> <p>Use the nominal values to prevent the steppers to become too hot.</p> <p>The Vref can be adjusted by the screw potentiometers next to the drivers, use a voltmeter while adjusting:</p> <p><a href="https://i.stack.imgur.com/rONzE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rONzE.png" alt="enter image description here" /></a></p>
<p>I would try to reinstall the old board and see if the extruder still skips.</p> <p>If the extruder is not having an issue with the old board installed, you'll need to visit <a href="https://www.creality.com/pages/download-ender-3?spm=..page_1934481.products_display_1.1" rel="nofollow noreferrer">Creality's Updates page</a> and install the Marlin 2.0 firmware designed for the 4.2.7 board. Please use a how-to video on YouTube for installing your new board, you will need to calibrate E-Steps, calibrate PID Temperatures, etc. as outlined in the video.</p> <p>If the extruder continues its behavior, the extruder is under-extruding. Please check out <a href="https://www.3dsourced.com/rigid-ink/ultimate-3d-printing-troubleshooting-guide/#inconsistent-extrusion-under" rel="nofollow noreferrer">The Holy Bible of 3D Printing troubleshooting: Underextruding printer</a> to get to the bottom of it before you upgrade to your new silent board. Then I can pretty much guarantee you have either a clogged nozzle or a hotend that's too cold during printing to melt the plastic at a fast enough rate.</p> <p>The third thing is you need to upgrade the stock Ender 3 extruder because the stock black extruder bracket is absolute garbage, and it alone would cause a skipping and flaking extruder. Get the sweet stainless grey one for 15 USD on amazon. Blame Creality for that oversight.</p> <p>Please respond back if this didn't help.</p>
2,226
<p>I have a couple of questions about generic wildcards in Java:</p> <ol> <li><p>What is the difference between <code>List&lt;? extends T&gt;</code> and <code>List&lt;? super T&gt;</code>?</p></li> <li><p>What is a bounded wildcard and what is an unbounded wildcard?</p></li> </ol>
<p>In your first question, <code>&lt;? extends T&gt;</code> and <code>&lt;? super T&gt;</code> are examples of bounded wildcards. An unbounded wildcard looks like <code>&lt;?&gt;</code>, and basically means <code>&lt;? extends Object&gt;</code>. It loosely means the generic can be any type. A bounded wildcard (<code>&lt;? extends T&gt;</code> or <code>&lt;? super T&gt;</code>) places a restriction on the type by saying that it either has to <em>extend</em> a specific type (<code>&lt;? extends T&gt;</code> is known as an upper bound), or has to be an ancestor of a specific type (<code>&lt;? super T&gt;</code> is known as a lower bound).</p> <p>The Java Tutorials have some pretty good explanations of generics in the articles <a href="http://java.sun.com/docs/books/tutorial/java/generics/wildcards.html" rel="noreferrer">Wildcards</a> and <a href="http://java.sun.com/docs/books/tutorial/extra/generics/morefun.html" rel="noreferrer">More Fun with Wildcards</a>.</p>
<p>learn by example:</p> <p>consider the <code>sort()</code> method in <code>Collections</code> class which use both <code>extends</code> and <code>super</code>:</p> <pre><code> public static &lt;T extends Comparable&lt;? super T&gt;&gt; void sort(List&lt;T&gt; list){...} </code></pre> <p>so</p> <p><strong>why <code>&lt;T extends Comparable&lt;...&gt;&gt;</code>:</strong> becuase we <strong>need</strong> list items (<code>T</code>) to be a subclass of the <code>Comparable</code> interface.</p> <p><strong>why <code>Comparable&lt;? super T&gt;</code>:</strong> becuase we <strong>allow</strong> the <code>Comparable</code> type to be a <strong>Comparable of any super type of T</strong>.</p> <p>Consider</p> <pre><code>interface Comparable&lt;T&gt;{ public int compareTo(T o); } public static &lt;T extends Comparable&lt;? super T&gt;&gt; void sort(List&lt;T&gt; list){...} public static &lt;T extends Comparable&lt;T&gt;&gt; void sort2(List&lt;T&gt; list){...} class A implements Comparable&lt;A&gt;{ @Override public int compareTo(A o) { ... } } class B extends A { } List&lt;A&gt; listA = new ArrayList&lt;&gt;(); List&lt;B&gt; listB = new ArrayList&lt;&gt;(); sort(listA); //ok sort(listB); //ok sort2(listA); //ok sort2(listB); //Error </code></pre>
31,402
<p>In previous versions of VS, if you right-clicked a breakpoint's red dot and selected Disable Breakpoint, the dot would become 'hollow', and clicking it again would re-enable it. But in VS2008, disabling the breakpoint removes the red dot entirely and you need to go to the Breakpoints window to re-enable.</p> <p>Anyone know how to get the previous versions' behavior? I have a few BP's that I toggle often, and its a bit of a PITA to do it in this way. I don't understand why MS took this away.</p> <p>EDIT: I installed SP1 yesterday - because without it, VS would crash as soon as I tried to CTRL+F. Nice testing, Microsoft! Same problem happens pre-SP.</p> <p>I hadn't touched the default color scheme, and checking it indicates that it should be a hollow dot. I tried changing it to no avail. In fact, I can't even change the enabled breakpoint's color.</p> <p>This is a Windows XP 64-bit machine. I'm guessing this is the root of the problems.</p>
<p>Looks like a bug in VS 2008 SP1.</p> <p><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366060" rel="nofollow noreferrer"><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366060" rel="nofollow noreferrer">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366060</a></a></p>
<p>I have VS2008 SP1 and it has the 'diasble breakpoint' functionality you describe... do you have SP1 installed? Maybe it's a bug?</p>
28,907
<p>I'm looking for a regular expression that will match all strings EXCEPT those that contain a certain string within. Can someone help me construct it?</p> <p>For example, looking for all strings that <em>do not</em> have a, b, and c in them in that order.</p> <p>So <br /> abasfaf3 would match, whereas <br /> asasdfbasc would not</p>
<p>in perl:</p> <pre><code>if($str !~ /a.*?b.*?.*c/g) { print "match"; } </code></pre> <p>should work.</p>
<p>in Java:</p> <pre><code>(?m)^a?(.(?!a[^b\r\n]*b[^\r\nc]*c))+$ </code></pre> <p>does match</p> <pre><code>abasfaf3 xxxabasfaf3 </code></pre> <p>does not match</p> <pre><code>asasdfbascf xxxxasasdfbascf </code></pre>
41,732
<p>I am working on an application where I have an images folder relative to my application root. I want to be able to specify this relative path in the Properties -> Settings designer eg. "\Images\". The issue I am running into is in cases where the Environment.CurrentDirectory gets changed via an OpenFileDialog the relative path doesn't resolve to the right location. Is there a way to specifiy in the Settings file a path that will imply to always start from the application directory as opposed to the current directory? I know I can always dynamically concatenate the application path to the front of the relative path, but I would like my Settings property to be able to resolve itself.</p>
<p>As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use <code>Environment.CurrentDirectory</code> specifically for the reasons you mention - the current directory may not always be correct for this situation.</p> <p>The safest code I've found to find the executing assembly location is this:</p> <pre><code>public string ExecutingAssemblyPath() { Assembly actualAssembly = Assembly.GetEntryAssembly(); if (this.actualAssembly == null) { actualAssembly = Assembly.GetCallingAssembly(); } return actualAssembly.Location; } </code></pre>
<p>2 options:</p> <ul> <li>The code that uses the setting can resolve the setting against the directory of the current executing assembly.</li> <li>You can create your own type that serializes as a string relative to the executing assembly, and has an accessor for the full path that will resolve against the directory of the current executing assembly.</li> </ul> <p>Code sample:</p> <pre><code>string absolutePath = Settings.Default.ImagePath; if(!Path.IsPathRooted(absolutePath)) { string root = Assembly.GetEntryAssembly().Location; root = Path.GetDirectoryName(root); absolutePath = Path.Combine(root, absolutePath); } </code></pre> <p>The nice thing about this code is that it allows a fully qualified path, or a relative path, in your settings. If you need the path to be relative to a different assembly, you can change which assembly's location you use - <code>GetExecutingAssembly()</code> will give you the location of the assembly with the code you're running, and <code>GetCallingAssembly()</code> would be good if you go with option 2.</p>
36,035
<p>Is there a way to have a file that is modified / touched whenever the WC is updated to a new revision? Or, as the second-best option, whenever <code>svn update</code> is executed?</p> <p>Here's the motivation: I want to have the SVN revision number inside my executable. So I have to run SubWCRev as part of the build. The output file of SubWCRev is re-created every time, even if the revision number has not changed. This means that the exe is linked on every build, even if nothing has changed. I want it to be linked only as needed.</p>
<ol> <li>Get the SubWCRev output into a temporary file</li> <li>Compare this file to the current revision-number file</li> <li>Overwrite it with the temp file only if the two are different</li> <li>Delete the temporary file</li> </ol> <p>You might even be able to do this with a .bat file (using <code>fc</code>). Something like...</p> <pre><code>REM ***UNTESTED*** FC temp.rev curr.rev | FIND "FC: no dif" &gt; nul IF NOT ERRORLEVEL 1 COPY /Y temp.rev curr.rev DEL temp.rev </code></pre> <p><strong>Edit:</strong> As an aside, you can do this in Mercurial by making the rev-number-file depend on <code>.hg/dirstate</code>.</p>
<p>My answer will probably be too short, but might give you some direction.</p> <p>SVN has hooks. They are scripts that get executed everytime code is commited.</p> <p>Maybe?</p>
19,219
<p>Why was the <code>arguments.callee.caller</code> property deprecated in JavaScript?</p> <p>It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.</p> <p>Is there a good reason to put this valuable functionality in limbo?</p> <p>(Or alternately, is there a better way to grab a handle on the calling function?)</p>
<p>Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression:</p> <pre><code> // This snippet will work: function factorial(n) { return (!(n&gt;1))? 1 : factorial(n-1)*n; } [1,2,3,4,5].map(factorial); // But this snippet will not: [1,2,3,4,5].map(function(n) { return (!(n&gt;1))? 1 : /* what goes here? */ (n-1)*n; }); </code></pre> <p>To get around this, <code>arguments.callee</code> was added so we could do:</p> <pre><code> [1,2,3,4,5].map(function(n) { return (!(n&gt;1))? 1 : arguments.callee(n-1)*n; }); </code></pre> <p>However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different <code>this</code> value, for example:</p> <pre><code>var global = this; var sillyFunction = function (recursed) { if (!recursed) return arguments.callee(true); if (this !== global) alert("This is: " + this); else alert("This is the global"); } sillyFunction(); </code></pre> <p>Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.:</p> <pre><code> [1,2,3,4,5].map(function factorial(n) { return (!(n&gt;1))? 1 : factorial(n-1)*n; }); </code></pre> <p>This has numerous benefits:</p> <ul> <li><p>The function can be called like any other from inside your code.</p></li> <li><p>It does not pollute the namespace.</p></li> <li><p>The value of <code>this</code> does not change.</p></li> <li><p>It's more performant (accessing the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments" rel="noreferrer">arguments object</a> is expensive).</p></li> </ul> <h3>Whoops,</h3> <p>Just realised that in addition to everything else the question was about <code>arguments.callee.caller</code>, or more specifically <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller" rel="noreferrer"><code>Function.caller</code></a>.</p> <p>At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult.</p> <p>Eg. if we can't guarantee that a function <code>f</code> will not call an unknown function, then it is not possible to inline <code>f</code>. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take:</p> <pre><code> function f(a, b, c, d, e) { return a ? b * c : d * e; } </code></pre> <p>If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function.</p> <p>Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.</p>
<p>Just an extension. The value of "this" changes during recursion. In the following (modified) example, factorial gets the {foo:true} object.</p> <pre><code>[1,2,3,4,5].map(function factorial(n) { console.log(this); return (!(n&gt;1))? 1 : factorial(n-1)*n; }, {foo:true} ); </code></pre> <p>factorial called first time gets the object, but this is not true for recursive calls.</p>
12,925
<p>I was wondering which was better:</p> <pre><code>$lookup = array( "a" =&gt; 1, "b" =&gt; 2, "c" =&gt; 3 ); return $lookup[$key]; </code></pre> <p>or</p> <pre><code>if ( $key == "a" ) return 1 else if ( $key == "b" ) return 2 else if ( $key == "c" ) return 3 </code></pre> <p>or maybe just a nice switch...</p> <pre><code>switch($key){ case "a": return 1; case "b": return 2; case "c": return 3; } </code></pre> <p>I always prefer the first method as I can separate the data from the code; At this scale it looks quite silly but on a larger scale with thousands of lines of lookup entries; How much longer is PHP going to take building an array and then only checking maybe 1 or 2 entries per request.</p> <p>I think it'd have to be tested and clocked, but I'd say the bigger and more complicated the array the slower it's going to become.</p> <p>PHP Should be able to handle lookups faster than I can in PHP-code, but building the array in the first place surely takes up a lot of time.</p>
<p>For anything with measurable performance (not only 3 entries) lookup is fastest way. That's what hash tables are for.</p>
<p>If you've got thousands of entries, an array lookup will win hands down. The associative array might be a bit slow, but finding an array key is much faster than doing thousands of <code>if()</code> blocks (not to mention the time it takes to type it all out!)</p>
44,760
<p>I am designing the (G)UI of a program, and have stumbled across a problem; The program will convert a number into different units, and the layout of a unit been converted to is:</p> <p>[Unit name (when clicked gives information)] [Special status, if any] [Output in textfield that can also be used for input (to convert to other units)]</p> <p>I want the user to be able to copy an outputnumber onto the clipboard, without having to mess around with highlighting and finding the right buttons to press. So, I thought I'd make a button after the text-output field, saying something like "C" or "Copy".</p> <p>But I was reading on <a href="http://www.joelonsoftware.com/uibook/chapters/fog0000000063.html" rel="nofollow noreferrer">joelonsoftware.com</a> yesterday, and discovered that users seem to be cursorclumsy. So what should I do?</p> <p>I've thought about a number of different options:</p> <ol> <li>Click on textfield to copy to clipboard - BUT: I want to use it for input as well</li> <li>Pressing a numeral on the keyboard to copy the respective one - BUT: There will probably be more than 10, and I need them for new input</li> <li>Bigger Copy button, like on that actually says "Copy" - Hmm, would this work? I know that I like to use the keyboard when I can, so a solution involving it would be nice.</li> <li>Each unit will have its own space, where everything (name, textfield etc.) fits in. What if it would copy to clipboard when clicked anywhere in that space except for on the name or textfield. - BUT: What if you miss, meaning to click below one textfield, and clicking above another?</li> <li>But what about highlighting the unit's space as I went along? - Could still mean trouble...</li> </ol> <p>What do you think? I think I just might opt for #3 - Bigger copy-button..</p>
<p>There's nothing wrong with a Copy button after every field if you feel that it's going to be a very common operation. </p> <p>Two suggestions, however:</p> <ol> <li><p>In terms of look and feel, make sure that the button is clearly associated with the field. For a text field, the best way to do this is to put the Copy button inside the text field (on the right side - but be prepared to handle RTL languages by switching its position as needed!).</p></li> <li><p>To avoid making it overly big, don't use any text, but rather use the stock Windows icon for Copy (like this one: <img src="https://getinvolved-donate.fao.org/pub_libs21/fck_alt/editor/skins/silvernarrow/toolbar/copy.gif">), and put the text into its tooltip. If you do that, you may also get rid of button border entirely, further reducing its size, though you'd still want some visual hover indicator to make it clear that it's an active UI element. In fact, you might want to specifically copy Vista/Win7 Explorer (also seen in IE7/8) UI for location field and the Reload icon in it.</p></li> </ol>
<p>If you accidentally click on the wrong area, you could just click on the right area after that. If your issue lies in the user not knowing when they click on the wrong area, just highlight the last-clicked area.</p> <p>Is there a problem with copying whatever is in the textfield when they click on it? So what if it's being used for input? They're just going to copy the value they need <i>after</i> they type values in.</p> <p>You could also have a <code>ctrl-click</code> or <code>shift-click</code> in the text box be a copy.</p> <p>Most people know how to copy text on their own computer. Perhaps the best solution is to just auto-highlight all the text in a textbox when it gets focus so they can just ctrl-c to copy or start typing to begin input.</p>
38,777
<p>For a complex web application that includes dynamic content and personalization, what is a good response time from the server (so excluding network latency and browser rendering time)? I'm thinking about sites like Facebook, Amazon, MyYahoo, etc. A related question is what is a good response time for a backend service? </p>
<p>There's a great deal of research on this. Here's a <a href="http://www.useit.com/papers/responsetime.html" rel="noreferrer">quick summary</a>.</p> <blockquote> <h2>Response Times: The 3 Important Limits</h2> <p>by <a href="http://www.nngroup.com/articles/author/jakob-nielsen/" rel="noreferrer">Jakob Nielsen</a> on January 1, 1993</p> <p>Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.</p> <p><em>Excerpt from Chapter 5 in my book <a href="http://www.nngroup.com/books/usability-engineering/" rel="noreferrer">Usability Engineering</a>, from 1993:</em></p> <p>The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:</p> <ul> <li><strong>0.1 second</strong> is about the limit for having the user feel that the system is <strong>reacting instantaneously</strong>, meaning that no special feedback is necessary except to display the result.</li> <li><strong>1.0 second</strong> is about the limit for the <strong>user's flow of thought</strong> to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.</li> <li><strong>10 seconds</strong> is about the limit for <strong>keeping the user's attention</strong> focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.</li> </ul> </blockquote>
<p>2 to 3 seconds</p>
19,848
<p>because i read that one of the advantages of <a href="http://en.wikipedia.org/wiki/WS-Discovery" rel="nofollow noreferrer">WS-Discovery</a> that it "Support both SOAP 1.1 and SOAP 1.2 Envelopes" so what?</p>
<p>thanks for your replies. I toyed around with doing both of these suggestions but neither is "exactly" what I was looking for - even if it gets the job done. I can't see us ever going back to 1.1 either so we did end up making it the default but i'm still holding out hope that there's a magic setting on some task that can do this.</p> <p>thanks again</p>
<p>None of this works simple as the following lines:</p> <p>First, create the website directory:</p> <pre><code>&lt;WebDirectoryCreate ServerName="$(DeployServerName)" VirtualDirectoryName="MyVirualSiteName" /&gt; </code></pre> <p>Second, Apply the ASP.NET version you want:</p> <pre><code>&lt;InstallAspNet Path="W3SVC/1/Root/MyVirualSiteName" Version="Version20" /&gt; </code></pre> <p>Have my best,</p>
46,104
<p>I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. </p> <p>Here's the scenario, I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.</p> <p>Here's the 'servstop.txt' file contents:</p> <blockquote> <p>[SC] StartService FAILED 1058:</p> <p>The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.</p> </blockquote> <p>I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058" and the body to contain the entire error message above.</p> <p>I will put my current method in an answer below using a program called blat to send me the result.</p>
<p>Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank <code>xmlns</code> attributes: pass in the root node's namespace when creating any child node you want <em>not</em> to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to <em>also</em> not have prefixes.</p> <p>Fixed Code:</p> <pre><code>XmlDocument xml = new XmlDocument(); xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0")); xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); Console.WriteLine(xml.OuterXml); </code></pre> <p>Thanks everyone to all your answers which led me in the right direction!</p>
<p>If possible, create a serialization class then do:</p> <pre><code>XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer serializer = new XmlSerializer(yourType); serializer.Serialize(xmlTextWriter, someObject, ns); </code></pre> <p>It's safer, and you can control the namespaces with attributes if you really need more control.</p>
16,354
<p>What's the best way to pipe the output from an java.io.OutputStream to a String in Java?</p> <p>Say I have the method:</p> <pre><code> writeToStream(Object o, OutputStream out) </code></pre> <p>Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.</p> <p>I'm considering writing a class like this (untested):</p> <pre><code>class StringOutputStream extends OutputStream { StringBuilder mBuf; public void write(int byte) throws IOException { mBuf.append((char) byte); } public String getString() { return mBuf.toString(); } } </code></pre> <p>But is there a better way? I only want to run a test!</p>
<p>I would use a <code>ByteArrayOutputStream</code>. And on finish you can call:</p> <pre><code>new String( baos.toByteArray(), codepage ); </code></pre> <p>or better:</p> <pre><code>baos.toString( codepage ); </code></pre> <p>For the <code>String</code> constructor, the <code>codepage</code> can be a <code>String</code> or an instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html" rel="noreferrer">java.nio.charset.Charset</a>. A possible value is <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8" rel="noreferrer">java.nio.charset.StandardCharsets.UTF_8</a>.</p> <p>The method <code>toString()</code> accepts only a <code>String</code> as a <code>codepage</code> parameter (stand Java 8).</p>
<p>Here's what I did (don't use this in production, this is not great! But it makes fixing multiple errors easier.)</p> <ul> <li><p>Create a list that holds Exceptions.</p> </li> <li><p>Create a logger to log exceptions.</p> </li> <li><p>Use the code below:</p> <p>private static void exceptionChecker() throws Exception { if(exceptionList.isEmpty()) return; //nothing to do :) great news</p> <pre><code> //create lock for multithreading synchronized (System.err){ //create new error stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream errorOut = new PrintStream(byteArrayOutputStream); //save standard err out PrintStream standardErrOut = System.err; try{ //set new error stream System.setErr(errorOut); exceptionList.forEach(exception -&gt; { exception.printStackTrace(); System.err.println(&quot;&lt;----------&gt;&quot;); }); } finally { //reset everything back to normal System.setErr(standardErrOut); //Log all the exceptions exceptionLogger.warning(byteArrayOutputStream.toString()); //throw final generic exception throw new Exception(); } }} </code></pre> </li> </ul> <p>This isn't great as you are throwing an error in the finally block and it locks on the error stream, but it works for dev purposes.</p>
26,667
<p>Does anyone have any good suggestions for creating a Pipe object in Java which <em>is</em> both an InputStream and and OutputStream since Java does not have multiple inheritance and both of the streams are abstract classes instead of interfaces?</p> <p>The underlying need is to have a single object that can be passed to things which need either an InputStream or an OutputStream to pipe output from one thread to input for another.</p>
<p>It seems the point of this question is being missed. If I understand you correctly, you want an object that functions like an InputStream in one thread, and an OutputStream in another to create a means of communicating between the two threads.</p> <p>Perhaps one answer is to use composition instead of inheritance (which is recommended practice anyway). Create a Pipe which contains a PipedInputStream and a PipedOutputStream connected to each other, with getInputStream() and getOutputStream() methods.</p> <p>You can't directly pass the Pipe object to something needing a stream, but you can pass the return value of it's get methods to do it.</p> <p>Does that work for you?</p>
<p>I had to implement a filter for slow connections to Servlets so basically I wrapped the servlet output stream into a QueueOutputStream which will add every byte (in small buffers), into a queue, and then output those small buffers to a 2nd output stream, so in a way this acts as input/output stream, IMHO this is better than JDK pipes which won't scale that well, basically there is too much context switching in the standard JDK implementation (per read/write), a blocking queue is just perfect for a single producer/consumer scenario:</p> <pre><code>import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.*; public class QueueOutputStream extends OutputStream { private static final int DEFAULT_BUFFER_SIZE=1024; private static final byte[] END_SIGNAL=new byte[]{}; private final BlockingQueue&lt;byte[]&gt; queue=new LinkedBlockingDeque&lt;&gt;(); private final byte[] buffer; private boolean closed=false; private int count=0; public QueueOutputStream() { this(DEFAULT_BUFFER_SIZE); } public QueueOutputStream(final int bufferSize) { if(bufferSize&lt;=0){ throw new IllegalArgumentException("Buffer size &lt;= 0"); } this.buffer=new byte[bufferSize]; } private synchronized void flushBuffer() { if(count&gt;0){ final byte[] copy=new byte[count]; System.arraycopy(buffer,0,copy,0,count); queue.offer(copy); count=0; } } @Override public synchronized void write(final int b) throws IOException { if(closed){ throw new IllegalStateException("Stream is closed"); } if(count&gt;=buffer.length){ flushBuffer(); } buffer[count++]=(byte)b; } @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { super.write(b,off,len); } @Override public synchronized void close() throws IOException { flushBuffer(); queue.offer(END_SIGNAL); closed=true; } public Future&lt;Void&gt; asyncSendToOutputStream(final ExecutorService executor, final OutputStream outputStream) { return executor.submit( new Callable&lt;Void&gt;() { @Override public Void call() throws Exception { try{ byte[] buffer=queue.take(); while(buffer!=END_SIGNAL){ outputStream.write(buffer); buffer=queue.take(); } outputStream.flush(); } catch(Exception e){ close(); throw e; } finally{ outputStream.close(); } return null; } } ); } </code></pre>
47,633
<p>Instead of arranging controls on a winform form by specifying pixel locations, I'd like to lay it out similar to the way you'd layout a form in html. This would make it scale better (for larger fonts etc).</p> <p>Does anyone know of a layout library that allows you to define the form in xml and lay it out similar to html?</p>
<p>Have you checked out the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx" rel="nofollow noreferrer">TableLayoutPanel</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.aspx" rel="nofollow noreferrer">FlowLayoutPanel</a> in the .NET framework? It might be what you are looking for.</p>
<p>You may also want to consider using Windows Presentation Foundation (WPF) instead of WinForms - WPF has an XML declarative markup language (XAML) that works well for defining scalable UI.</p>
7,217
<p>Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.</p> <p><img src="https://i.stack.imgur.com/ss2sE.png" alt="alt text"></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms533259.aspx" rel="noreferrer">MSDN Device Context Functions</a></p> <p>What you basically need to do:</p> <blockquote> <p>Use the EnumDisplayDevices() API call to enumerate the display devices on the system and look for those that don't have the <code>DISPLAY_DEVICE_ATTACHED_TO_DESKTOP</code> flag set (this will include any mirroring devices so not all will be physical displays.) Once you've found the display device you'll need to get a valid display mode to change it to, you can find this by calling the EnumDisplaySettingsEx() API call - Generally you'd display all the available modes and allow the user to choose however in your case it sounds like this may be possible to hard-code and save you an additional step. For the sake of future-proofing your application though I'd suggest having this easily changeable without having to dig through the source every time, a registry key would be the obvious choice. Once you've got that sorted out populate a DevMode display structure with the information about the display positioning (set the PelsWidth/Height, Position, DisplayFrequency and BitsPerPel properties) then set these flags in the fields member. Finally call ChangeDisplaySettingsEx() with this settings structure and be sure to send the reset and update registry flags. That should be all you need, hope this helps,</p> </blockquote> <p><a href="http://www.pinvoke.net/default.aspx/Structures/DISPLAY_DEVICE.html" rel="noreferrer">DISPLAY_DEVICE</a> structure import using PInvoke</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/EnumDisplayDevices.html" rel="noreferrer">EnumDisplayDevices</a> function import</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/EnumDisplaySettingsEx.html" rel="noreferrer">EnumDisplaySettingsEx</a> function import</p> <p>etc. the rest of them functions can be found with a simple search by name.</p>
<p>To enable a monitor, set its position to something other than 0,0, like as shown:</p> <pre><code>POINTL enabledPosition = new POINTL(); enabledPosition.x = -1280; enabledPosition.y = 0; dm.dmPosition = enabledPosition; dm.dmFields = DM.Position; res = ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, (uint) DeviceFlags.CDS_UPDATEREGISTRY, IntPtr.Zero); </code></pre>
28,891
<p>I have CLI/MFC application and I would like to begin to learn how to unit test with it. I have VS2008 Pro. If possible, I would like to use the built in unit testing. Thanks for your input!</p>
<p>I've had success with both <a href="http://sourceforge.net/projects/cppunit" rel="nofollow noreferrer">CPPUnit</a> and <a href="http://code.google.com/p/googletest/" rel="nofollow noreferrer">Google Test</a>. For either you have to do a bit of work to get the test results to integrate back into Studio. The granularity of the results you want directly affects how much work. Do you want a pass/fail for the whole test set, or individual results? The former is a simple msbuild task, the latter requires outputting the result set to XML, massaging that with a transform, then pulling it back in.</p>
<p>We use Gallio &amp; MbUnit to test our MFC &amp; C++/CLI application. Simply write the tests in C++/CLI then you can test both managed and unmanged code in a single framework. We also use NMock2 for mocking the managed code.</p>
44,796
<p>Currently I have a ListView (using the Details View). I would like to implement the behaviour whereby when a user selects a single item (log entry) the log entry expands (from one line to multiple lines) to provide more detailed information about the error that occured.</p> <p>My question is this: Is this possible? If so, is there a good resource that I can use to help me?</p> <p>EDIT:</p> <p>If I <em>HAVE</em> to use WPF, then I guess Ill use the ElementHost with the control. However, I have absolutely no idea as to how about designing/coding/using WPF components. Any suggestions?</p>
<p>Edit: sorry this is wpf</p> <p>The trick I used to achieve the same thing was creating a trigger to show a secondary grid which is defaulted to collapsed.</p> <p>Try this out:</p> <pre><code> &lt;ListBox ItemsSource="{Binding}"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition&gt;&lt;/RowDefinition&gt; &lt;RowDefinition&gt;&lt;/RowDefinition&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid Grid.Row="0" Height="20" &gt; &lt;TextBlock Text="Not Selected"&gt;&lt;/TextBlock&gt; &lt;/Grid&gt; &lt;Grid x:Name="selectedOnlyGrid" Grid.Row="1" Visibility="Collapsed"&gt; &lt;TextBlock Text="Selected"&gt;&lt;/TextBlock&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1}, Path=IsSelected}" Value="True"&gt; &lt;Setter Property="Visibility" Value="Visible" TargetName="selectedOnlyGrid" /&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre>
<p>Not a direct answer to your question, but I think you're better off with a grid in this case.</p>
38,190
<p>I bought a set of 5 <a href="https://a.aliexpress.com/_mL7Tt7b" rel="nofollow noreferrer">stepper motors</a> from Trianglelab's official Aliexpress shop.</p> <p><a href="https://i.stack.imgur.com/XZDW8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XZDW8.jpg" alt="enter image description here" /></a></p> <p>Only one of these motors was given any kind of protective bubble wrap for shipping. The contents of the package shifted in transit and several of the motors got banged up with two of them suffering visible damage to their wire insulation.</p> <p>I contacted Trianglelabs and was told to fix it myself for \$0.03 with a wire or to add some tape. This repair advice was accompanied with the weightiest assumptions of my personal expertise that I have ever received.</p> <p>At this point I'm not planning to keep them if this is how the company does business; shaving pennies on shipping and telling the buyer to fix it themselves.</p> <p>But all of this brought up an interesting question. How can I reliably test my stepper motors for basic functionality and measured compliance with the rated specifications?</p>
<p>For the AliExpress part, open a dispute and attach pictures to the dispute and ask for a partial, reasonable discount. It always worked for me.</p> <p>As for how to test the motors themselves, it depends on what other hardware you have.</p> <p>For example, you could wire the motors to your printer board, and try to issue a <a href="https://marlinfw.org/docs/gcode/G006.html" rel="nofollow noreferrer">G6</a> command to that motor.</p> <p>If you find issues while testing the motors, that could be evidence for an even bigger discount, or even full refund if the motor doesn't work.</p>
<p>I would be far more worried about damage to the wire insulation (i.e. are they nicked/cut at all or just scuffed up?) as that could potentially lead to a short circuit situation against your frame etc. Assuming no serious cable damage, motors can take a fair amount of mechanical abuse so I'd just put them through their paces with short (a few seconds) forward/backward movements at various speeds listening for any scraping/grinding/other unusual noises indicating any interior damage. Assuming no issues found, then you could run them for a more extended period of time (5-10 minutes or so periodically changing direction/speed) and if that didn't reveal anything, I wouldn't worry about it. If it helps, you're probably going to inadvertently abuse them electrically/thermally far more than the shipment did over their service life.</p> <p>Unfortunately, when shipping things overseas sometimes the packaging is insufficient (somewhat surprising for Trianglelab as that's one area I generally see people give them high marks for) and bad things can happen during shipment. I've received all sorts of mangled packages and, aside from the irritation of knowing it was probably avoidable but for the bad packaging, I usually try to be reasonable when tallying up any damage when asking for a refund (partial or otherwise). If you really feel like a seller fell short, then your best recourse is generally to ding them on their rating if it's really warranted. Yes, it's irritating, but it will happen from time to time.</p>
1,788
<p>Marlin offers a bunch of different choices for auto-levelling and assisted manual levelling for bent build plates (mesh levelling), but for the moment I want to level things completely manually.</p> <p>That is, I want to move Z to 0, disable steppers, and then move around the print head and adjust the distance between bed and nozzle at various points with a piece of paper.</p> <p>With the old Repetier based firmware on my printer, selecting "home all axes" did not only home XYZ to endstops, but it also moved the head to position (0, 0, 0) afterwards. Then I could simply disable steppers via the menu and go on with my levelling. Note that in my case, the coordinates of the endstop positions are negative for all axes, so moving to the endstops alone isn't cutting it.</p> <p>With Marlin, selecting the "auto home" option merely moves to the endstops and then to some positive Z position (+10). This means I have to use the menu to manually move Z back to 0, which is quite inconvenient, unless I have a PC nearby that allows me to enter G-code.</p> <p>So, that leaves two related questions for me:</p> <p>Is there some simple way to move to (0, 0, 0) with the menu?</p> <p>Can I implement an assisted manual levelling (i.e. some procedure that simply moves the head between a number of different X/Y positions) easily? Does something like that already exist? If not, I wonder why.</p>
<p>Write a few pieces of gcode to do this. Place it on an SD-card (I assume you have a reader) and select the file you want to execute.</p> <p>Home all:</p> <pre><code>G28 G1 Z0 </code></pre> <p>Do you really want to home it directly? I would say you want to take it down slowly and adjusting end-stops incrementally.</p> <p>First:</p> <pre><code>G28 G1 Z10 </code></pre> <p>Then</p> <pre><code>G28 G1 Z3 </code></pre> <p>Then</p> <pre><code>G28 G1 Z1 </code></pre> <p>etc etc</p> <p>You can also move it around in the X and Y plane:</p> <pre><code>G28 G1 Z5 X50 Y30 </code></pre>
<p>The way I manually level my bed is by connecting a computer to the printer via USB. As far as I am aware, if you have a touchscreen this should be available on the printer options as well for marlin.</p> <p>But if you connect a computer, simply run something like pronterface or any other manual control gui and:</p> <p>1) home axes</p> <p>2) disable motors</p> <p>3) move printhead in x/y directions as necessary by hand</p> <p>4) adjust z height manually with the GUI software. This should not affect your x/y positions or turn on their motors.</p>
532
<p>I'm doing this system <a href="http://stacked.ra-ajax.org/" rel="nofollow noreferrer">Stacked</a> and I am creating the search function. And in that process it occurs to me that <em>maybe</em> AR/nHibernate Expression.Like (and siblings) might maybe not be 100% "safe" in that you can create stuff like; "\r\ndrop database xxx;---" and similar things...?</p> <p>I would expect them to be safe, but I am not sure...</p>
<p>NHibernate (and by extension ActiveRecord) generate parameterized SQL statements of the form <code>sp_executesql 'select blah from table where column = @p1', '@p1 varchar(10)', @p1 = 'drop database xxx;---'</code> for queries. These types of SQL statements are safe from SQL injection because the contents of the parameters are not executed (unlike they would be if simple concatenation was used). </p> <p>So yes, both are "safe".</p>
<p>If you find a security bug, you should definitely file it. Many rely on such things.</p>
43,137