text
stringlengths
8
267k
meta
dict
Q: Case Sensitivity when querying SQL Server 2005 from .NET using OleDB I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds. Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers. Thanks in advance for any help with this. Code Sample Below (The Difference in in the first line of the query at the end (fk_source vs. fk _Source): //Original OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " + "CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn); //Rebuilt OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " + "ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " + "CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn); A: I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries). Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then I ran the same query with different capitlization and I was surprised to see the procedure count higher. Try this.... Connect to SQL Server Management Studio. DBCC MemoryStatus Select Columns... From TABLES.... Where.... dbcc MemoryStatus Select Columns... From tables.... Where.... dbcc MemoryStatus I think you'll find that the TotalProcs changes when the statement changes (even when the only change is case sensitive). Updating your statistics may help. That is a rather slow running process, so you may want to run that during a slow period. A: Since you are using SQL Server 2005, have you tried with a SqlCommand object instead of the OleDbCommand object? A: I'm not seeing a difference in your queries which would affect performance - what about caching or index/statistics changes between runs? The execution plan may have changed due to statistics or index changes. Regarding the case: Case can matter if the database is set to be case-sensistive, but for both queries to run in a case-sensitive database, there would have to be columns named in both formats - the query parser will obey the case - it won't cause a performance difference. A: firstly, are you 100% sure its the query that is going wrong? Check the trace profile in sql server to see how long its taking in the DB. Secondly, are you getting the same number of results back. The capitalisation should not matter by default in sql server, but it could have been set up differently. A: If I had a query that took "5+ minutes", I wouldn't be worried about the 100 milliseconds it takes to match up the case of the string. A: thanks for all your answers, I'll respond to each in turn: 1) Russ, I agree that SQLConnection would be better, but unfortunately I do not get to set the type of connection. I just created a small app to test this query, but the query is dynamically created in a much larger application. 2) gbjbaanb, It's not a server issue I think, because I can run both queries from the management studio in about the same time, it only seems to be a problem when run through oledb in .net (1.1 and 2.0). We've run a profiler on it and the trace file confirmed that it took over 5 minutes to complete the query when called this way. 3)Joel Coehoorn, Agreed, but really what I'm trying to get at here is "why" because right now we don't know how big this problem is and where it lies. 4)Cade Roux, The difference is very reproduceable, so I don't think it's an issue with index changes or caching since I have run the tests back to back with the same results and that they take about the same time in SQL Server to run. A: Thanks to G Mastros for the most complete answer, although in retrospect the update in statistics was suggested by Cade. G Mastos' solution was better suited to my level of SQL Server experience, however. Thanks for helping everybody! I'm going to look into why this seemingly innocent difference has such large consequences
{ "language": "en", "url": "https://stackoverflow.com/questions/150017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What needs checking in for a Grails app? What parts of a Grails application need to be stored in source-control? Some obvious parts that are needed: * *grails-app directory *test directory *web-app directory Now we reach questions like: * *If we use a Grails plug-in (like gldapo), do we need to check in that plugin? *Do Grails plugins install in the Grails directory, or your project? I'm not looking to start a religious war about .project, so please ignore that, but are there any "hidden" project files I need to worry about, along with the plugin issues? Converted to a community wiki, as new versions of Grails have changed some of these solutions, especially as regards plugins. A: * *You do not want ./plugins/core (Core Grails plugins) under SVN *You do not want anything under ./web-app/WEB-INF/ under SVN. You should not usually need to put files in here. Files from ./conf are copied to WEB-INF/classes so they are on the classpath, if you need to supply anything. Here's a link to the docs describing in more detail. A: I would say, put all your project directory under versionning. Even the libs, it won't take that much disk space and you'll not change them so often. To my point of view, it's somehow "safer" than relying on external tools such as maven to grab all the dependencies, especially when one of the dependecies silently upgrade and change a little bit its behaviour, introducing "bugs" in your own project. A: After a bit more research, it seems that plugins for Grails are installed in the project directory, they don't change your Grails install. This means you'll need to install that plugin in each Grails project you want to use the functionality, and that the plugin is part of each project's source code. These plugins are installed in the grails-app/plugins directory, so if you're already checking in the grails-app directory, all should be well. There don't seem to be any "hidden files" that need checking in, though there are a few empty directories created when starting a new project that should be added to the source-control, as you'll probably add files to them at a later date.
{ "language": "en", "url": "https://stackoverflow.com/questions/150020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Has anyone run into problems in TortoiseSVN where the 'author' isn't written to the log? I have someone connecting to my repository using the url (substituted the IP address): svn+ssh://craig@123.45.67.89/subversion Yet when they commit files, the author entry is "null". According to this article: http://tortoisesvn.net/node/80 it should be working fine. Does anyone have any suggestions? A: Check your server configuration in [repository]/conf/svnserve.conf file if it has set anon-acces=write auth-access=write Usually, with the default settings anon-access = read auth-access = write (you can just comment out the lines), the author information should be preserved.
{ "language": "en", "url": "https://stackoverflow.com/questions/150027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing rulers in C# form Does anyone have a good technique (or tutorial) to implement rulers within a C# Windows Forms application? I want to display an image while showing rulers that indicate your mouse position to allow a more accurate positioning of the cursor. Just like the image below: I tried using splitter controls to hold the tick marks but I don't know how to make the top-left the gray blank area. Any advice? Thanks. A: I would build a custom control to do this in both X and Y location and use two controls. The control would have to override Paint() and use GDI methods to display the tick marks, it would then capture mouse events and update locations appropriately. A: This is the best article I've found and used on the matter: http://www.codeproject.com/KB/miscctrl/ruler.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/150031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ideas to replace Stored Procedure in Cash Flow report We have a Cash flow report which is basically in this structure: Date |Credit|Debit|balance| 09/29| 20 | 10 | 10 | 09/30| 0 | 10 | 0 | The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day. Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently. Anyone could give me some possible different solutions? for the problem? This report is being displayed on a DataGrid. A: This may be too big a change or off the mark for you, but a cash flow report indicates to me that you are probably maintaining, either formally or informally, a general ledger arrangement of some sort. If you are, then maybe I am naive about this but I think you should maintain your general ledger detail as a single table that has a bare minimum number of columns like ID, date, account, source and amount. All of the data that comes from different tables suggests that there several different kinds of events that are affecting your cash. To me, representing these different kinds of events in their own tables (like accounts receivable or accounts payable or inventory or whatever) makes sense, but the trick is to not have any monetary columns in those other tables. Instead, have them refer to the row in the general ledger detail where that data is recorded. If you enforce this, then the cash flow would always work the same regardless of changes to the other tables. The balance forward issue still has to be addressed and you have to take into account the number of transactions involved and the responsiveness required of the system but at least you could make a decision about how to handle it one time and not have to make changes as the other parts of your system evolve. A: On the code side of things, you've got two relatively easy options, but they both involve iterating through the dataset. option 1: For loop prior to databinding. For each row in the datatable, add/subtract the credit/debits to the previous row's balance and assign it to the appropriate cell of your datatable. Option 2: calculate during databinding. First you'd have a global variable that you could hold your value in. Set it to zero right before the databind. For each item or altitem, add/subtract the credit/debits to the global variable and assign it to the appropriate cell of your datagrid. A: Be aware that this normally means great raise of network traffic, which can reduce the performance of the application as a whole (since you'd have to fetch all this data to process on the client). An alternative approach is creating a ( in what implementation you like) middle layer application which you can send a request and do this processing on the database server or in a separate network segment. If there is a SP to do this calculation, normally is because it touch a lot of data and the objective is to avoid this circulating in the network.
{ "language": "en", "url": "https://stackoverflow.com/questions/150032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression to match non-ASCII characters? What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. A: The situation with regexes, Unicode, and Javascript sucks. It's ridiculous that programmers should have to rely on external libraries to recognize that "Αλφα" is a word, or even that "é" is a letter. But so it goes. This guy has written a good library for handling Unicode in Javascript Regexes: http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode The Unicode stuff is a plugin to this regex library: http://xregexp.com/ Here's a post about the Unicode extension: http://blog.stevenlevithan.com/archives/xregexp-unicode-plugin And the extension page itself: http://xregexp.com/plugins/ Great work but it still bums me out that Javascript is so backwards in this regard. (He wrote a book for O'Reilly about the topic so it's quite possible that he knows what he's talking about.) The way he implemented it is by adding tables of characters with certain properties. Then, when you contruct a regex with his library, \p{charclass} gets replaced with [allthecharactersintheclass]. A: You do the same way as any other character matching, but you use \uXXXX where XXXX is the unicode number of the character. Look at: http://unicode.org/charts/charindex.html http://unicode.org/charts/ http://www.decodeunicode.org/ A: All Unicode-enabled Regex flavours should have a special character class like \w that match any Unicode letter. Take a look at your specific flavour here. A: This should do it: [^\x00-\x7F]+ It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F). You can do the same thing with Unicode: [^\u0000-\u007F]+ For unicode you can look at this 2 resources: * *Code charts list of Unicode ranges *This tool to create a regex filtered by Unicode block. A: The answer given by Jeremy Ruten is great, but I think it's not exactly what Paul Wicks was searching for. If I understand correctly Paul asked about expression to match non-english words like können or móc. Jeremy's regex matches only non-english letters, so there's need for small improvement: ([^\x00-\x7F]|\w)+ or ([^\u0000-\u007F]|\w)+ This [^\x00-\x7F] and this [^\u0000-\u007F] parts allow regullar expression to match non-english letters. This (|) is logical or and \w is english letter, so ([^\u0000-\u007F]|\w) will match single english or non-english letter. + at the end of the expression means it could be repeated, so the whole expression allows all english or non-english letters to match. Here you can test the first expression with various strings and here is the second. A: var words_in_text = function (text) { var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+)/g; return text.match(regex); }; words_in_text('Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$'); // returns array ["Düsseldorf", "Köln", "Москва", "北京市", "إسرائيل"] This regex will match all words in the text of any language... A: Unicode Property Escapes are among the features of ES2018. Basic Usage With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression: /\p{Letter}/u Or with the shorthand, even terser: /\p{L}/u Matching Words Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters together with other word-characters like hyphens: /[\p{L}-]/u Stitching it all together, you could match words of all[1] languages with this beautifully short RegEx: /[\p{L}-]+/ug Example (shamelessly plugged from the answer above): 'Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$'.match(/[\p{L}-]+/ug) // ["Düsseldorf", "Köln", "Москва", "北京市", "إسرائيل"] [1] Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words besides letters and hyphens. Browser Support This feature is available in all major evergreen browsers. Transpiling If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called regexpu. There's an online demo available here. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression: /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])/ If you're using Babel, there's also a regexpu-powered plugin for that (Babel v6 plugin, Babel v7 plugin). A: I had a problem with \p working as expected, so I just used a different strategy like: ([^\t]+)\t Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/150033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "309" }
Q: How to wire a middle tier of Objects to a data tier consisting of a DataSet? I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships. I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted. How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset? Also, how do I wire the relationships together for 2 tables? The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail) I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method. Thank you, Keith A: I will not start another debate whether datasets are good or evil. If you continue to use them, here are something to consider: * *You need to keep the original dataset and update that, in order to get correct inserts and updates. *You want your parents to know their children, but not the other way. Banish the ParentTable. *An Order and its OrderDetails is an aggregate (from Domain Driven Design) and should be considered as a whole. A call to order.Save() should save everything. Well, that's the theory. How can we do that? One way is to create the following artifacts: * *Order *OrderDetail *OrderRepository *OrderMap The OrderMap is where you manage the Order to Dataset relationships. Internally, it could use a Hashtable or a Dictionary. The OrderRepository is where you get your Orders from. The repository will get the dataset with all relations from somewhere, build the Order with all its OrderDetails, and store the Order/Dataset relationship in the OrderMap. The OrderMap must be kept alive as long as the Order is alive. The Order contains all OrderDetails. Pass the order to the repository and let it save it. The repository will get the dataset from the map, update the Order-table from the order and iterate all order-details to update the OrderDetail-table. Retrieve and save: var order = repository.GetOrder(id); repository.Save(order); Inside OrderRepository.GetOrder(): var ds = db.GetOrderAndDetailsBy(id); var order = new Order(); UpdateOrder(ds, order); UpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order. map.Register(ds, order); Inside OrderRepository.Save(): var ds = map.GetDataSetFor(order); UpdateFromOrder(ds, order); foreach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail); Some final notes: * *You can implement the map as a singelton. *Let the map use weak references. Then any order should be garbage-collected when it should, and memory will be freed. *You need some way to associate an OrderDetail with its table-row *If you have the slightest possibility to upgrade to .NET 3.5, do it. Linq to Sql or Linq to Entity will remove some of your pain. *All of this is created out of thin air. I hope it's not too inaccurate. A: So, What I am doing right now is passing a reference to the DataSet and a reference to the DataRow of the parent into the Save method of the Child Object. Here is a little code showing the concept of what I am doing. // some random save event in a gui.cs// public void HandleSaveButtonClick() { parentObject.Save(); } // Save inside the parentObject.cs // public void Save() { CustomDataSet dataSet = new CustomDataSet(); ParentObjectTableAdapter parentTableAdapter = new ParentObjectTableAdapter(); DataTable dt = dataSet.ParentTable; DataRow newParentDataRow = dt.NewRow(); newParentDataRow["Property1"] = "Hello"; newParentDataRow["Property2"] = "World"; dt.Rows.Add(newParentDataRow); parentTableAdapter.Update(dataSet.ParentTable); //save children _child1.Save(dataSet, newParentDataRow) dataSet.AcceptChanges(); } //Save inside child1.cs // public void Save(CustomDataSet dataSet, DataRow parentRow) { Child1TableAdapter childTableAdapter= new Child1TableAdapter(); DataTable dt = dataSet.ChildTable; DataRow dr = dt.NewRow(); dr.SetParentRow(parentRow); dr["CProp1"] = "Child Property 1"; dt.Rows.Add(dr); childTableAdapter.Update(dataSet.ChildTable); } Let me know how this looks. Is this a usable pattern or am I missing something critical? Thank you, Keith
{ "language": "en", "url": "https://stackoverflow.com/questions/150038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What regEx can I use to Split a string into whole words but only if they start with #? I have tried this... Dim myMatches As String() = System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b") But it is splitting all words, I want an array of words that start with# Thanks! A: This seems to work... c# Regex MyRegex = new Regex("\\#\\w+"); MatchCollection ms = MyRegex.Matches(InputText); or vb.net Dim MyRegex as Regex = new Regex("\#\w+") Dim ms as MatchCollection = MyRegex.Matches(InputText) Given input text of... "asdfas asdf #asdf asd fas df asd fas #df asd f asdf" ...this will yield.... "#asdf" and "#df" I'll grant you that this does not get you a string Array but the MatchCollection is enumerable and so might be good enough. Additionally, I'll add that I got this through the use of Expresso. which appears to be free. It was very helpful in producing the c# which I am very poor at. (Ie it did the escaping for me.) (If anyone thinks I should remove this pseudo-advert then please comment, but I thought it might be helpful :) Good times ) A: Since you want to include the words in the split you should use something like "\b#\w+\b" This includes the actual word there in the expression. However I'm not sure that's what you want. Could you provide an example of input and the desired output? A: Using PHP's preg_match_all(): $text = 'Test #string testing #my test #text.'; preg_match_all('/#[\S]+/', $text, $matches); echo '<pre>'; print_r($matches[0]); echo '</pre>'; Outputs: Array ( [0] => #string [1] => #my [2] => #text. ) A: Here is a code in Javascript: text = "what #regEx can I use to #split a #string into whole words but only" // what #regEx can I use to #split a #string into whole words but only" text.match(/#\w+/g); // [#regEx,#split,#string] A: In Microsoft RegEx flavours, try: \#:w That worked for me using Find in Visual Studio. I don't know how it will translate into the RegEx class. EDIT: Backslash was swallowed.
{ "language": "en", "url": "https://stackoverflow.com/questions/150042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using asp:content markup more than once in the masterpage I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page? A: Title is actually an attribute on content pages, so you do something like: <%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %> on the content page. To get that into a header, on the master page just render the page title: <h1><%= this.Page.Title %></h3> A: I see that someone has just provided a (far) better answer to this specific problem. You could use the solution below if you have a master page that has the same content in multiple places (excluding the title). The best solution I can come up with is the following: Add an asp:Label for the page title and another one for the second position you want the text to appear (use two different id's, for example: pageTitle and sameTitle) Add a method to your master page: public void SetPageTitle(string title) { pageTitle.Text = title; sameTitle.Text = title; } On your content page, call the master page method. If your content page has a master page, it has a property called Master. You can now call the SetPageTitle method from your content page PageLoad method: ((MyMasterPage) Master).SetPageTitle("My content page"); You can also use the MasterType directive in your master page, check here for more info. This way you get a strongly-typed Master property that you do not have to cast: Master.SetPageTitle("My content page"); Regards, Ronald A: Also, master pages can have different content tags (with different Id's) which is good if you want pages to potentially alter various parts of the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/150044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MSBuild - Getting the target called from command line Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users. Example: msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV I want access to the target words ApplicationDeployment in my .Proj file. Is there a property I can access? Any clue how to do this? EDIT: I do not want to have to also pass in a property to get this. UPDATE: This is based on deployment scripts using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into. A: I found the answer! <Target Name="ApplicationDeployment" > <CreateProperty Value="$(MSBuildProjectName) - $(Environment) - Application Deployment Complete"> <Output TaskParameter="Value" PropertyName="DeploymentCompleteNotifySubject" /> </CreateProperty> I would like to give partial credit to apathetic. Not sure how to do that. A: There's no way to do this (that I am aware of). MSBuild doesn't have a property for the list of targets requested to build. However, if you find a way, keep in mind that it might not be a single target, but instead a list of targets to build. A: I'm not sure how to do exactly what you ask, but could you pass that string using the /p option? msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV;MyValue=ApplicationDeployment The only other way I can see to do it is to use a conditional property in each target, and thus establish the first target to be invoked. <Target Name="ApplicationDeployment"> <PropertyGroup> <InvokedTarget Condition="'${InvokedTarget}'==''">ApplicationDeployment</InvokedTarget> </PropertyGroup> ... </Target> A: I'd recommend using a server like CCNET to handle build executions and notification. Sure, you can do things to your MSBuild script to send out notificatioms, but that domain belongs to the build server.
{ "language": "en", "url": "https://stackoverflow.com/questions/150047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to run Visual Studio post-build events for debug build only How can I limit my post-build events to running only for one type of build? I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode. A: Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName). For instance if $(ConfigurationName) == Debug xcopy something somewhere A: FYI, you do not need to use goto. The shell IF command can be used with round brackets: if $(ConfigurationName) == Debug ( copy "$(TargetDir)myapp.dll" "c:\delivery\bin" /y copy "$(TargetDir)myapp.dll.config" "c:\delivery\bin" /y ) ELSE ( echo "why, Microsoft, why". ) A: You can pass the configuration name to the post-build script and check it in there to see if it should run. Pass the configuration name with $(ConfigurationName). Checking it is based on how you are implementing the post-build step -- it will be a command-line argument. A: As of Visual Studio 2019, the modern .csproj format supports adding a condition directly on the Target element: <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'"> <Exec Command="nswag run nswag.json" /> </Target> The UI doesn't provide a way to set this up, but it does appear to safely leave the Configuration attribute in place if you make changes via the UI. A: As of VS 2022, I have found 2 solutions. In my particular case, I want to pack to a different directory depending on Configuration. Option 1 <Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Exec Command="if $(Configuration) == Debug (dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)) else (dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo))" /> </Target> Option 2 <Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Exec Condition="'$(Configuration)' == 'Debug'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)" /> <Exec Condition="'$(Configuration)' == 'Release'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo)" /> </Target> I prefer option 2. A: Visual Studio 2015: The correct syntax is (keep it on one line): if "$(ConfigurationName)"=="My Debug CFG" ( xcopy "$(TargetDir)test1.tmp" "$(TargetDir)test.xml" /y) else ( xcopy "$(TargetDir)test2.tmp" "$(TargetDir)test.xml" /y) No error 255 here. A: Add your post build event like normal. Then save your project, open it in Notepad (or your favorite editor), and add condition to the PostBuildEvent property group. Here's an example: <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PostBuildEvent>start gpedit</PostBuildEvent> </PropertyGroup> A: Alternatively (since the events are put into a batch file and then called), use the following (in the Build event box, not in a batch file): if $(ConfigurationName) == Debug goto :debug :release signtool.exe .... xcopy ... goto :exit :debug ' Debug items in here :exit This way you can have events for any configuration, and still manage it with the macros rather than having to pass them into a batch file, remember that %1 is $(OutputPath), etc. A: I found that I was able to put multiple Conditions in the project file just like this: <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' != 'Debug' AND '$(Configuration)' != 'Release' "> <Exec Command="powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)postBuild.ps1 -ProjectPath $(ProjectPath) -Build $(Configuration)" /> </Target> A: Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step. A: In Visual Studio 2012 you have to use (I think in Visual Studio 2010, too) if $(Configuration) == Debug xcopy $(ConfigurationName) was listed as a macro, but it wasn't assigned. Compare: Macros for Build Commands and Properties A: This works for me in Visual Studio 2015. I copy all DLL files from a folder located in a library folder on the same level as my solution folder into the targetdirectory of the project being built. Using a relative path from my project directory and going up the folder structure two steps with..\..\lib MySolutionFolder ....MyProject Lib if $(ConfigurationName) == Debug ( xcopy /Y "$(ProjectDir)..\..\lib\*.dll" "$(TargetDir)" ) ELSE (echo "Not Debug mode, no file copy from lib")
{ "language": "en", "url": "https://stackoverflow.com/questions/150053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "650" }
Q: mysql "drop database" takes time -- why? mysql5.0 with a pair of databases "A" and "B", both with large innodb tables. "drop database A;" freezes database "B" for a couple minutes. Nothing is using "A" at that point, so why is this such an intensive operation? Bonus points: Given that we use "A", upload data into "B", and then switch to using "B", how can we do this faster? Dropping databases isn't the sort of thing one typically has to do all the time, so this is a bit off the charts. A: By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so conceivably "drop database A" could affect database B. Since "drop database" is likely to involve heavy reorgainsing of the innodb data files, it's conceivable that it's a blocking operation, either because of the intensity of the operation, or by design. However, I think you can make each database use different physical files, although I haven't tried that myself, so you'll have to figure out the specifics for yourself. Failing that, then you may need to use two different mysql installs side-by-side on the same machine, which is perfectly doable. A: So I'm not sure Matt Rogish's answer is going to help 100%. The problem is that MySQL* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, no other tables can be opened. This is described by a colleague of mine here: http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/ One excellent impact reduction strategy is to use a filesystem like XFS. The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above). A: Following off of skaffman: Change your my.cnf (and restart MySQL) to include: innodb_file_per_table = 1 (http://mysqldba.blogspot.com/2006/12/innodbfilepertable.html) This will give your databases dedicated file storage and take it out of the shared pool. It will then let you do fun things like place the tables/indexes on different physical disks to even further split up I/O and improve performance. Note this doesn't change existing tables; you'll have to do work to get 'em in their own file (http://capttofu.livejournal.com/11791.html).
{ "language": "en", "url": "https://stackoverflow.com/questions/150058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How Do I Authenticate to ActiveResource to Avoid the InvalidAuthenticityToken Response? I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response? require 'rubygems' require 'activeresource' class Event < ActiveResource::Base self.site = "http://localhost:3000" end e = Event.create( :name => "Shortest Event Ever!", :starts_at => 1.second.ago, :capacity => 25, :price => 10.00) e.destroy A: I found an answer to this issue which works since I am writing a command-line application. I added the following to my controller: # you can disable csrf protection on controller-by-controller basis: skip_before_filter :verify_authenticity_token A: Rails only requires this when you're requesting html, if you're requesting xml (possibly anything other than html?) it doesn't check for that. Looks like the destroy action for your server needs an xml response and the problem should go away.
{ "language": "en", "url": "https://stackoverflow.com/questions/150076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to hide a Pocket Internet Explorer element? How can I hide an element in html on Pocket Internet Explorer running on a Windows Mobile 6 device. The following code does not work even though it apears to be setting the values correctly. function ShowCollapseElement(sLinkId, sContentId) { var oLinkElement; var oContentElement; //Get the elements oLinkElement = document.getElementById(sLinkId); oContentElement = document.getElementById(sContentId); //Toggle the visibility of the content oContentElement.style.display = (oContentElement.style.display != 'none' ? 'none' : 'inline'); //Set the link text oLinkElement.innerText = (oContentElement.style.display != 'none' ? '-' : '+'); } A: I've just discovered that the code works when the element is a div, but not with a table row. I will have to settle for using a div.
{ "language": "en", "url": "https://stackoverflow.com/questions/150083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Abstracting storage data structures within XPath I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". Is there a way to do this without copying all of the records in the DataTable into the XDocument? I'm using .Net 3.5 A: .NETs XPath stuff operates on the IXPathNavigable interface. Every IXPathNavigable has a CreateNavigator() method that returns an IXPathNavigator. In order to expose all of your data sources as one large document you would need to create a class implementing IXPathNavigable, containing all the xpath data sources. The CreateNavigator method should return a custom XPathNavigator that exposes the contents as one large data source. Unfortunately, implementing this navigator is somewhat fiddly, and care must be taken especially when jumping between documents, A: I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space. Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>(); // ... populate dictionary of tables ... XElement TableRoot = new XStreamingElement("Tables", from t in Tables select new XStreamingElement(t.Key, from DataRow r in t.Value.Rows select new XStreamingElement("row", from DataColumn c in t.Value.Columns select new XElement(c.ColumnName, r[c]))))) The result is an XElement (TableRoot) with a structure similar to the following, assuming the dictionary contains one table called "Orders" with two rows. <Tables> <Orders> <row> <sku>12345</sku> <quantity>2</quantity> <price>5.95</price> </row> <row> <sku>54321</sku> <quantity>3</quantity> <price>2.95</price> </row> </Orders> </Tables> That can be merged with a larger XElement/XDocument based hierarchy and queried with XPath. A: Are you looking for something similar to what I asked regarding XPath foreign keys? A: As the XPath recommendation says, "The primary purpose of XPath is to address parts of an XML document." It doesn't have any facility for addressing parts of more than one XML document. You'll have to build a single XML document if you want to do what you're trying to do. A: You would have to merge your documents, or at lest perform the same transformations on all of your documents. You may consider moving your documents to a single DataTable, then filtering the DataTable if the XPath / XSLT is not do-able.
{ "language": "en", "url": "https://stackoverflow.com/questions/150084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Interpolating a string into a regex I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example: foo = "0.0.0.0" goo = "here is some other stuff 0.0.0.0" if goo =~ /value of foo here dynamically/ puts "success!" end A: Probably Regexp.escape(foo) would be a starting point, but is there a good reason you can't use the more conventional expression-interpolation: "my stuff #{mysubstitutionvariable}"? Also, you can just use !goo.match(foo).nil? with a literal string. A: Regexp.compile(Regexp.escape(foo)) A: Use Regexp.new: if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/ A: Here's a limited but useful other answer: I discovered I that I can easily insert into a regex without using Regexp.quote or Regexp.escape if I just used single quotes on my input string: (an IP address match) IP_REGEX = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' my_str = "192.0.89.234 blahblah text 1.2, 1.4" # get the first ssh key # replace the ip, for demonstration my_str.gsub!(/#{IP_REGEX}/,"192.0.2.0") puts my_str # "192.0.2.0 blahblah text 1.2, 1.4" single quotes only interpret \\ and \'. http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes This helped me when i needed to use the same long portion of a regex several times. Not universal, but fits the question example, I believe. A: Same as string insertion. if goo =~ /#{Regexp.quote(foo)}/ #... A: Note that the Regexp.quote in Jon L.'s answer is important! if goo =~ /#{Regexp.quote(foo)}/ If you just do the "obvious" version: if goo =~ /#{foo}/ then the periods in your match text are treated as regexp wildcards, and "0.0.0.0" will match "0a0b0c0". Note also that if you really just want to check for a substring match, you can simply do if goo.include?(foo) which doesn't require an additional quoting or worrying about special characters. A: foo = "0.0.0.0" goo = "here is some other stuff 0.0.0.0" puts "success!" if goo =~ /#{foo}/
{ "language": "en", "url": "https://stackoverflow.com/questions/150095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "176" }
Q: Exception Thrown Causes RunTime Error We have developed a website that uses MVC, C#, and jQuery. In one of my controller classes we are validating inputs from the user and if it fails we throw an exception that the Ajax error parameter(aka option) handles. (We use Block UI to display the error message. BlockUI is a jQuery plugIn that blocks the screen and displays a message box.) (Yes, the message has text in it with no funny characters or non-sense) When running the website locally or on a server we receive different effects from the exception being thrown. Locally: The proper exception is displayed in BlockUI. Server: The message "Runtime Error" is displayed instead of the exception message. print( public ActionResult FailUpdateStatus(string id) { string message = Request.Form["message"]; throw new Exception(message); } ); I have been able to run the website on the server and remote attach to the website. While debugging the exception gets thrown as it should but block UI shows the Runtime error. Any ideas? A: By default, ASP.NET web applications will hide errors from remote machines accessing the site, and will only return the generic 'Runtime Error'. ASP.NET will only show application specific error messages when the site is accessed locally (i.e. if the ASP.NET application server is running on your local development machine, or if you open up a web browser on the server hosting the ASP.NET web application). To view messages generated on a remote server from a local client, add the following code to your web.config file. <configuration><system.web><customErrors mode="Off"/></system.web></configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/150104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error sending mail with System.Web.Mail An older application using System.Web.Mail is throwing an exception on emails coming from hr@domain.com. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening? Here is the exception and stack trace: System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server. --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) --- End of inner exception stack trace --- at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at ProcessEmail.Main() A: Does you client's host machine have permission to send mail via the Exchange Sever? A: Here's a tutorial for diagnosing those exceptions (a very common one with a lot of meanings).
{ "language": "en", "url": "https://stackoverflow.com/questions/150113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parsing Performance (If, TryParse, Try-Catch) I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this. Which of these offers the best performance in which situations? Parse(...) // Crash if the case is extremely rare .0001% If (SomethingIsValid) // Check the value before parsing Parse(...) TryParse(...) // Using TryParse try { Parse(...) } catch { // Catch any thrown exceptions } A: Always use T.TryParse(string str, out T value). Throwing exceptions is expensive and should be avoided if you can handle the situation a priori. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is worse and that the performance of TryParse is better. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse. (edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested) Times for various failure rates on 10,000 inputs from the user (for the unbelievers): Failure Rate Try-Catch TryParse Slowdown 0% 00:00:00.0131758 00:00:00.0120421 0.1 10% 00:00:00.1540251 00:00:00.0087699 16.6 20% 00:00:00.2833266 00:00:00.0105229 25.9 30% 00:00:00.4462866 00:00:00.0091487 47.8 40% 00:00:00.6951060 00:00:00.0108980 62.8 50% 00:00:00.7567745 00:00:00.0087065 85.9 60% 00:00:00.7090449 00:00:00.0083365 84.1 70% 00:00:00.8179365 00:00:00.0088809 91.1 80% 00:00:00.9468898 00:00:00.0088562 105.9 90% 00:00:01.0411393 00:00:00.0081040 127.5 100% 00:00:01.1488157 00:00:00.0078877 144.6 /// <param name="errorRate">Rate of errors in user input</param> /// <returns>Total time taken</returns> public static TimeSpan TimeTryCatch(double errorRate, int seed, int count) { Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; try { value = Int32.Parse(input); } catch(FormatException) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed; } /// <param name="errorRate">Rate of errors in user input</param> /// <returns>Total time taken</returns> public static TimeSpan TimeTryParse(double errorRate, int seed, int count) { Stopwatch stopwatch = new Stopwatch(); Random random = new Random(seed); string bad_prefix = @"X"; stopwatch.Start(); for(int ii = 0; ii < count; ++ii) { string input = random.Next().ToString(); if (random.NextDouble() < errorRate) { input = bad_prefix + input; } int value = 0; if (!Int32.TryParse(input, out value)) { value = -1; // we would do something here with a logger perhaps } } stopwatch.Stop(); return stopwatch.Elapsed; } public static void TimeStringParse() { double errorRate = 0.1; // 10% of the time our users mess up int count = 10000; // 10000 entries by a user TimeSpan trycatch = TimeTryCatch(errorRate, 1, count); TimeSpan tryparse = TimeTryParse(errorRate, 1, count); Console.WriteLine("trycatch: {0}", trycatch); Console.WriteLine("tryparse: {0}", tryparse); } A: Try-Catch will always be the slower. TryParse will be faster. The IF and TryParse are the same. A: Option 1: Will throw an exception on bad data. Option 2: SomethingIsValid() could be quite expensive - particularly if you are pre-checking a string for Integer parsability. Option 3: I like this. You need a null check afterwards, but it's pretty cheap. Option 4 is definitely the worst. Exception handling is comparatively expensive, so avoid it if you can. In particular, bad inputs are to be expected, not exceptional, so you shouldn't use them for this situation. (Although, before TryParse, It may have been the best option.)
{ "language": "en", "url": "https://stackoverflow.com/questions/150114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: C# .NET / javascript : Collapsable Table Rows - what about this is wrong? I have a C# .NET page where I want to make rows collapse when a button is pressed. I found many tutorials like this one (http://codingforums.com/archive/index.php?t-90375.html), tried to implement their solutions, but none of them do anything for me when I click my button. To make sure I wasn't going crazy, I made a small test page just to see if the idea works. For some reason, it isn't. The browser is IE6. I'm running Visual Studio 2005. Does anyone have any idea why this isn't working? The rendered page shows a button and a line of text as I would expect; the line of text does not disappear when I click the button. I know I could use divs, but remember this is just a proof of concept; in my real application it is table rows that must collapse. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Project.Web.Auth.Test" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Shop Financials</title> <link href="../StyleSheets/ClaimsV2.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function btnClick(control) { try { var id_table = document.getElementById(control).style; if(id_table.display == "block") { id_table.display = "none"; } else { id_table.display = "block"; } } catch(e) { alert(e); } } function toDepositPrinterFriendly() { } </script> </head> <body> <form id="form1" runat="server"> <table> <tr> <td><asp:Button runat="server" OnClientClick="javascript:btnClick('HeaderRow')"/></td> </tr> <tr id="HeaderRow" runat="server"> <td>TEST2</td> </tr> </table> </form> </body> </html> A: 1) The display is (probably) not 'block' initially. Try: if(id_table.display == 'none') { id_table.display = ''; } else { id_table.display = 'none'; } 2) The id of the control will not be what you think it is, thanks to Naming Containers. Check your HTML Source
{ "language": "en", "url": "https://stackoverflow.com/questions/150124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a Lambda? Could someone provide a good description of what a Lambda is? We have a tag for them and they're on the secrets of C# question, but I have yet to find a good definition and explanation of what they are in the first place. A: It's just an anonymous function declared inline, most typically assigned to a delegate when you don't want to write a full-fledged function. In languages like lisp/scheme, they're often passed around quite liberally as function parameters, but the idiom in C# typically finds lambdas used only for lazy evaluation of functions, as in linq, or for making event-handling code a bit terser. A: There's not really such a thing as 'a lambda' in programming. It depends on the language, etc. In short, normally a language that 'has lambdas' uses the term for anonymous functions or, in some cases, closures. Like so, in Ruby: f = lambda { return "this is a function with no name" } puts f.call A: In response to the previous answers: -The important thing about anonymous functions is not that they dont require a name. -Closures are a separate concept. -A gigantic wikipedia article is not making this any clearer. Here's my answer in 3 parts: 1. A lambda is a function which is also an expression. This is the important thing. 2. Many languages which implement so-called "lambdas" add some syntactic sugar to make writing these short functions easier and faster, but this is not required. 3. Some languages may require that a lambda has no side effects. That would be a more pure lambda in the functional sense. When a function is an expression, it's a "first class citizen" within the language. I can do all the important things with it: x = lambda(){ return "Hello World"; } doit( 1, 2, lambda(a,b){ return a > b; }, 3 ) x = (lambda(a){ return a+1; }) + 5 // type error, not syntax error (lambda(a,b){ print(a); log(b); })( 1, 2 ) // () is valid operator here A: Also called closures or anonymous functions.. I found the best description here. Basically, inline block of code that can be passed as an argument to a function. A: "Lambda" refers to the Lambda Calculus or to a specific lambda expression. Lambda calculus is basically a branch of logic and mathematics that deals with functions, and is the basis of functional programming languages. ~ William Riley-Land A: Closures, lambdas, and anonymous functions are not necessarily the same thing. An anonymous function is any function that doesn't have (or, at least, need) its own name. A closure is a function that can access variables that were in its lexical scope when it was declared, even after they have fallen out of scope. Anonymous functions do not necessarily have to be closures, but they are in most languages and become rather less useful when they aren't. A lambda is.. not quite so well defined as far as computer science goes. A lot of languages don't even use the term; instead they will just call them closures or anon functions or invent their own terminology. In LISP, a lambda is just an anonymous function. In Python, a lambda is an anonymous function specifically limited to a single expression; anything more, and you need a named function. Lambdas are closures in both languages. A: Clipped from wikipedia: http://en.wikipedia.org/wiki/Lambda#Lambda.2C_the_word In programming languages such as Lisp and Python, lambda is an operator used to denote anonymous functions or closures, following lambda calculus usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/150129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "95" }
Q: Any success rendering HDVideo with WPF MediaElement? Is there a better video player option for WPF? I'm using a WPF MediaElement to render HD video in an application. When the size of the MediaElement gets over about 300 units square the video stutters and the computer is nearly totally unresponsive. I need to render the video full screen. Has anybody had success rendering fullscreen video using the WPF MediaElement? What were the processor/video specs of the computer used? Is there a better way to get video displayed in a WPF application? EDIT: Timothy: I need to be able to put text or other elements over the graphic, so I think that hosting WMP is out. Currently I am not doing any layers nor opacity/transparency. I'm running in XP currently. I hope to be able to run the application in both Vista and XP. Mike: I was reading some of Jeremiah Morrill's posts on the MSDN forums prior to coming back and checking on this post. I found my way to some of his libraries and will be testing them out. Thanks. UPDATE: It appears that the problem is on my development machine. On the test machine things are running fine. My development machine is dual headed w/ 2 1650x1080 CRTs with a ATI Radon X1650 series card with 256MB of memory. When using the WPF perfmon tool it indicates that everything is hardware rendered, but the performance sucks. For now I'm just going to go with it as I know the code runs fine on the machines we distribute it with. At some point in the future I'll try to dig into why it performs so poorly on my development machine. (all machines are XP). Thanks for all the suggestions. A: Jeremiah Morrill has recently released a specialized WPF library that supports displaying HD Media (among other features) A: It sure doesn't seem to work correctly. It may be that testing for the opacity of other layers slows it down too much. Have you tried running the test with Aero turned off? It has been suggested that hosting Windows Media Player may be the way to go. Walkthrough: Hosting an ActiveX Control in Windows Presentation Foundation by Using XAML A: What is the resolution/format of your HD video? I have done a 720p WMV on a dual core 2.6ghz fullscreen without issues, but it has a NVidia 9800GXT in it. What is the CPU usage of the HD video in just WMP? Remember that there is some overhead with rendering anything within WPF. So if you are running near 100% CPU, rendering to WPF may be just enough to set it over. Also if your GPU is too slow, you may also suffer choppy video. -Jeremiah A: I think this is only a problem in Windows XP. It seems that the video playback is not updating with the vsynch. So it updates the screen whenever it feels like it. In Vista, the video rendering of WPF is smarter some how. A: Using correct vsync should solve the problem, and it is not necessarily related to the wpf and vista. Some ATI cards come with graphic drivers that have the vsync option turned off by default. Hope this helps. A: Old thread, but just like to share my own experience. My guess is that your distribution machines are single monitor. I ever had a second monitor on my laptop and found that the first seconds of a video where not visible, and schocking video afterwards. Removing and disable the additional monitor solved the problems. I have seen more reports that the media element has problems in a dual monitor environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/150143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Separation of Presentation and Business Tiers with Spring In my just-completed project, I was working getting distributed transactions working. We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries. Our request sequence looked like: browser -> secured servlet -> 'wafer-thin' SLSB -> spring TX-aware proxy -> request-handler POJO What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB. Our SLSB had a static initialiser block to bootstrap our Spring application context. I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations. I would be interested to know what others propose to separate tiers when using Spring? A: Requiring an EJB3 app server just for a SLSB that is a facade doesn't seem like it's worth the effort to me. There is no reason you couldn't just remove that and have your servlet work directly with Spring. You can add the ContextLoaderListener to the WAR to load your ApplicationContext and then WebApplicationContextUtils to get at it. Alternatively you could use SpringMVC, Struts or other web technologies if you need to do more than what the Servlet on its own will allow for. A: A pretty typical approach is to define a web tier, a service tier and a DAO tier, and attach transactional semantics to the service tier. The service tier might be a bunch of POJOs with @Transactional annotations, for example. The web tier might be Spring Web MVC controllers. In this approach, the web tier is essentially adapting the service tier to HTTP. Good separation and no need for SLSBs here. One area of debate though is with respect to the domain objects, like Employee or PurchaseOrder or whatever. These span application tiers and one thing that seems to be happening with annotations is that the domain objects get annotations that are tied to specific tiers. So you might have ORM annotations here but then use the same domain object as a form-backing bean as a way to avoid parallel domain/form object classes. Some people object to that as violating architectural separation of concerns.
{ "language": "en", "url": "https://stackoverflow.com/questions/150146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I share a menu definition between a context menu and a regular menu in WPF I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below? <Page.Resources> <MenuItem x:Key="123"/> </Page.Resources> <ContextMenu> <MenuItem>Something hardcoded</MenuItem> <!-- include shared menu here --> </ContextMenu> A: I've done this by setting x:Shared="False" on the menu item itself. Resources are shared between each place that uses them by default (meaning one instance across all uses), so turning that off means that a new "copy" of the resource is made each time. So: <MenuItem x:Key="myMenuItem" x:Shared="False" /> You'll still get a "copy" of it, but you only need to define it in one place. See if that helps. You use it like this within your menu definition: <StaticResource ResourceKey="myMenuItem" /> A: Because you want to mix-and-match... I would make a custom control that inherits from ContextMenu that has a "SharedMenuItems" Dependancy Property and a MenuItems Dependancy Property. This way your control can decide how to merge these two sets together. If you would like an example of this, please let me know. A: A number of options: a) Databind the ContextMenu or the Menu to the same underlying collection and use item templates et al to the work b) Use commands, and databind to a set of command bindings
{ "language": "en", "url": "https://stackoverflow.com/questions/150150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to improve performance and memory usage with a large number of polygons on a canvas? The project I'm working on needs to render an ESRI shape file, which can have a large number of polygons/shapes. When I add all these polygons, lines, points, etc to the canvas I'm using, it gets really slow. To draw the shapes on the map, I'm creating a Path object, and setting it's Data property to a StreamGeometry. I originally used a Polygon, but according to MSDN a StreamGeometry is much lighter weight. How can I improve the performance? Would converting the finished product to a Bitmap, or VisualBrush help? Is there a more efficient way of to render all these shapes onto the canvas? EDIT: I forgot to mention that this needs to be able to work in a Partial-Trust XBAP. A: No need to resort to GDI, you just need to move down a layer in the WPF API's and combine your geometry into fewer visuals. Pablo Fermicola has some useful information about picking which layer to use depending on your performance needs. I've managed to get excellent performance using DrawingVisual and the DrawingContext class. A: You could try using GDI+ or direct x instead of WPF. I did a similar project (rendering Map data via WPF), for an MSDN magazine article I wrote about a year ago. It was just something I wrote rather quickly (the article + the app took about 1 week), and was designed to just be a "this is something neat you can do", and so I didn't focus on performance much. In any case, I ran into the same problem. Once the number of polygons on the canvas got large, the rendering performance started to suffer. For example, resizing the window would involve about a 1/2 second delay or so. A lot of this has to do with the overhead of WPF. It's primarily designed as an GUI toolkit, rather than a high performance graphic engine. That means it focuses on feature richness over efficent rendering. With smaller numbers of objects (what is likely to be found in most GUI applications), the performance is pretty good and the databinding, animation, and declarative style features (and all the event routing and other things they require) can really come in handy. When drawing a map, however, the sheer volume of data can cause all those neat data binding features to cause perf problems, as you seem well aware. If you don't need declarative styling and animation, then I would just eliminate WPF, and use GDI+ to draw the map your self. It basicly involves setting up the right transformation matrix to get the map to draw onto a control surface, and then iterating through all the polygons and calling a bunch of DrawPolygon methods. To enable interaction you will have to write your own hit testing code, and you will have to redraw the map anytime the form is resized. You will also have to hand code any animations or style changes or things like that you want to do (such as highlighting regions when the mouse is over them). But, it shouldn't be that difficult to write that code. I would imaging you could do it in about 1.5 weeks. Doing it that way, however, should improve performance, because it would come down to doing only about 20-30K vector transformations, which doesn't take much processor power on most modern CPU's. You could also look into using Direct X, which would allow you to take advantage of the GPU as well, which could give an even bigger performance boost. A: You may be limited by the performance of the canvas widget. If you have the option of using a 3rd party toolkit look at QT. It has a high performance canvas widget that is designed to render complex shapes quickly. This has already been used for at least one GIS application, so it has some track record in this space. You can wrap QT as an ActiveX control or use the Qyoto/Kimono .Net bindings to interface to a .Net application. Troll Tech have just revamped their website and I can't find the downloadable demo they used to have there but it shows the QGraphicsView widget rendering a very large vector drawing and zooming out in real time. A: You are about to discover the motivation behind GPUs and insanely overclocked and cooled-down graphics cards. And double-buffering. And: converting the thing to a bitmap: what's the difference to rendering it? After all you have n objects that /somehow/ have to get rendered (unless you can figure out which objects are hidden behind other objects but that doesn't help you much since you'd have to look at n! object relations). Besides: maybe it pays off to leave the orthodox OOP approach and go procedural instead. A: @xmjx And: converting the thing to a bitmap: what's the difference to rendering it? My thought here was that my slowdown could be caused by having n number of objects on a canvas, versus 1 bitmap. That said, I don't know the performance, or what happens in the background when converting a canvas with n number of objects to a Bitmap. I would prefer not to use a Bitmap, so that I can allow the user to interact (modify/delte) with the shape/polygons. A: If performance is an issue then you want to avoid Visual Brushes. These brushes are best used to project some visible part of the screen to another place on the screen. They cause a large performance hit because these brushes automatically update when the brush's content changes. Any usage of this brush will be software rendered, and will not be able to take advantage of the hardware capabilities of your graphic card. More info from MSDN on VisualBrush A: Use DrawingGroup and add/remove Drawing objects to solve this. See my answer to a similar question about DrawingVisual performance with Opacity=0. I think my answer actually fits this question better. A: if you do not have to show ALL polygons at once (e.g. due to zooming, panning etc), check out the virtualizing canvas sample here
{ "language": "en", "url": "https://stackoverflow.com/questions/150151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: NHibernate ICriteria - Does the sort allow for null? Using NHibernate ICriteria and adding .AddOrder ... I want to sort by a property that is sometimes null with all the populated ones at the top. Will .AddOrder allow me to do this? If not is there an alternative? The sorting options for ILists leave a lot to be desired. A: If you use something similar to: IList cats = sess.CreateCriteria(typeof(Cat)) .AddOrder( Order.Desc("PropertyName") ) .List(); The objects with NULLs for the given property will be last in the list. (Taken in part from the NHibernate documentation.) A: You should get the non-null values first by using that method. We use sorting in that way on my project, and have not had any issues with the null values... they get listed at end.
{ "language": "en", "url": "https://stackoverflow.com/questions/150153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Waiting for user input with a timeout I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers. EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues. function Pause-Host { param( $Delay = 1 ) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)) { [Threading.Thread]::Sleep(1000) } } A: It's quite old now but how I solved it based on the same KeyAvailable method is here: https://gist.github.com/nathanchere/704920a4a43f06f4f0d2 It waits for x seconds, displaying a . for each second that elapses up to the maximum wait time. If a key is pressed it returns $true, otherwise $false. Function TimedPrompt($prompt,$secondsToWait){ Write-Host -NoNewline $prompt $secondsCounter = 0 $subCounter = 0 While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $secondsToWait) ){ start-sleep -m 10 $subCounter = $subCounter + 10 if($subCounter -eq 1000) { $secondsCounter++ $subCounter = 0 Write-Host -NoNewline "." } If ($secondsCounter -eq $secondsToWait) { Write-Host "`r`n" return $false; } } Write-Host "`r`n" return $true; } And to use: $val = TimedPrompt "Press key to cancel restore; will begin in 3 seconds" 3 Write-Host $val A: For people who are looking for a modern age solution with an additional constraint for exiting a PowerShell script on a pre-defined key press, the following solution might help you: Write-Host ("PowerShell Script to run a loop and exit on pressing 'q'!") $count=0 $sleepTimer=500 #in milliseconds $QuitKey=81 #Character code for 'q' key. while($count -le 100) { if($host.UI.RawUI.KeyAvailable) { $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp") if($key.VirtualKeyCode -eq $QuitKey) { #For Key Combination: eg., press 'LeftCtrl + q' to quit. #Use condition: (($key.VirtualKeyCode -eq $Qkey) -and ($key.ControlKeyState -match "LeftCtrlPressed")) Write-Host -ForegroundColor Yellow ("'q' is pressed! Stopping the script now.") break } } #Do your operations $count++ Write-Host ("Count Incremented to - {0}" -f $count) Write-Host ("Press 'q' to stop the script!") Start-Sleep -m $sleepTimer } Write-Host -ForegroundColor Green ("The script has stopped.") Sample script output: Refer Microsoft document on key states for handling more combinations. Credits: Technet Link A: Found something here: $counter = 0 while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)) { [Threading.Thread]::Sleep( 1000 ) } A: Here is a keystroke utility function that accepts: * *Validation character set (as a 1-character regex). *Optional message *Optional timeout in seconds Only matching keystrokes are reflected to the screen. Usage: $key = GetKeyPress '[ynq]' "Run step X ([y]/n/q)?" 5 if ($key -eq $null) { Write-Host "No key was pressed."; } else { Write-Host "The key was '$($key)'." } Implementation: Function GetKeyPress([string]$regexPattern='[ynq]', [string]$message=$null, [int]$timeOutSeconds=0) { $key = $null $Host.UI.RawUI.FlushInputBuffer() if (![string]::IsNullOrEmpty($message)) { Write-Host -NoNewLine $message } $counter = $timeOutSeconds * 1000 / 250 while($key -eq $null -and ($timeOutSeconds -eq 0 -or $counter-- -gt 0)) { if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable) { $key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp") if ($key_.KeyDown -and $key_.Character -match $regexPattern) { $key = $key_ } } else { Start-Sleep -m 250 # Milliseconds } } if (-not ($key -eq $null)) { Write-Host -NoNewLine "$($key.Character)" } if (![string]::IsNullOrEmpty($message)) { Write-Host "" # newline } return $(if ($key -eq $null) {$null} else {$key.Character}) } A: timeout.exe 5 still works from powershell. Waits 5 seconds or until key press. Inelegant perhaps. But easy. However, From the Powershell_ISE it pops up a new command prompt window, and returns immediately, so it doesnt wait (From the powershell console it uses that console and does wait). You can make it wait from the ISE with a little more work (still pops up its own window tho): if ($psISE) { start -Wait timeout.exe 5 } else { timeout.exe 5 } A: Another option: you can use choice shell command which comes with every Windows version since Windows 2000 Choice /C yn /D n /t 5 /m "Are you sure? You have 5 seconds to decide" if ($LASTEXITCODE -eq "1") # 1 for "yes" 2 for "no" { # do stuff } else { # don't do stuff } Stackoverflow syntax higlighting doesn't work for powershell, # means "comment" here A: function ReadKeyWithDefault($prompt, $defaultKey, [int]$timeoutInSecond = 5 ) { $counter = $timeoutInSecond * 10 do{ $remainingSeconds = [math]::floor($counter / 10) Write-Host "`r$prompt (default $defaultKey in $remainingSeconds seconds): " -NoNewline if($Host.UI.RawUI.KeyAvailable){ $key = $host.UI.RawUI.ReadKey("IncludeKeyUp") Write-Host return $key } Start-Sleep -Milliseconds 100 }while($counter-- -gt 0) Write-Host $defaultKey return $defaultKey } $readKey = ReadKeyWithDefault "If error auto exit( y/n )" 'y' 5 A: To optionally pause the script before it exits (useful for running headless scripts and pausing on error output), I appended nathanchere's answer with: if ([Console]::KeyAvailable) { $pressedKey = [Console]::ReadKey($true); read-host; break; } elseif ($secondsCounter -gt $secondsToWait) { Write-Host "`r`n" return $false; } A: The $Host.UI.RawUI.KeyAvailable seems to be buggy so I had more luck using [Console]::KeyAvailable: function keypress_wait { param ( [int]$seconds = 10 ) $loops = $seconds*10 Write-Host "Press any key within $seconds seconds to continue" for ($i = 0; $i -le $loops; $i++){ if ([Console]::KeyAvailable) { break; } Start-Sleep -Milliseconds 100 } if ([Console]::KeyAvailable) { return [Console]::ReadKey($true); } else { return $null ;} }
{ "language": "en", "url": "https://stackoverflow.com/questions/150161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: How do I list / export private keys from a keystore? How do I list and export a private key from a keystore? A: If you don't need to do it programatically, but just want to manage your keys, then I've used IBM's free KeyMan tool for a long time now. Very nice for exporting a private key to a PFX file (then you can easily use OpenSSL to manipulate it, extract it, change pwds, etc). https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc Select your keystore, select the private key entry, then File->Save to a pkcs12 file (*.pfx, typically). You can then view the contents with: $ openssl pkcs12 -in mykeyfile.pfx -info A: Here is a shorter version of the above code, in Groovy. Also has built-in base64 encoding: import java.security.Key import java.security.KeyStore if (args.length < 3) throw new IllegalArgumentException('Expected args: <Keystore file> <Keystore format> <Keystore password> <alias> <key password>') def keystoreName = args[0] def keystoreFormat = args[1] def keystorePassword = args[2] def alias = args[3] def keyPassword = args[4] def keystore = KeyStore.getInstance(keystoreFormat) keystore.load(new FileInputStream(keystoreName), keystorePassword.toCharArray()) def key = keystore.getKey(alias, keyPassword.toCharArray()) println "-----BEGIN PRIVATE KEY-----" println key.getEncoded().encodeBase64() println "-----END PRIVATE KEY-----" A: For android development, to convert keystore created in eclipse ADT into public key and private key used in SignApk.jar: export private key: keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der openssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem edit private.rsa.pem and leave "-----BEGIN PRIVATE KEY-----" to "-----END PRIVATE KEY-----" paragraph, then: openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der export public key: keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der sign apk: java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk A: This question came up on stackexchange security, one of the suggestions was to use Keystore explorer https://security.stackexchange.com/questions/3779/how-can-i-export-my-private-key-from-a-java-keytool-keystore Having just tried it, it works really well and I strongly recommend it. A: A portion of code originally from Example Depot for listing all of the aliases in a key store: // Load input stream into keystore keystore.load(is, password.toCharArray()); // List the aliases Enumeration aliases = keystore.aliases(); for (; aliases.hasMoreElements(); ) { String alias = (String)aliases.nextElement(); // Does alias refer to a private key? boolean b = keystore.isKeyEntry(alias); // Does alias refer to a trusted certificate? b = keystore.isCertificateEntry(alias); } The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app. import java.io.FileInputStream; import java.security.Key; import java.security.KeyStore; import sun.misc.BASE64Encoder; public class DumpPrivateKey { /** * Provides the missing functionality of keytool * that Apache needs for SSLCertificateKeyFile. * * @param args <ul> * <li> [0] Keystore filename. * <li> [1] Keystore password. * <li> [2] alias * </ul> */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha n keystore"); } final String keystoreName = args[0]; final String keystorePassword = args[1]; final String alias = args[2]; final String keyPassword = getKeyPassword(args,keystorePassword); KeyStore ks = KeyStore.getInstance("jks"); ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray()); Key key = ks.getKey(alias, keyPassword.toCharArray()); String b64 = new BASE64Encoder().encode(key.getEncoded()); System.out.println("-----BEGIN PRIVATE KEY-----"); System.out.println(b64); System.out.println("-----END PRIVATE KEY-----"); } private static String getKeyPassword(final String[] args, final String keystorePassword) { String keyPassword = keystorePassword; // default case if(args.length == 4) { keyPassword = args[3]; } return keyPassword; } } Note: this use Sun package, which is a "bad thing". If you can download apache commons code, here is a version which will compile without warning: javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java and will give the same result: import java.io.FileInputStream; import java.security.Key; import java.security.KeyStore; //import sun.misc.BASE64Encoder; import org.apache.commons.codec.binary.Base64; public class DumpPrivateKey { /** * Provides the missing functionality of keytool * that Apache needs for SSLCertificateKeyFile. * * @param args <ul> * <li> [0] Keystore filename. * <li> [1] Keystore password. * <li> [2] alias * </ul> */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha n keystore"); } final String keystoreName = args[0]; final String keystorePassword = args[1]; final String alias = args[2]; final String keyPassword = getKeyPassword(args,keystorePassword); KeyStore ks = KeyStore.getInstance("jks"); ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray()); Key key = ks.getKey(alias, keyPassword.toCharArray()); //String b64 = new BASE64Encoder().encode(key.getEncoded()); String b64 = new String(Base64.encodeBase64(key.getEncoded(),true)); System.out.println("-----BEGIN PRIVATE KEY-----"); System.out.println(b64); System.out.println("-----END PRIVATE KEY-----"); } private static String getKeyPassword(final String[] args, final String keystorePassword) { String keyPassword = keystorePassword; // default case if(args.length == 4) { keyPassword = args[3]; } return keyPassword; } } You can use it like so: java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat A: First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys. Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt option of its pkcs8 utility): KeyStore keys = ... char[] password = ... Enumeration<String> aliases = keys.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (!keys.isKeyEntry(alias)) continue; Key key = keys.getKey(alias, password); if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) { /* Most PrivateKeys use this format, but check for safety. */ try (FileOutputStream os = new FileOutputStream(alias + ".key")) { os.write(key.getEncoded()); os.flush(); } } } If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question. A: Another great tool is KeyStore Explorer: http://keystore-explorer.sourceforge.net/ A: You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use keytool to convert to the standard format. Make sure you use the same password for both files (private key password, not the keystore password) or you will get odd failures later on in the second step. keytool -importkeystore -srckeystore keystore.jks \ -destkeystore intermediate.p12 -deststoretype PKCS12 Next, use OpenSSL to do the extraction to PEM: openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format). When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly. The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab. A: Another less-conventional but arguably easier way of doing this is with JXplorer. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.
{ "language": "en", "url": "https://stackoverflow.com/questions/150167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: transaction isolation problem or wrong approach? I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters. Their initial naive implementation was something like BEGIN INSERT INTO B SELECT * FROM A DELETE FROM A COMMIT; END Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted). Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table. However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows DURING THE WAIT. We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach. However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command. In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why? A: Depending on your isolation level, selecting all the rows from a table does not prevent new inserts, it will just lock the rows you read. In SQL Server, if you use the Serializable isolation level then it will prevent new rows if they would have been including in your select query. http://msdn.microsoft.com/en-us/library/ms173763.aspx - SERIALIZABLE Specifies the following: * *Statements cannot read data that has been modified but not yet committed by other transactions. *No other transactions can modify data that has been read by the current transaction until the current transaction completes. *Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes. A: I can't speak to the transaction stability, but an alternate approach would be to have the second step delete from the source table where exists (select ids from target table). Forgive the syntax, I have not tested this code, but you should be able to get the idea: INSERT INTO B SELECT * FROM A; DELETE FROM A WHERE EXISTS (SELECT B.<primarykey> FROM B WHERE B.<primarykey> = A.<primarykey>); That way you are using the relational engine to enforce that no newer data will be deleted, and you don't need to do the two steps in a transaction. Update: corrected syntax in subquery A: This can be achieved in Oracle using: Alter session set isolation_level=serializable; This can be set in PL/SQL using EXECUTE IMMEDIATE: BEGIN EXECUTE IMMEDIATE 'Alter session set isolation_level=serializable'; ... END; See Ask Tom: On Transaction Isolation Levels A: It's just the way transactions work. You have to pick the correct isolation level for the task at hand. You're doing INSERT and DELETE in the same transaction. You don't mention the isolation mode transaction is using, but it's probably 'read committed'. This means that the DELETE command will see the records that were committed in the meantime. For this kind of job, it's much better to use 'snapshot' type of transaction, because then both INSERT and DELETE would know about the same set of records - only those and nothing else. A: i don't know if this is relevant, but in SQL Server the syntax is begin tran .... commit not just 'begin' A: You need to set your transaction isolation level so that the inserts from another transaction don't affect your transaction. I don't know how to do that in Oracle. A: In Oracle, the default transaction isolation level is read committed. That basically means that Oracle returns the results as they existed at the SCN (system change number) when your query started. Setting the transaction isolation level to serializable means that the SCN is captured at the start of the transaction so all the queries in your transaction return data as of that SCN. That ensures consistent results regardless of what other sessions and transactions are doing. On the other hand, there may be a cost in that Oracle may determine that it cannot serialize your transaction because of activity that other transactions are performing, so you would have to handle that sort of error. Tony's link to the AskTom discussion goes in to substantially more detail about all this-- I highly recommend it. A: Yes Milan, I haven't specified the transaction isolation level. I suppose it's the default isolation level which I don't know which it is. Neither in Oracle 11g nor in SQL Server 2005. Furthermore the INSERT that was made during the WAIT command (on the 2nd connection) was NOT inside a transaction. Should have it been to prevent this data loss? A: This is the standard behaviour of the default read-committed mode, as mentioned above. The WAIT command just causes a delay in processing, there's no link to any DB transaction handling. To fix the problem you can either: * *set the isolation level to serializable, but then you can get ORA- errors, which you need to handle with retries! Also, you may get a serious performance hit. *use a temp table to store the values first *if the data is not too large to fit into the memory, you can use a RETURNING clause to BULK COLLECT INTO a nested table and delete only if the row is present in the nested table. A: Alternatively, you can use snapshot isolation to detect lost updates: When Snapshot Isolation Helps and When It Hurts A: I have written a sample code:- First run this on Oracle DB:- Create table AccountBalance ( id integer Primary Key, acctName varchar2(255) not null, acctBalance integer not null, bankName varchar2(255) not null ); insert into AccountBalance values (1,'Test',50000,'Bank-a'); Now run the below code package com.java.transaction.dirtyread; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DirtyReadExample { /** * @param args * @throws ClassNotFoundException * @throws SQLException * @throws InterruptedException */ public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connectionPayment = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr"); Connection connectionReader = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr"); try { connectionPayment.setAutoCommit(false); connectionPayment.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } catch (SQLException e) { e.printStackTrace(); } Thread pymtThread=new Thread(new PaymentRunImpl(connectionPayment)); Thread readerThread=new Thread(new ReaderRunImpl(connectionReader)); pymtThread.start(); Thread.sleep(2000); readerThread.start(); } } package com.java.transaction.dirtyread; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ReaderRunImpl implements Runnable{ private Connection conn; private static final String QUERY="Select acctBalance from AccountBalance where id=1"; public ReaderRunImpl(Connection conn){ this.conn=conn; } @Override public void run() { PreparedStatement stmt =null; ResultSet rs =null; try { stmt = conn.prepareStatement(QUERY); System.out.println("In Reader thread --->Statement Prepared"); rs = stmt.executeQuery(); System.out.println("In Reader thread --->executing"); while (rs.next()){ System.out.println("Balance is:" + rs.getDouble(1)); } System.out.println("In Reader thread --->Statement Prepared"); Thread.sleep(5000); stmt.close(); rs.close(); stmt = conn.prepareStatement(QUERY); rs = stmt.executeQuery(); System.out.println("In Reader thread --->executing"); while (rs.next()){ System.out.println("Balance is:" + rs.getDouble(1)); } stmt.close(); rs.close(); stmt = conn.prepareStatement(QUERY); rs = stmt.executeQuery(); System.out.println("In Reader thread --->executing"); while (rs.next()){ System.out.println("Balance is:" + rs.getDouble(1)); } } catch (SQLException | InterruptedException e) { e.printStackTrace(); }finally{ try { stmt.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } } package com.java.transaction.dirtyread; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class PaymentRunImpl implements Runnable{ private Connection conn; private static final String QUERY1="Update AccountBalance set acctBalance=40000 where id=1"; private static final String QUERY2="Update AccountBalance set acctBalance=30000 where id=1"; private static final String QUERY3="Update AccountBalance set acctBalance=20000 where id=1"; private static final String QUERY4="Update AccountBalance set acctBalance=10000 where id=1"; public PaymentRunImpl(Connection conn){ this.conn=conn; } @Override public void run() { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(QUERY1); stmt.execute(); System.out.println("In Payment thread --> executed"); Thread.sleep(3000); stmt = conn.prepareStatement(QUERY2); stmt.execute(); System.out.println("In Payment thread --> executed"); Thread.sleep(3000); stmt = conn.prepareStatement(QUERY3); stmt.execute(); System.out.println("In Payment thread --> executed"); stmt = conn.prepareStatement(QUERY4); stmt.execute(); System.out.println("In Payment thread --> executed"); Thread.sleep(5000); //case 1 conn.rollback(); System.out.println("In Payment thread --> rollback"); //case 2 //conn.commit(); // System.out.println("In Payment thread --> commit"); } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally{ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } Output:- In Payment thread --> executed In Reader thread --->Statement Prepared In Reader thread --->executing Balance is:50000.0 In Reader thread --->Statement Prepared In Payment thread --> executed In Payment thread --> executed In Payment thread --> executed In Reader thread --->executing Balance is:50000.0 In Reader thread --->executing Balance is:50000.0 In Payment thread --> rollback U can test it by inserting new rows as defined by oracle:- A phantom read occurs when transaction A retrieves a set of rows satisfying a given condition, transaction B subsequently inserts or updates a row such that the row now meets the condition in transaction A, and transaction A later repeats the conditional retrieval. Transaction A now sees an additional row. This row is referred to as a phantom. It will avoid the above scenario as well as I have used TRANSACTION_SERIALIZABLE. It will set the most strict lock on the Oracle. Oracle only supports 2 type of transaction isolation levels:- TRANSACTION_READ_COMMITTED and TRANSACTION_SERIALIZABLE.
{ "language": "en", "url": "https://stackoverflow.com/questions/150177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: send e-mail and check status Using Java mail, I would like to send an e-mail and check the status. Possible statuses include: * *Hard-bounce: No mail server found *Soft-bounce: Mail server found, but account not found *Success Is it even possible to send an e-mail and get some feedback about the delivery attempt in the manner I've described above? EDIT: A respondent suggested looking for a Java library that provides the same functionality as ListNanny. I've searched around, but haven't found anything. Any idea if such a library exists? A: You can't do this reliably or consistently. What happens if your local mail server passes it onto a corporate out-going mail server, and then it bounces when that server tries to pass it on? What happens if the mail server can't talk to the other mail server and then the message times out after 4 days? A: If you're sending out HTML email, you might want to embed a 1 pixel transparent image in the email. The image URL would actually reference a servlet that returns the image. The URL would also have some sort of message id as a parameter. The idea behind this is that when the user reads the message, he/she displays the image, which triggers your servlet, which writes to the db that the message had been read. A: What you have to do is set the envelope SMTP sender to an address you monitor for NDR messages. You have to parse the emails as they come in and figure out what went wrong. This is commonly done for mailing lists, and products like ListNanny are used to process the messages (it's a .NET product, but I'm sure there is a Java equivalent, or you could write it yourself). The envelope "from" is different than the message "from" address. It's part of the SMTP conversation that happens between your code and your MTA. All NDRs will be sent to that address. A: Finding the mail server and connecting: easy. Checking for an account: possible. But it depends on whether you get access to the mail server in the first place. It may decline your connection attempts (e.g. because your network is blacklisted) The most complicated thing is what you call "success": Short answer: No. Long answer: Theoretically it would be possible, but you would have to wait for hours if not days to know the status. With graylisting, whitelisting, spam-blocking mail servers many will only accept an email after several delivery attempts. You will only know about delivery success when they have finally delivered or given up on the mail. And depending on mail server load the sending of an email may be postponed for an arbitrary amount of time. A: I'm not famliar specifically w/Javamail, but I would say this: Even "success" may not be success. You're definition of hard and soft failures should be simple enough to check. If you can't find a server it's hard, if you connet and the server says "mailbox not found" it's "soft". But what if the server accepts the message and then bounces it later? Many front-end servers accept unknown messages, either by design or necessity (front end relay for "real" backend servers) and if the message is later found to be addressed to an invalid address the message is bounced back to the sender. In that case you'll have reported a "success" in sending when it's really not successful. Ensuring delivery is next to impossible w/out some sort of "click here" embedded in the message. A: Don't rely on what you get back (if you get back) info from a server. Many mail servers are now set up to not indicate whether the receipient exists or not, due the the security hole it creates. (e.g. if a given domain is reporting ("yes"/"no") for the existence of an email address, a hacker would simply unleash a dictionary attack on the server to determine all the valid users, and thus they get an instant spam list. A: You can use http://www.mailcounter.info free service to check whether your email has been read as well as how many times it has been read by t he user. Its a free service. A: what you should do is actually check the MX record of the recipient's email (DNS MX query of the domain portion of the email address) and send the message via the SMTP server that is resolved. this way, if the MX record is not found, you get a "Hard Bounce", if it is found but the send method throws an exception, you get a "Soft Bounce", and if it goes through - you get a "Success". you can use the dnsjava project to resolve the MX record. http://www.dnsjava.org/ A: This link might helps you. This in an experimental jar file which uses RFC 3642 and RFC 3464. It has some basic classes which allows you to get the mail delivery status. And also you'll need Javamail jar file.
{ "language": "en", "url": "https://stackoverflow.com/questions/150183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to order headers in .NET C++ projects I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project. this forum thread IDataObject : ambiguous symbol error answers a problem I've seen multiple times. Post #4 states "Move all 'using namespace XXXX' from .h to .cpp" this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like void loadConfigurations(String^ pPathname); How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file? A: It's a good idea to always use fully qualified names in header files. Because the using statement affects all following code regardless of #include, putting a using statement in a header file affects everybody that might include that header. So you would change your function declaration in your header file to: void loadConfigurations(SomeNamespace::String^ pPathname); where SomeNamespace is the name of the namespace you were using previously. A: I don't know much about .NET, so my answer only applies to the unmanaged c++ part of your question. Personally, this is one of the main reasons I avoid like the plague "using namespace XXXX;" statements. I prefer to just be explicit with namespaces like "std::cout << "hello world" << std::endl;" This avoid namespace collisions and there is never any ambiguity as to where something came from. Also, when you do something like "using namespace std;" you are kinda undoing what namespaces give you. They were designed to avoid collisions and by importing everything into the global, you just invite collisions back in. This is stricly a matter of opinion and taste. As for what to do in headers, I just write stuff like this: "void f(const std::string &s);" A: To solve this I've done this in the .h file: namespace TestClassNS { class TestClass; } and then in the .cpp file I would #include the .h that TestClass was in and do the using namespaceTestClassNS there. My C++ is rusty, so there may be a better way. A: In my experience the only namespace you have to be careful about is System itself. It's somewhat annoying that the most common, most important one is where you find problems, but that's life. At least you can take comfort that if you're creating managed classes, you're issues with includes will get relief at the assembly barrier, unlike issues with header files for unmanaged classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/150186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In firebug, how do I find out all of the css styles being applied to a particular element? I'm way buried in many nested levels of css, and I can't tell which style layer/level is messing up my display. How can I find out everything that's being applied to a particular element? A: Right click the element and choose "Inspect Element", then you should see the element and all of the CSS rules which contributed to it. You can modify the rules simply by clicking and editing the values to try out different things to correct problems. A: Use the Inspect button. Click on the item you're interested in. On the right-hand side, Firebug shows all the styles of the element, and the file + line number they originiated from. Find the style you're trying to apply, and see if it has a stroke through it. If it does, it's being overridden by something higher in the hierarchy. Now you have to decide how you want to solve it. Either by making your css entry more specific to the item in question, or modifying your styles in some other manner. A: Click Inspect (upper left) to select the element you want to check then on the right panel select the tab labeled "Style". It will also tell you from which .css file that particular property comes from A: from the 'CSS' tab, click on "Inspect" and then click on the element. All the applied styles (and their origin) will show up on the right hand side.
{ "language": "en", "url": "https://stackoverflow.com/questions/150191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using underscores in Java variables and method names Even nowadays I often see underscores in Java variables and methods. An example are member variables (like "m_count" or "_count"). As far as I remember, to use underscores in these cases is called bad style by Sun. The only place they should be used is in constants (like in "public final static int IS_OKAY = 1;"), because constants should be all upper case and not camel case. Here, the underscore should make the code more readable. Do you think using underscores in Java is bad style? If so (or not), why? A: "Bad style" is very subjective. If a certain conventions works for you and your team, I think that will qualify a bad/good style. To answer your question: I use a leading underscore to mark private variables. I find it clear and I can scan through code fast and find out what's going on. (I almost never use "this" though, except to prevent a name clash.) A: Using 'm_' or '_' in the front of a variable makes it easier to spot member variables in methods throughout an object. As a side benefit, typing 'm_' or '_' will make intellsense pop them up first ;) A: Here's a link to Sun's recommendations for Java. Not that you have to use these or even that their library code follows all of them, but it's a good start if you're going from scratch. Tool like Eclipse have built in formatters and cleanup tools that can help you conform to these conventions (or others that you define). For me, '_' are too hard to type :) A: * *I happen to like leading underscores for (private) instance variables. It seems easier to read and distinguish. Of course, this thing can get you into trouble with edge cases (e.g., public instance variables (not common, I know) - either way you name them, you're arguably breaking your naming convention: private int _my_int; public int myInt;? _my_int? ) *As much as I like the _style of this and think it's readable, I find it's arguably more trouble than it's worth, as it's uncommon and it's likely not to match anything else in the codebase you're using. Automated code generation (e.g., Eclipse's generate getters and setters) aren't likely to understand this, so you'll have to fix it by hand or muck with Eclipse enough to get it to recognize it. Ultimately, you're going against the rest of the (Java) world's preferences and are likely to have some annoyances from that. And as previous posters have mentioned, consistency in the codebase trumps all of the above issues. A: There is a reason why using underscores was considered being bad style in the old days. When a runtime compiler was something unaffordable and monitors came with astonishing 320x240 pixel resolution it was often not easy to differentiate between _name and __name. A: It's nice to have something to distinguish private vs. public variables, but I don't like '_' in general coding. If I can help it in new code, I avoid their use. A: Rules: * *Do what the code you are editing does *If #1 doesn't apply, use camelCase, no underscores A: I don't think using _ or m_ to indicate member variables is bad in Java or any other language. In my opinion, it improves readability of your code because it allows you to look at a snippet and quickly identify out all of the member variables from locals. You can also achieve this by forcing users to prepend instance variables with "this", but I find this slightly draconian. In many ways it violates DRY because it's an instance variable. Why qualify it twice? My own personal style is to use m_ instead of _. The reason being that there are also global and static variables. The advantage to m_/_ is it distinguishes a variable's scope. So you can't reuse _ for global or static and instead I choose g_ and s_ respectively. A: It's a blend of coding styles. One school of thought is to preface private members with an underscore to distinguish them. setBar( int bar) { _bar = bar; } instead of setBar( int bar) { this.bar = bar; } Others will use underscores to indicate a temporary local variable that will go out of scope at the end of the method call. (I find this pretty useless - a good method shouldn't be that long, and the declaration is right there! So I know it goes out of scope.) God forbid a programmer from this school and a programmer from the memberData school collaborate! It would be hell. Sometimes, generated code will preface variables with _ or __. The idea being that no human would ever do this, so it's safe. A: I think any style that breaks a language's own style guidelines (without due reason) is ugly and therefore "bad". No doubt the code you've seen was written by someone who used to work on a language where underscores were acceptable. Some people just cannot adapt to new coding styles... A: The reason people do it (in my experience) is to differentiate between member variables and function parameters. In Java you can have a class like this: public class TestClass { int var1; public void func1(int var1) { System.out.println("Which one is it?: " + var1); } } If you made the member variable _var1 or m_var1, you wouldn't have the ambiguity in the function. So it's a style, and I wouldn't call it bad. A: Personally, I think a language shouldn't make rules about coding style. It is a matter of preferences, usage, convenience, and concept about readability. Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team). At least, IDEs like Eclipse are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines. Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing Booleans with an initial b, using an initial uppercase letter for function names and aligning braces... The horror for Java fundamentalists! ;-) Funnily, that's the conventions used where I work... probably because the main initial developer comes from the MFC world! :-D A: If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that. The biggest thing about coding style is consistency. If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start. A: sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs(); as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable(); A: It's just your own style, not a bad style code nor a good style code. It just differentiates our code with the others.
{ "language": "en", "url": "https://stackoverflow.com/questions/150192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: Using "Remember Me" functionality for authentication in .NET 2.0 My client wants me to enable a "Remember Me" checkbox when the user logs in. I am encrypting and storing both the username and password in a cookie. However, you cannot write to a textbox when it's in password mode. I've seen this done numerous times, so how are they doing it? thanks in advance! A: How about instead of inserting the text into the login form, you just bypass the form completely and check the contents of the cookie right at the login page? Less work for the user, and it'll make it a little more seamless. A: Page_Load( ...) { ... process cookie ... if (cookie is good) Response.Redirect("content.aspx"); } Just remember to close and dispose any database activity before redirecting. A: They don't want the user to automatically be logged in they just want the usernamd and password field pre-filled in. I know it's stupid and the same thing as keeping you logged in, but it's their request. I've mentioned that it's not the best security practice but they don't care. sites like myspace use it, wher eyou go to myspace.com and your usernamd and password are already filled in. A: I don't recall any web page doing something like that as you described but I think it's the web browsers automatically filling passwords. I know this is not a good solution but what you can do might be, setting the text of o normal textbox with stars or something like that in a different login page if there is a cookie to authenticate the user. You don't need to use the password from the textbox to authenticate the user anyway. A: If your server-side code has access to their username and password from the cookie, then can't your page just populate the value attributes of the form fields like so: <input type="text" name="username" value="<%=decryptedUsername%>" /> <input type="password" value="<%=decryptedPassword%>" /> Of course, this is pretty un-secure as you're echo-ing the users password back to them in plain-text (which is a big no-no). But as you say your client isn't that bothered about the security implications. If they are then SSL may help mitigate this risk. A: You can set the expiration of the cookie in 2 weeks to keep the user logged in. That's how ASP.NET authentication works with persistent authentication. Remember to update the expiration on every request. A: Thatz quite straight forward, try using: txtPass.Attributes["value"] = "123456"; (most probably on the page load event handler) where txtPass is the id of the password textbox (in password mode). and the password u want displayed is 123456. A: Is it possible for the text box to have the type changed? If so, can you make the text box normal and hidden, then put the password in there, then change the text box type to password type, then unhide it...
{ "language": "en", "url": "https://stackoverflow.com/questions/150201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I convert HTML to RTF (Rich Text) in .NET without paying for a component? Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)? The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish. I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly. A: Check out this CodeProject article on XHTML2RTF. A: Expanding on Spartaco's answer I implimented the following which works GREAT! Using reportWebBrowser As New WebBrowser reportWebBrowser.CreateControl() reportWebBrowser.DocumentText = sbHTMLDoc.ToString While reportWebBrowser.DocumentText <> sbHTMLDoc.ToString Application.DoEvents() End While reportWebBrowser.Document.ExecCommand("SelectAll", False, Nothing) reportWebBrowser.Document.ExecCommand("Copy", False, Nothing) Using reportRichTextBox As New RichTextBox reportRichTextBox.Paste() reportRichTextBox.SaveFile(DocumentFileName) End Using End Using A: Actually there is a simple and free solution: use your browser, ok this is the trick I used: var webBrowser = new WebBrowser(); webBrowser.CreateControl(); // only if needed webBrowser.DocumentText = *yourhtmlstring*; while (_webBrowser.DocumentText != *yourhtmlstring*) Application.DoEvents(); webBrowser.Document.ExecCommand("SelectAll", false, null); webBrowser.Document.ExecCommand("Copy", false, null); *yourRichTextControl*.Paste(); This could be slower than other methods but at least it's free and works! A: It is not perfect of course, but here is the code I use to convert HTML to plain text. (I was not the original author, I adapted it from code found on the web) public static string ConvertHtmlToText(string source) { string result; // Remove HTML Development formatting // Replace line breaks with space // because browsers inserts space result = source.Replace("\r", " "); // Replace line breaks with space // because browsers inserts space result = result.Replace("\n", " "); // Remove step-formatting result = result.Replace("\t", string.Empty); // Remove repeating speces becuase browsers ignore them result = System.Text.RegularExpressions.Regex.Replace(result, @"( )+", " "); // Remove the header (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*head([^>])*>", "<head>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*head( )*>)", "</head>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(<head>).*(</head>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // remove all scripts (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*script([^>])*>", "<script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*script( )*>)", "</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //result = System.Text.RegularExpressions.Regex.Replace(result, // @"(<script>)([^(<script>\.</script>)])*(</script>)", // string.Empty, // System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<script>).*(</script>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // remove all styles (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*style([^>])*>", "<style>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*style( )*>)", "</style>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(<style>).*(</style>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert tabs in spaces of <td> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*td([^>])*>", "\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert line breaks in places of <BR> and <LI> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*br( )*>", "\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*li( )*>", "\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert line paragraphs (double line breaks) in place // if <P>, <DIV> and <TR> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*div([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*tr([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*p([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove remaining tags like <a>, links, images, // comments etc - anything thats enclosed inside < > result = System.Text.RegularExpressions.Regex.Replace(result, @"<[^>]*>", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // replace special characters: result = System.Text.RegularExpressions.Regex.Replace(result, @"&nbsp;", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&bull;", " * ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&lsaquo;", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&rsaquo;", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&trade;", "(tm)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&frasl;", "/", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @">", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&copy;", "(c)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&reg;", "(r)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove all others. More can be added, see // http://hotwired.lycos.com/webmonkey/reference/special_characters/ result = System.Text.RegularExpressions.Regex.Replace(result, @"&(.{2,6});", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // make line breaking consistent result = result.Replace("\n", "\r"); // Remove extra line breaks and tabs: // replace over 2 breaks with 2 and over 4 tabs with 4. // Prepare first to remove any whitespaces inbetween // the escaped characters and remove redundant tabs inbetween linebreaks result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)( )+(\r)", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\t)( )+(\t)", "\t\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\t)( )+(\r)", "\t\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)( )+(\t)", "\r\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove redundant tabs result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)(\t)+(\r)", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove multible tabs followind a linebreak with just one tab result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)(\t)+", "\r\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Initial replacement target string for linebreaks string breaks = "\r\r\r"; // Initial replacement target string for tabs string tabs = "\t\t\t\t\t"; for (int index = 0; index < result.Length; index++) { result = result.Replace(breaks, "\r\r"); result = result.Replace(tabs, "\t\t\t\t"); breaks = breaks + "\r"; tabs = tabs + "\t"; } // Thats it. return result; } A: I recommend a console tool named Pandoc. It is not a component, it is rather huge conversion pack. I am using it to convert between HTML and LaTeX. It is just awesome. The full list of supported formats you can find on the program page. In order to convert an HTML document to RTF format you write on the console: pandoc filename.html -f html -t rtf -s -o filename.rtf A: Maybe what you need is a control to edit the HTML?
{ "language": "en", "url": "https://stackoverflow.com/questions/150208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: How do I use LINQ to query for items, but also include missing items? I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered. I started with this: var dailyCountList = (from a in showDC.Attendee let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day) group a by justDate into DateGroup orderby DateGroup.Key select new RegistrationCount { EventDateTime = DateGroup.Key, Count = DateGroup.Count() }).ToList(); That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero. So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above: // Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations) var allDates = new List<RegistrationCount>(); for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date <= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1)) { DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx allDates.Add(new RegistrationCount { EventDateTime = date, Count = (from dclInner in dailyCountList where dclInner.EventDateTime == thisDate select dclInner).DefaultIfEmpty(new RegistrationCount { EventDateTime = date, Count = 0 }).Single().Count }); } So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this. Can anyone thing of an elegant solution? Or at least one that is less embarrassing? A: O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff. if (!dailyCountList.Any()) return; //make a dictionary to provide O(1) lookups for later Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime); DateTime minDate = dailyCountList[0].EventDateTime; DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime; int DayCount = 1 + (int) (maxDate - minDate).TotalDays; // I have the days now. IEnumerable<DateTime> allDates = Enumerable .Range(0, DayCount) .Select(x => minDate.AddDays(x)); //project the days into RegistrationCounts, making up the missing ones. List<RegistrationCount> result = allDates .Select(d => lookup.ContainsKey(d) ? lookup[d] : new RegistrationCount(){EventDateTime = d, Count = 0}) .ToList(); A: Does this syntax for left outer joins no longer work as well after SP1, then? Usually, you should able to do the following, but you'd need a calendar table of sorts in your SQL database joined to your date key in the registrations table (w/a foreign key on the date id field), and then try: var query = from cal in dataContext.Calendar from reg in cal.Registrations.DefaultIfEmpty() select new { cal.DateID, reg.Something }; A: The problem is that you have no range of dates without executing your query. So, you can either pick a date range, run a SELECT MAX and SELECT MIN against your DB, or execute your query and then add the missing dates. var allDailyCountList = from d in Range(dc[0].EventDateTime, dc[dc.Count - 1].EventDateTime) // since you already ordered by DateTime, we don't have to search the entire List join dc in dailyCountList on d equals dc.EventDateTime into rcGroup from rc in rcGroup.DefaultIfEmpty( new RegistrationCount() { EventDateTime = d, Count = 0 } ) // gives us a left join select rc; public static IEnumerable<DateTime> Range(DateTime start, DateTime end) { for (DateTime date = start, date <= end; date = date.AddDays(1)) { yield return date; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/150213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL 2005 Express Edition - Install new instance Looking for a way to programatically, or otherwise, add a new instance of SQL 2005 Express Edition to a system that already has an instance installed. Traditionally, you run Micrsoft's installer like I am in the command line below and it does the trick. Executing the command in my installer is not the issue, it's more a matter of dragging around the 40 MBs of MS-SQL installer that I don't need if they have SQL Express already installed. This is what my installer currently executes: SQLEXPR32.EXE /qb ADDLOCAL=ALL INSTANCENAME=<instancename> SECURITYMODE=SQL SAPWD=<password> SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0 I don't need assistance with launching this command, rather the appropriate way to add a new instance of SQL 2005 Express without actually running the full installer again. I'd go into great detail about why I want to do this but I'd simply bore everyone. Suffice to say, having this ability to create a new instance without the time it takes to reinstall SQL Express etc. would greatly assist me for the deployment of my application and it's installer. If makes any difference to anyone, I'm using a combination of NSIS and Advanced Installer for this installation project. A: It sounds like a user instance might help you. If you have the MDF and LDF files, you can connect to the files by instructing SQL Server Express to launch a user instance and attach the specified file to that instance. This artile http://msdn.microsoft.com/en-us/library/bb264564.aspx has a good description of how you can lean on the existing SQL Server Express installation to instantiate a user-specific instance for the duration of your connection. Hope it helps. A: I do not know how to do it with an API, but if no one gives a better solution, you can always use Process.Start() to execute your command line as-is. A: After months/years of looking into this it appears it can't be done. Oh well, I guess I just reinstall each time I want a new instance. I guess it's because each instance is it's own service.
{ "language": "en", "url": "https://stackoverflow.com/questions/150223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: While-clause in T-SQL that loops forever I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode <> 0 BEGIN Goto Cleanup END DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this END Facts: * *There's only one or two records matching the first select-clause *RowCount from the DELETE statement indicates that it has been removed *The WHILE-clause will loop forever The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity. Why does it loop forever? Clarification: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged) Clarification 2: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record. Update: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky. Update clarification: brien pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand A: Are you operating in explicit or implicit transaction mode? Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements. WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode <> 0 BEGIN Goto Cleanup END BEGIN TRANSACTION delete DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this COMMIT TRANSACTION delete END Clarification: The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful. In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to really make the changes. A: FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID Oops, your join brings the result set down to zero rows. SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID Oops, you used multi-assignment against a set with no rows. This causes the variables to remain unchanged (they will have the same value that they had last time through the loop). The variables do NOT get assigned to null in this case. If you put this code at the start of the loop, it will (correctly) fail faster: SELECT @TmpGFSID = null, @TmpQuantity = null, @TmpShoppingCartItemID = null If you change your code to fetch a key (without joining) and then fetching the related data by key in a second query, you'll win. A: Is there a record in ShoppingCartItem with that @PurchID where the GFSID is not in the GoodsForSale table? That would explain why the EXISTS returns true, but there are no more records to delete. A: Obviously, something is not being deleted or modified where it should. If the condition is still the same on the next iteration, it's going to keep going. Also, you're comparing @TmpShoppingCartItemID, and not @PurchID. I can see how these could be different, and you could delete a different row than the one that's being checked for in the while statement. A: If the above comments did not help you so far, I propose adding / replacing: DECLARE Old@ShoppingCartItemID INT SET @OldShoppingCartItemID = 0 WHILE EXISTS (SELECT ... WHERE ShoppingCartItemID > @ShoppingCartItemID) SELECT TOP 1 WHERE ShoppingCartItemID > @OldShoppingCartItemID ORDER BY ShoppingCartItemID SET @OldShoppingCartItemID = @TmpShoppingCartItemID A: If there are any shopping cart items that do not exist in the GoodsForSale table then this will spin into an infinite loop. Try changing your exists statement to take account of that (SELECT * FROM ShoppingCartItem WHERE JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID where ShoppingCartItem.PurchID = @PurchID) Or better still, rewriting this so it does not require a loop. Looping like this is an infinite loop waiting to happen. You should replace with set based operations and a transaction. A: I not sure if I understand the problem, but in the select clause it's making an inner join with another table. That join can cause to get no records and then the delete fails. Try using a left join.
{ "language": "en", "url": "https://stackoverflow.com/questions/150250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Finding un-referenced methods in a C++ app We have a large C/C++ legacy source tree that has been around the block a few times. We expect there are a substantial number of methods no longer used. Is there a tool that can help us quickly identify the unused code? A: You should get a good static code analyzer. Look around here for suitable option. * *Is there any free C++ code coverage tool which is useful? *What tools do you use for static code analysis? *What is your favourite Code Coverage tool(s) (Free and non-free) Also check out CTC++ Test Coverage Analyser A: For GCC there is GCov. A: At work, we use AQTime for any profiling needs. It comes with a static analysis tool, which should be what you need. However, if you don't need the other profilers or run on a platform or compiler not supported by AQTime, it is overkill, money-wise at least.
{ "language": "en", "url": "https://stackoverflow.com/questions/150269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the difference between __reduce__ and __reduce_ex__? I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both? A: __reduce_ex__ is what __reduce__ should have been but never became. __reduce_ex__ works like __reduce__ but the pickle protocol is passed. A: The docs say that If provided, at pickling time __reduce__() will be called with no arguments, and it must return either a string or a tuple. On the other hand, It is sometimes useful to know the protocol version when implementing __reduce__. This can be done by implementing a method named __reduce_ex__ instead of __reduce__. __reduce_ex__, when it exists, is called in preference over __reduce__ (you may still provide __reduce__ for backwards compatibility). The __reduce_ex__ method will be called with a single integer argument, the protocol version. On the gripping hand, Guido says that this is an area that could be cleaned up.
{ "language": "en", "url": "https://stackoverflow.com/questions/150284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How to programmatically get the CPU cache line size in C++? I'd like my program to read the cache line size of the CPU it's running on in C++. I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be useful to others, so post them if you know them). For Linux I could read the content of /proc/cpuinfo and parse the line beginning with cache_alignment. Maybe there is a better way involving a call to an API. For Windows I simply have no idea. A: On Linux try the proccpuinfo library, an architecture independent C API for reading /proc/cpuinfo A: Looks like at least SCO unix (http://uw714doc.sco.com/en/man/html.3C/sysconf.3C.html) has _SC_CACHE_LINE for sysconf. Perhaps other platforms have something similar? A: For x86, the CPUID instruction. A quick google search reveals some libraries for win32 and c++. I have used CPUID via inline assembler as well. Some more info: * *http://www.intel.com/Assets/PDF/appnote/241618.pdf *http://softpixel.com/~cwright/programming/simd/cpuid.php A: On Windows #include <Windows.h> #include <iostream> using std::cout; using std::endl; int main() { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); cout << "Page Size Is: " << systemInfo.dwPageSize; getchar(); } On Linux http://linux.die.net/man/2/getpagesize A: Here is sample code for those who wonder how to to utilize the function in accepted answer: #include <new> #include <iostream> #include <Windows.h> void ShowCacheSize() { using CPUInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION; DWORD len = 0; CPUInfo* buffer = nullptr; // Determine required length of a buffer if ((GetLogicalProcessorInformation(buffer, &len) == FALSE) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { // Allocate buffer of required size buffer = new (std::nothrow) CPUInfo[len]{ }; if (buffer == nullptr) { std::cout << "Buffer allocation of " << len << " bytes failed" << std::endl; } else if (GetLogicalProcessorInformation(buffer, &len) != FALSE) { const DWORD count = len / sizeof(CPUInfo); for (DWORD i = 0; i < count; ++i) { // This will be true for multiple returned caches, we need just one if (buffer[i].Relationship == RelationCache) { std::cout << "Cache line size is: " << buffer[i].Cache.LineSize << " bytes" << std::endl; break; } } } else { std::cout << "ERROR: " << GetLastError() << std::endl; } delete[] buffer; } } A: On Win32, GetLogicalProcessorInformation will give you back a SYSTEM_LOGICAL_PROCESSOR_INFORMATION which contains a CACHE_DESCRIPTOR, which has the information you need. A: I think you need NtQuerySystemInformation from ntdll.dll. A: If supported by your implementation, C++17 std::hardware_destructive_interference_size would give you an upper bound (and ..._constructive_... a lower bound), taking into account stuff like hardware prefetch of pairs of lines. But those are compile-time constants, so can't be correct on all microarchitectures for ISAs which allow different line sizes. (e.g. older x86 CPUs like Pentium III had 32-byte lines, but all later x86 CPUs have used 64-byte lines, including all x86-64. It's theoretically possible that some future microarchitecture will use 128-byte lines, but multi-threaded binaries tuned for 64-byte lines are widespread so that's perhaps unlikely for x86.) For this reason, some current implementations choose not to implement that C++ feature at all. GCC does implement it, clang doesn't (Godbolt). It becomes part of the ABI when code uses it in struct layouts, so it's not something compilers can change in future to match future CPUs for the same target. GCC defines both constructive and destructive as 64 x86-64, neglecting the destructive interference that adjacent-line prefetch can cause, e.g. on Intel Sandybridge-family. It's not nearly as disastrous as false sharing within a cache line in a high-contention case, so you might choose to only use 64-byte alignment to separate objects that different threads will be accessing independently. * *Should the cache padding size of x86-64 be 128 bytes? - a performance experiment on Skylake showing 500 +- 300 machine clears in an aligned pair of lines, vs. 10M in a single line, vs. near zero in more distant lines. Machine clears were easier to measure than actual cache misses due to losing access to the line. *Understanding std::hardware_destructive_interference_size and std::hardware_constructive_interference_size
{ "language": "en", "url": "https://stackoverflow.com/questions/150294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: How can I extract the address information from a Compressed ESRI shapefile datasource? When I download the zip file from the website it contains files with the following extensions: .dbf .prj .sbn .sbx .shp .shp.xml .shx Is this is a common data file format that I download or purchase a converter? I think this is some kind of mapping data file but I all need are the addresses it contains to push into our existing database. Specifically and related to programming. How can I setup a .NET Datasource to this group of files or just the .dbf file that actually contains the information? A: I'm guessing the address information you are looking for is stored in the dbf file. You can download the ESRI dBase driver from here. There is sample code that shows this driver in use at http://forums.esri.com/Thread.asp?c=9&f=85&t=141422. A: Much thanks to everyone who provided information. I found a CodePlex C# project that was exactly what I needed. I did have to make one small modification which I posted back on the project discussion board which was for an unknown column type of "F". But the command line program DBF2CSV worked beautifully to create a well formated csv from the dbf file. After a few minutes with Excel I had it ready to import to our MySQL database. The following project has a command line program that will convert a DBF file to CSV http://www.codeplex.com/fastdbf A: It's a shapefile There are links at the bottom of the page that may help you. My only experience with these type of files was using other proprietary (and expensive) software. A: The format for the dbf files is like the old DBase III format. The shp files contains the shapes and the shx are some kind of indices. A: You can open shapefile .dbf files in MS Access using DBase IV driver or directly in MS Excel (open as *.dbf) :o)
{ "language": "en", "url": "https://stackoverflow.com/questions/150301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 404 page that displays requested page I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem. How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using: request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server. But that didn't work. Any Ideas? The site is on IIS 6.0. We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's. A: I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward. //did the error go to a .ASP page? If so, append x (for .aspx) and //issue a 301 permanently moved //when we get an error, the querystring will be "404;<complete original URL>" string targetPage = Request.RawUrl.Substring(Request.FilePath.Length); if((null == targetPage) || (targetPage.Length == 0)) targetPage = "[home page]"; else { //find the original URL if(targetPage[0] == '?') { if(-1 != targetPage.IndexOf("?aspxerrorpath=")) targetPage = targetPage.Substring(15); // ?aspxerrorpath= else targetPage = targetPage.Substring(5); // ?404; } else { if(-1 != targetPage.IndexOf("errorpath=")) targetPage = targetPage.Substring(14); // aspxerrorpath= else targetPage = targetPage.Substring(4); // 404; } } string upperTarget = targetPage.ToUpper(); if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP"))) { //this is a request for an .ASP page - permanently redirect to .aspx targetPage = upperTarget.Replace(".ASP", ".ASPX"); //issue 301 redirect Response.Status = "301 Moved Permanently"; Response.AddHeader("Location",targetPage); Response.End(); } if(-1 != upperTarget.IndexOf("ORDER")) { //going to old order page -- forward to new page Response.Redirect(WebRoot + "/order.aspx"); Response.End(); } A: How about: Request.ServerVariables("HTTP_REFERER"); A: A lot of the links have changed, but they can be easily corrected by searching for patters in the url Rather than send your users to a 404, have you considered using url re-writes? This way your users (and search engines, if that's important to you in this case) will get a 301 or 302 rather than having to go through your 404 handler. It's usually quicker and less stressful on your servers to handle the rewrite at the url level than firing up your code and processing it there. Microsoft have released a URL Rewrite Module for IIS 7, and there's a decent introduction to it here and here. For IIS 6, there's a good intro here to getting URL rewriting working with it, slightly different than IIS7. An example rewrite rule would be # $1 will contain the contents of (.*) - everything after new-dir/ RewriteRule /new-dir/(.*) /find_old_page.asp?code=$1 there are a few hundred pages, so no one is keen on spending the time to create the 301's The beauty of rewrite rules is that you don't need to list to explicitly list all of your pages, but can write rules which follow the same pattern. We had to do something similar to this recently, and it's surprising how many of the moved urls could be handled by a couple of simple rules. A: Instead of using a 404 page, I think the proper thing to do would be to redirect with a 301 - Moved Permanently code. A: Here's what we do on init on our 404 pages: Dim AttemptedUrl As String = Request.QueryString("aspxerrorpath") If Len(AttemptedUrl) = 0 Then AttemptedUrl = Request.Url.Query AttemptedUrl = LCase(AttemptedUrl) CheckForRedirects(AttemptedUrl) CheckforRedirects then has custom logic to match up old URLs with new URLs. I'd argue that this is the preferred approach (as opposed to 301s or URL rewriting) if you have enough information internally to match up a large number of URLs from the old system with the new system - e.g. if you have a table that matches up old IDs with new IDs or something similar. If there's a consistent pattern that you can use to map old URLs to new URLs with a regex, though, then URL rewriting would be the way to go. A: To build on the Rewrites suggestion, Umbraco already uses UrlRewriting.NET and new rewrites can be added to \config\UrlRewriting.config Hope this helps A: Update, you actually want to pick up: VB.NET: Request.QueryString("aspxerrorpath") C#: Request.QueryString["aspxerrorpath"];
{ "language": "en", "url": "https://stackoverflow.com/questions/150329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combining Lists in Lambda/LINQ If I have variable of type IEnumerable<List<string>> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an IEnumerable<string>? A: How about myStrings.SelectMany(x => x) A: SelectMany - i.e. IEnumerable<List<string>> someList = ...; IEnumerable<string> all = someList.SelectMany(x => x); For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>. These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified): static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } } } Although that is simplified somewhat. A: Not exactly a single method call, but you should be able to write var concatenated = from list in lists from item in list select item; Where 'lists' is your IEnumerable<List<string>> and concatenated is of type IEnumerable<string>. (Technically this is a single method call to SelectMany - it just doesn't look like it was all I meant by the opening statement. Just wanted to clear that up in case anyone got confused or commented - I realised after I'd posted how it could have read). A: Make a simple method. No need for LINQ: IEnumerable<string> GetStrings(IEnumerable<List<string>> lists) { foreach (List<string> list in lists) foreach (string item in list) { yield return item; } } A: Using LINQ expression... IEnumerable<string> myList = from a in (from b in myBigList select b) select a; ... works just fine. :-) b will be an IEnumerable<string> and a will be a string. A: Here's another LINQ query comprehension. IEnumerable<string> myStrings = from a in mySource from b in a select b;
{ "language": "en", "url": "https://stackoverflow.com/questions/150332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How can I create Exchange distribution list inside the GAL using .NET? We need to remotely create an Exchange 2007 distribution list from Asp.Net. Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company. Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API. It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? A: Look for LDAP.NET, I don't have it handy but I've done it before and it worked well at the time. Edit: I should add that LDAP is Lightweight Directory Access Protocol. Also, I can't find LDAP.NET (I got curious and went to look) and now it appears that there's a built-in System.DirectoryServices namespace to do it for you. http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/729d1214-37f5-4330-9208-bc4d9d695ad0 A: We had a similar problem with mail enabling programatically created public folders and needed to set the msExchHideFromAddressLists property on the exchange system object in active directory... using (DirectoryEntry LDAPConnection = new DirectoryEntry("LDAP://OURDOMAIN/CN=" + name+ ",CN=Microsoft Exchange System Objects,DC=ourdomain,DC=com")) { LDAPConnection.AuthenticationType = AuthenticationTypes.Secure; LDAPConnection.Properties["msExchHideFromAddressLists"].Value = false; LDAPConnection.CommitChanges(); } PS. make sure that any DirectoryEntries are properly disposed of or you'll likely run out of connections before the GC kicks in and end up having to restart the server to clear them.
{ "language": "en", "url": "https://stackoverflow.com/questions/150333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to dynamically create RDLC xml as input to VS2005 Report Viewer? What is the best way to dynamically create RDLC xml as input to VS2005 Report Viewer? I would like to autosize columns based on the data sizes. I would also like to programmatically control what columns are displayed. A: Lisa Nicholls gives a complete answer in this thread about dynamically defining a report. You'll want to scroll down some before you get to a useful answer. This thread most directly answers your question about controlling which columns are displayed. These same techniques can be used to size the columns programmatically, but your code will have to figure out the appropriate column widths. A: Dan Smith also has a good solution at: http://csharpshooter.blogspot.com/2007/08/revised-dynamic-rdlc-generation.html Majid also has a refinement of Dan's solution in the comments to that blog entry that doesn't need to write any files to the file system.
{ "language": "en", "url": "https://stackoverflow.com/questions/150335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Generating an Excel file in ASP.NET I am about to add a section to an ASP.NET app (VB.NET codebehind) that will allow a user to get data returned to them as an Excel file, which I will generate based on database data. While there are several ways of doing this, each has its own drawbacks. How would you return the data? I'm looking for something that's as clean and straightforward as possible. A: This is a free wrapper around SpreadML--it works great. http://www.carlosag.net/Tools/ExcelXmlWriter/ A: Based on the answers given, and consultation with coworkers, it appears that the best solution is to generate either an XML file or HTML tables and push it down as an attachment. The one change recommended by my co-workers is that the data (i.e. the HTML tables) can be written directly to the Response object, thus eliminating the need to write out a file, which can be troublesome due to permissions problems, I/O contention, and ensuring that scheduled purging occurs. Here's a snippet of the code... I haven't checked this yet, and I haven't supplied all the called code, but I think it represents the idea well. Dim uiTable As HtmlTable = GetUiTable(groupedSumData) Response.Clear() Response.ContentType = "application/vnd.ms-excel" Response.AddHeader("Content-Disposition", String.Format("inline; filename=OSSummery{0:ddmmssf}.xls", DateTime.Now)) Dim writer As New System.IO.StringWriter() Dim htmlWriter As New HtmlTextWriter(writer) uiTable.RenderControl(htmlWriter) Response.Write(writer.ToString) Response.End() A: You can output the data as html table cells, stick a .xls or .xlsx extension on it, and Excel will open it as if it were a native document. You can even do some limited formatting and formula calculations this way, so it's much more powerful than CSV. Also, outputting an html table ought to be pretty easy to do from a web platform like ASP.Net ;) If you need multiple worksheets or named worksheets within your Excel Workbook, you can do something similar via an XML schema called SpreadSheetML. This is not the new format that shipped with Office 2007, but something completely different that works as far back as Excel 2000. The easiest way to explain how it works is with an example: <?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <Author>Your_name_here</Author> <LastAuthor>Your_name_here</LastAuthor> <Created>20080625</Created> <Company>ABC Inc</Company> <Version>10.2625</Version> </DocumentProperties> <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> <WindowHeight>6135</WindowHeight> <WindowWidth>8445</WindowWidth> <WindowTopX>240</WindowTopX> <WindowTopY>120</WindowTopY> <ProtectStructure>False</ProtectStructure> <ProtectWindows>False</ProtectWindows> </ExcelWorkbook> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom" /> <Borders /> <Font /> <Interior /> <NumberFormat /> <Protection /> </Style> </Styles> <Worksheet ss:Name="Sample Sheet 1"> <Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table1"> <Column ss:Width="150" /> <Column ss:Width="200" /> <Row> <Cell><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell><Data ss:Type="Number">3</Data></Cell> <Cell><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell><Data ss:Type="Number">5</Data></Cell> <Cell><Data ss:Type="Number">6</Data></Cell> </Row> <Row> <Cell><Data ss:Type="Number">7</Data></Cell> <Cell><Data ss:Type="Number">8</Data></Cell> </Row> </Table> </Worksheet> <Worksheet ss:Name="Sample Sheet 2"> <Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table2"> <Column ss:Width="150" /> <Column ss:Width="200" /> <Row> <Cell><Data ss:Type="String">A</Data></Cell> <Cell><Data ss:Type="String">B</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">C</Data></Cell> <Cell><Data ss:Type="String">D</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">E</Data></Cell> <Cell><Data ss:Type="String">F</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">G</Data></Cell> <Cell><Data ss:Type="String">H</Data></Cell> </Row> </Table> </Worksheet> </Workbook> A: since Excel understands HTML you can just write the data out as an HTML table to a temp file with an .xls extension, get the FileInfo for the file, and blow it back using Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name); Response.AddHeader("Content-Length", fi.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(fi.FullName); Response.End(); if you wanted to avoid the temp file, you could write to an in-memory stream and write the bytes back instead of using WriteFile if the content-length header is omitted you could just write the html back directly, but this may not work correctly all the time in all browsers A: I personally prefer the XML method. I'll return the data from the database in a Dataset, save it to XMl, then I create an xslt file that contains a transformation rule that will format a proper document, and a simple XML transform will finish the job up. The best part of about this you can format cells, do conditional formatting, setup headers and footers, and even set print ranges. A: I've done this a couple of times and each time the easiest way was to simply return a CSV (Comma Separated Value) file. Excel imports it perfectly, and it's relatively fast to do. A: we export data from a datagrid to excel all the time. Converting it to HTML then writing to an excel file Response.ContentType = "application/vnd.ms-excel" Response.Charset = "" Response.AddHeader("content-disposition", "fileattachment;filename=YOURFILENAME.xls") Me.EnableViewState = False Dim sw As System.IO.StringWriter = New System.IO.StringWriter Dim hw As HtmlTextWriter = New HtmlTextWriter(sw) ClearControls(grid) grid.RenderControl(hw) Response.Write(sw.ToString()) Response.End() The only gotcha with this method was that a lot of our grids had buttons or links in them so you need this too: 'needed to export grid to excel to remove link button control and represent as text Private Sub ClearControls(ByVal control As Control) Dim i As Integer For i = control.Controls.Count - 1 To 0 Step -1 ClearControls(control.Controls(i)) Next i If TypeOf control Is System.Web.UI.WebControls.Image Then control.Parent.Controls.Remove(control) End If If (Not TypeOf control Is TableCell) Then If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then Dim literal As New LiteralControl control.Parent.Controls.Add(literal) Try literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing)) Catch End Try control.Parent.Controls.Remove(control) Else If Not (control.GetType().GetProperty("Text") Is Nothing) Then Dim literal As New LiteralControl control.Parent.Controls.Add(literal) literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing)) control.Parent.Controls.Remove(control) End If End If End If Return End Sub I found that somewhere, it works well. A: Here's a report that pulls from a stored procedure. The results are exported to Excel. It uses ADO instead of ADO.NET and the reason why is this line oSheet.Cells(2, 1).copyfromrecordset(rst1) It does most of the work and isn't available in ado.net. ‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim cnn As ADODB.Connection cnn = New ADODB.Connection cnn.Open("Provider=SQLOLEDB;data source=xxxxxxx;" & _ "database=xxxxxxxx;Trusted_Connection=yes;") Dim cmd As New ADODB.Command cmd.ActiveConnection = cnn cmd.CommandText = "[sp_TomTepley]" cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc cmd.CommandTimeout = 0 cmd.Parameters.Refresh() Dim rst1 As ADODB.Recordset rst1 = New ADODB.Recordset rst1.Open(cmd) Dim oXL As New Excel.Application Dim oWB As Excel.Workbook Dim oSheet As Excel.Worksheet 'oXL = CreateObject("excel.application") oXL.Visible = True oWB = oXL.Workbooks.Add oSheet = oWB.ActiveSheet Dim Column As Integer Column = 1 Dim fld As ADODB.Field For Each fld In rst1.Fields oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15 Column = Column + 1 Next fld oXL.Workbooks(1).Worksheets(1).name = "Tom Tepley Report" oSheet.Cells(2, 1).copyfromrecordset(rst1) oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit() oXL.Visible = True oXL.UserControl = True rst1 = Nothing cnn.Close() Beep() End Sub A: I recommend free opensource excel generation libruary which is based on OpenXML It helped me several months ago. A: If coming from a DataTable: public static void DataTabletoXLS(DataTable DT, string fileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "utf-16"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; string tab = ""; foreach (DataColumn dc in DT.Columns) { HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", "")); tab = "\t"; } HttpContext.Current.Response.Write("\n"); int i; foreach (DataRow dr in DT.Rows) { tab = ""; for (i = 0; i < DT.Columns.Count; i++) { HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", "")); tab = "\t"; } HttpContext.Current.Response.Write("\n"); } HttpContext.Current.Response.End(); } From a Gridview: public static void GridviewtoXLS(GridView gv, string fileName) { int DirtyBit = 0; int PageSize = 0; if (gv.AllowPaging == true) { DirtyBit = 1; PageSize = gv.PageSize; gv.AllowPaging = false; gv.DataBind(); } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}.xls", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a table to contain the grid Table table = new Table(); // include the gridline settings table.GridLines = gv.GridLines; // add the header row to the table if (gv.HeaderRow != null) { Utilities.Export.PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gv.Rows) { Utilities.Export.PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gv.FooterRow != null) { Utilities.Export.PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString().Replace("£", "")); HttpContext.Current.Response.End(); } if (DirtyBit == 1) { gv.PageSize = PageSize; gv.AllowPaging = true; gv.DataBind(); } } private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { Utilities.Export.PrepareControlForExport(current); } } } A: CSV Pros: * *Simple Cons: * *It may not work in other locales or in different Excel configurations (i.e. List separator) *Can't apply formatting, formulas, etc HTML Pros: * *Still pretty Simple *Supports simple formating and formulas Cons: * *You have to name the file as xls and Excel may warn you about opening a non native Excel file *One worksheet per workbook OpenXML (Office 2007 .XLSX) Pros: * *Native Excel format *Supports all Excel features *Do not require an install copy of Excel *Can generate Pivot tables *Can be generated using open source project EPPlus Cons: * *Limited compatibility outside Excel 2007 (shouldn't be a problem nowadays) *Complicated unless you're using a third party component SpreadSheetML (open format XML) Pros: * *Simple compared to native Excel formats *Supports most Excel features: formating, styles, formulas, multiple sheets per workbook *Excel does not need to be installed to use it *No third party libraries needed - just write out your xml *Documents can be opened by Excel XP/2003/2007 Cons: * *Lack of good documentation *Not supported in older versions of Excel (pre-2000) *Write-only, in that once you open it and make changes from Excel it's converted to native Excel. XLS (generated by third party component) Pros: * *Generate native Excel file with all the formating, formulas, etc. Cons: * *Cost money *Add dependencies COM Interop Pros: * *Uses native Microsoft libraries *Read support for native documents Cons: * *Very slow *Dependency/version matching issues *Concurrency/data integrity issues for web use when reading *Very slow *Scaling issues for web use (different from concurrency): need to create many instances of heavy Excel app on the server *Requires Windows *Did I mention that it's slow? A: If you fill a GridView with data you can use this function to get the HTML formatted data, but indicating the browser it's an excel file. Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView) HttpContext.Current.Response.Clear() HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName)) HttpContext.Current.Response.ContentType = "application/ms-excel" Dim sw As StringWriter = New StringWriter Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) Dim table As Table = New Table table.GridLines = gv.GridLines If (Not (gv.HeaderRow) Is Nothing) Then PrepareControlForExport(gv.HeaderRow) table.Rows.Add(gv.HeaderRow) End If For Each row As GridViewRow In gv.Rows PrepareControlForExport(row) table.Rows.Add(row) Next If (Not (gv.FooterRow) Is Nothing) Then PrepareControlForExport(gv.FooterRow) table.Rows.Add(gv.FooterRow) End If table.RenderControl(htw) HttpContext.Current.Response.Write(sw.ToString) HttpContext.Current.Response.End() End Sub Private Sub PrepareControlForExport(ByVal control As Control) Dim i As Integer = 0 Do While (i < control.Controls.Count) Dim current As Control = control.Controls(i) If (TypeOf current Is LinkButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text)) ElseIf (TypeOf current Is ImageButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText)) ElseIf (TypeOf current Is HyperLink) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text)) ElseIf (TypeOf current Is DropDownList) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text)) ElseIf (TypeOf current Is CheckBox) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked)) End If If current.HasControls Then PrepareControlForExport(current) End If i = i + 1 Loop End Sub A: Just avoid COM Interop via Microsoft.Office.Interop namespace. It is so damn slow and unreliable and unscalable. Not applicable for masochists. A: You can create nicely formatted Excel files using this library, quite easily: http://officehelper.codeplex.com/documentation. Microsoft Office does not need to be installed on the webserver! A: I would just create a CSV file based on the data, because I see that as the cleanest, and Excel has good support for it. But if you require a more flexible format, I'm sure there's some 3rd party tools for generating real excel files. A: CSV is easiest way. Most of the time it is linked to Excel. Otherwise you have to use the automation APIs or XML format. The APIs and XML are not that hard to use. Information about generating XML for Excel A: I either go the CSV route (as described above), or more often these days, I use Infragistics NetAdvantage to generate the file. (The very vast majority of the time where Infragistics is in play, we're just exporting an existing UltraWebGrid, which is essentially a one-LOC solution unless extra formatting tweaks are needed. We could manually generate an Excel/BIFF file as well, but there's rarely a need to.) A: man, in .net i guess you could have a component that could do that, but in classic asp I have already done it creating an html table and changing the mime tipe of the page to vnd/msexcel. I guess that if you use a gridview and change the mime type maybe it should work, because the gridview is an html table. A: The only bulletproof way of avoiding the "It looks like these numbers are stored as text" green triangles is to use the Open XML format. It is worth using it, just to avoid the inevitable green triangles. A: The best method i've seen for excel reports is to write out the data in XML with a XML extension and stream it to clients with the correct content type. (application/xls) This works for any report which requires basic formating, and allows you to compare against existing spreadsheets by using text comparison tools. A: Assuming this is for an intranet, where you can set permissions and mandate IE, you can generate the workbook client side with JScript/VBScript driving Excel. This gives you native Excel formatting, without the hassle of trying to automate Excel on the server. I'm not sure I'd really recommend this approach anymore except in fairly niche scenarios, but it was fairly common during the classic ASP heydays. A: You can of course always go for a third party components. Personally, I have had a good experience with Spire.XLS http://www.e-iceblue.com/xls/xlsintro.htm The component is pretty easy to use within your application: Workbook workbook = new Workbook(); //Load workbook from disk. workbook.LoadFromFile(@"Data\EditSheetSample.xls"); //Initailize worksheet Worksheet sheet = workbook.Worksheets[0]; //Writes string sheet.Range["B1"].Text = "Hello,World!"; //Writes number sheet.Range["B2"].NumberValue = 1234.5678; //Writes date sheet.Range["B3"].DateTimeValue = System.DateTime.Now; //Writes formula sheet.Range["B4"].Formula = "=1111*11111"; workbook.SaveToFile("Sample.xls"); A: One of the problems I've ran across using one of the solutions suggested above which are similar to this answer is that if you push the content out as an attachment (what I've found to be the cleanest solution for non-ms browsers), then open it in Excel 2000-2003, its type is an "Excel Web Page" and not a native Excel document. Then you have to explain to users how to use "Save as type" from within Excel to convert it to an Excel document. This is a pain if users need to edit this document and then re-upload it to your site. My recommendation is to use CSV. It's simple and if users do open it from within Excel, Excel at least prompts them to save it in its native format. A: Here's a solution the streams the datatable out as a CSV. Fast, clean, and easy, and it handles commas in the input. public static void ExportToExcel(DataTable data, HttpResponse response, string fileName) { response.Charset = "utf-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); for (int i = 0; i < data.Columns.Count; i++) { response.Write(data.Columns[i].ColumnName); response.Write(i == data.Columns.Count - 1 ? "\n" : ","); } foreach (DataRow row in data.Rows) { for (int i = 0; i < data.Columns.Count; i++) { response.Write(String.Format("\"{0}\"", row[i].ToString())); response.Write(i == data.Columns.Count - 1 ? "\n" : ","); } } response.End(); } A: If you have to use Excel instead of a CSV file you will need to use OLE automation on an Excel instance one the server. The easiest way to do this is to have a template file and programatically fill it in with the data. You save it to another file. Tips: * *Don't do it interactively. Have the user kick off the process and then post a page with the link to the file. This mitigates potential performance issues while the spreadsheet is generated. *Use the template as I described before. It makes it easier to modify it. *Make sure that Excel is set to not pop up dialogs. On a web server this will hang the whole excel instance. *Keep the Excel instance on a separate server, preferably behind a firewall, so it is not exposed as a potential security hole. *Keep an eye on resource usage. Generating a spreadhseet over the OLE automation interface (the PIA's are just shims over this) is a fairly heavyweight process. If you need to scale this to high data volumes you may need to be somewhat clever with your architecture. Some of the 'use mime-types to trick excel into opening HTML table' approaches would work if you don't mind the format of the file being a bit basic. These approaches also fob the CPU heavy work off onto the client. If you want fine-graned control over the format of the spreadsheet you will probably have to use Excel itself to generate the file as described above. A: just created a function to export from a web form C# to excel hope it helps others public void ExportFileFromSPData(string filename, DataTable dt) { HttpResponse response = HttpContext.Current.Response; //clean up the response.object response.Clear(); response.Buffer = true; response.Charset = ""; // set the response mime type for html so you can see what are you printing //response.ContentType = "text/html"; //response.AddHeader("Content-Disposition", "attachment;filename=test.html"); // set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); response.ContentEncoding = System.Text.Encoding.UTF8; response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble()); //style to format numbers to string string style = @"<style> .text { mso-number-format:\@; } </style>"; response.Write(style); // create a string writer using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // instantiate a datagrid GridView dg = new GridView(); dg.DataSource = dt; dg.DataBind(); foreach (GridViewRow datarow in dg.Rows) { //format specific cell to be text //to avoid 1.232323+E29 to get 1232312312312312124124 datarow.Cells[0].Attributes.Add("class", "text"); } dg.RenderControl(htw); response.Write(sw.ToString()); response.End(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/150339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "100" }
Q: TDD and Mocking out TcpClient How do people approach mocking out TcpClient (or things like TcpClient)? I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this? A: I think @Hitchhiker is on the right track, but I also like to think about abstracting out things like that just a step further. I wouldn't mock out the TcpClient directly, because that would still tie you too closely to the underlying implementation even though you've written tests. That is, your implementation is tied to a TcpClient method specifically. Personally, I would try something like this: [Test] public void TestInput(){ NetworkInputSource mockInput = mocks.CreateMock<NetworkInputSource>(); Consumer c = new Consumer(mockInput); c.ReadAll(); // c.Read(); // c.ReadLine(); } public class TcpClientAdapter : NetworkInputSource { private TcpClient _client; public string ReadAll() { return new StreamReader(_tcpClient.GetStream()).ReadToEnd(); } public string Read() { ... } public string ReadLine() { ... } } public interface NetworkInputSource { public string ReadAll(); public string Read(); public string ReadLine(); } This implementation will decouple you from Tcp related details altogether (if that is a design goal), and you can even pipe in test input from a hard coded set of values, or a test input file. Very hand if you are on the road to testing your code for the long haul. A: When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the Adapter design pattern. In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this: public interface ITcpClient { Stream GetStream(); // Anything you need here } public class TcpClientAdapter: ITcpClient { private TcpClient wrappedClient; public TcpClientAdapter(TcpClient client) { wrappedClient = client; } public Stream GetStream() { return wrappedClient.GetStream(); } } A: Using the Adapter pattern is most definitely the standard TDD approach to the problem. You could, however, also just create the other end of the TCP connection and have your test harness drive that. IMO the widespread use of adapter class obfuscates the most important parts of a design, and also tends to remove a lot of stuff from being tested that really ought to be tested in context. So the alternative is to build up your testing scaffolding to include more of the system under test. If you are building your tests from the ground up, you'll still achieve the ability to isolate the cause of a failure to a given class or function, it just won't be in isolation...
{ "language": "en", "url": "https://stackoverflow.com/questions/150341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Programmatically find the number of cores on a machine Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)? A: Windows (x64 and Win32) and C++11 The number of groups of logical processors sharing a single processor core. (Using GetLogicalProcessorInformationEx, see GetLogicalProcessorInformation as well) size_t NumberOfPhysicalCores() noexcept { DWORD length = 0; const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length); assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER); std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]); const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get()); const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length); assert(result_second != FALSE); size_t nb_physical_cores = 0; size_t offset = 0; do { const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info = reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset); offset += current_info->Size; ++nb_physical_cores; } while (offset < length); return nb_physical_cores; } Note that the implementation of NumberOfPhysicalCores is IMHO far from trivial (i.e. "use GetLogicalProcessorInformation or GetLogicalProcessorInformationEx"). Instead it is rather subtle if one reads the documentation (explicitly present for GetLogicalProcessorInformation and implicitly present for GetLogicalProcessorInformationEx) at MSDN. The number of logical processors. (Using GetSystemInfo) size_t NumberOfSystemCores() noexcept { SYSTEM_INFO system_info; ZeroMemory(&system_info, sizeof(system_info)); GetSystemInfo(&system_info); return static_cast< size_t >(system_info.dwNumberOfProcessors); } Note that both methods can easily be converted to C/C++98/C++03. A: C++11 #include <thread> //may return 0 when not able to detect const auto processor_count = std::thread::hardware_concurrency(); Reference: std::thread::hardware_concurrency In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines): * *Win32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors; *Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards) int numCPU = sysconf(_SC_NPROCESSORS_ONLN); *FreeBSD, MacOS X, NetBSD, OpenBSD, etc. int mib[4]; int numCPU; std::size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */ mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) numCPU = 1; } *HPUX int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL); *IRIX int numCPU = sysconf(_SC_NPROC_ONLN); *Objective-C (Mac OS X >=10.5 or iOS) NSUInteger a = [[NSProcessInfo processInfo] processorCount]; NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount]; A: One more Windows recipe: use system-wide environment variable NUMBER_OF_PROCESSORS: printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS"))); A: You probably won't be able to get it in a platform independent way. Windows you get number of processors. Win32 System Information A: OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a int omp_get_num_procs(); function that returns the number of processors/cores available at the time of call. A: Unrelated to C++, but on Linux I usually do: grep processor /proc/cpuinfo | wc -l Handy for scripting languages like bash/perl/python/ruby. A: More on OS X: sysconf(_SC_NPROCESSORS_ONLN) is available only versions >= 10.5, not 10.4. An alternative is the HW_AVAILCPU/sysctl() BSD code which is available on versions >= 10.2. A: If you have assembly-language access, you can use the CPUID instruction to get all sorts of information about the CPU. It's portable between operating systems, though you'll need to use manufacturer-specific information to determine how to find the number of cores. Here's a document that describes how to do it on Intel chips, and page 11 of this one describes the AMD specification. A: Windows Server 2003 and later lets you leverage the GetLogicalProcessorInformation function http://msdn.microsoft.com/en-us/library/ms683194.aspx A: (Almost) Platform Independent function in c-code #ifdef _WIN32 #include <windows.h> #elif MACOS #include <sys/param.h> #include <sys/sysctl.h> #else #include <unistd.h> #endif int getNumCores() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #elif MACOS int nm[2]; size_t len = 4; uint32_t count; nm[0] = CTL_HW; nm[1] = HW_AVAILCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { nm[1] = HW_NCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { count = 1; } } return count; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } A: On linux the best programmatic way as far as I know is to use sysconf(_SC_NPROCESSORS_CONF) or sysconf(_SC_NPROCESSORS_ONLN) These aren't standard, but are in my man page for Linux. A: hwloc (http://www.open-mpi.org/projects/hwloc/) is worth looking at. Though requires another library integration into your code but it can provide all the information about your processor (number of cores, the topology, etc.) A: On Linux, it's may not be safe to to use _SC_NPROCESSORS_ONLN as it's not part of POSIX standard and the sysconf manual states as much. So there's a possibility that _SC_NPROCESSORS_ONLN may not be present: These values also exist, but may not be standard. [...] - _SC_NPROCESSORS_CONF The number of processors configured. - _SC_NPROCESSORS_ONLN The number of processors currently online (available). A simple approach would be to read /proc/stat or /proc/cpuinfo and count them: #include<unistd.h> #include<stdio.h> int main(void) { char str[256]; int procCount = -1; // to offset for the first entry FILE *fp; if( (fp = fopen("/proc/stat", "r")) ) { while(fgets(str, sizeof str, fp)) if( !memcmp(str, "cpu", 3) ) procCount++; } if ( procCount == -1) { printf("Unable to get proc count. Defaulting to 2"); procCount=2; } printf("Proc Count:%d\n", procCount); return 0; } Using /proc/cpuinfo: #include<unistd.h> #include<stdio.h> int main(void) { char str[256]; int procCount = 0; FILE *fp; if( (fp = fopen("/proc/cpuinfo", "r")) ) { while(fgets(str, sizeof str, fp)) if( !memcmp(str, "processor", 9) ) procCount++; } if ( !procCount ) { printf("Unable to get proc count. Defaulting to 2"); procCount=2; } printf("Proc Count:%d\n", procCount); return 0; } The same approach in shell using grep: grep -c ^processor /proc/cpuinfo Or grep -c ^cpu /proc/stat # subtract 1 from the result A: This functionality is part of the C++11 standard. #include <thread> unsigned int nthreads = std::thread::hardware_concurrency(); For older compilers, you can use the Boost.Thread library. #include <boost/thread.hpp> unsigned int nthreads = boost::thread::hardware_concurrency(); In either case, hardware_concurrency() returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units. A: OS X alternative: The solution described earlier based on [[NSProcessInfo processInfo] processorCount] is only available on OS X 10.5.0, according to the docs. For earlier versions of OS X, use the Carbon function MPProcessors(). If you're a Cocoa programmer, don't be freaked out by the fact that this is Carbon. You just need to need to add the Carbon framework to your Xcode project and MPProcessors() will be available. A: For Win32: While GetSystemInfo() gets you the number of logical processors, use GetLogicalProcessorInformationEx() to get the number of physical processors. A: On Linux, you can read the /proc/cpuinfo file and count the cores. A: Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few. The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast... A: #include <stdint.h> #if defined(__APPLE__) || defined(__FreeBSD__) #include <sys/sysctl.h> uint32_t num_physical_cores(void) { uint32_t num_cores = 0; size_t num_cores_len = sizeof(num_cores); sysctlbyname("hw.physicalcpu", &num_cores, &num_cores_len, 0, 0); return num_cores; } #elif defined(__linux__) #include <unistd.h> #include <stdio.h> uint32_t num_physical_cores(void) { uint32_t lcores = 0, tsibs = 0; char buff[32]; char path[64]; for (lcores = 0;;lcores++) { FILE *cpu; snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u/topology/thread_siblings_list", lcores); cpu = fopen(path, "r"); if (!cpu) break; while (fscanf(cpu, "%[0-9]", buff)) { tsibs++; if (fgetc(cpu) != ',') break; } fclose(cpu); } return lcores / (tsibs / lcores); } #else #error Unrecognized operating system #endif This should return the number of physical cores on the system. This is different than the number of logical cores which most of these answers provide. If you're looking to size a thread pool which performs no blocking I/O, and doesn't sleep, then you want to use the number of physical cores, not the number of logical (hyper threading) cores. This answer only provides implementations for Linux and the BSDs. A: you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.
{ "language": "en", "url": "https://stackoverflow.com/questions/150355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "542" }
Q: What do I use for ChangeKey in EWS UpdateItem? I'm trying to use Exchange Web Services to update a calendar item. I'm creating an ItemChangeType, and then an ItemIdType. I have a unique ID to use for ItemIdType.Id, but I have nothing to use for the ChangeKey. When I leave it out, I get an ErrorChangeKeyRequiredForWriteOperations. But when i try to just put something in there, I get an ErrorInvalidChangeKey. What can I use for this to get it to work? I'm also trying to determine what is the best implementation of BaseItemIdType to use for ItemChangeType.Item. So far, I'm using ItemIdType, and I'm guessing that's correct, but I haven't been able to find any particularly helpful documentation on this. A: To be a bit more explicit on Hauge's answer: the ChangeKey is stored in Exchange and identifies the current state of the item. Any change to that item creates a new ChangeKey. This allows Exchange to "know" that your update is being applied to the same item state as when you looked at the item - it hasn't changed since you checked it. Some code available at: http://msdn.microsoft.com/en-us/library/aa563020.aspx A: If you have the ItemIdType.Id property you should also have access to the Changekey, it's also a property of ItemIdType: ItemIdType.ChangeKey Like the Id property it's a string, so you can grab it when you grab the Id. Regards Jesper Hauge A: If you know ID only, you can get ChangeKey easily, for example for folder: private FolderIdType GetFullFolderID(string folderID) { GetFolderType request = new GetFolderType(); request.FolderIds = new BaseFolderIdType[1]; FolderIdType id = new FolderIdType(); id.Id = folderID; request.FolderIds[0] = id; request.FolderShape = new FolderResponseShapeType(); request.FolderShape.BaseShape = DefaultShapeNamesType.IdOnly; GetFolderResponseType response = _binding.GetFolder(request); FailOnError(response); FolderInfoResponseMessageType firmt = (FolderInfoResponseMessageType)response.ResponseMessages.Items[0]; FolderType ft = (FolderType)firmt.Folders[0]; id.ChangeKey = ft.FolderId.ChangeKey; return id; } A: I recommend you to use the Exchange Managed API, instead of Exchange Web Services, for working with Exchange. It is much easier to use. You can find more details below: https://msdn.microsoft.com/en-gb/library/dd877012(v=exchg.150).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/150359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you break into the debugger from Python source code? What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? A: import pdb; pdb.set_trace() See Python: Coding in the Debugger for Beginners for this and more helpful hints. A: As of Python 3.7, you can use breakpoint() - https://docs.python.org/3/library/functions.html#breakpoint
{ "language": "en", "url": "https://stackoverflow.com/questions/150375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Text that only exists if CSS is enabled I have a website in which I provide tool-tips for certain things using a hidden <span> tag and JavaScript to track various mouse events. It works excellently. This site somewhat caters towards people with vision issues, so I try to make things degrade as well as possible if there is no JavaScript or CSS and generally I would say that it is successful in this regard. So my question is, is it possible for these <span> to only exist if CSS is being used? I have thought about writing out the tool-tips in JavaScript on document load. But I was wondering if there is a better solution. A: Perhaps you need to re-think the way you are providing tooltips. Could the content be contained in the title attribute of a semantically appropriate element? EDIT: If you provide more info, someone might be able to suggest more of a solution. What sorts of elements are the tooltips popping up on? Images? Would the abbreviation tags be appropriate? Quick Solution I just came up with: <span> has access to the core attributes, which include title, so you could include the tooltip text in the title, and use a javascript library like jQuery to display tooltips for all spans with a title. A: A quick hack would be to color the text the same as the background (say, white on white) in html, and then use CSS to change the color back to something visible (black on white). Of course, this is only relevant for people able to see the text. Screen readers and such wouldn't see the text as hidden. A: CSS is also used by screenreaders to help define which page elements are read or not. Screen readers will almost always ignore elements with display:none applied to them, so not using CSS is not a valid indicator of a screenreader's presence. I would go with Chris' idea of using javascript to generate the tooltips based on a title (or alt) attribute. You could use JS to ensure that tooltips are only displayed when valid styles are set, so if JS is enabled and CSS disabled you can treat the extra information differently (eg footnotes). http://juicystudio.com/article/screen-readers-display-none.php http://www.456bereastreet.com/archive/200711/screen_readers_sometimes_ignore_displaynone/
{ "language": "en", "url": "https://stackoverflow.com/questions/150384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .NET File Sync Library Is there a good .NET file syncing library? It can be pretty basic and only needs to work on local and mapped drives (no server client model like rsync is needed). And yes, I know there is the MS Sync Services, but that is a lot more than what I need. A: There is also Microsoft's Sync Framework. SyncToy is actually using the sync framework to implement it's functionality. Here are some of the APIs: * *Microsoft.Synchronization *Microsoft.Synchronization.Files A: Can you put something together yourself based on the FileSystemWatcher component, or are you looking for something more complete? A: Microsoft's SyncToy tool installs an API that you can call from your code, according to the article at: http://www.codeproject.com/KB/vb/SyncToy_Helper.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/150397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Desktop Applications: Architectural Frameworks? I'm wondering if there are any architectural frameworks out there to create desktop or standalone applications, in Java or C# for instance. It seems that there are tons of them available for web applications but I can't find many good resources on frameworks or architectural best-practices for desktop development. Ideally I would like to know if there is any source code available of desktop applications that would be considered to have a good architecture or are built with a certain framework. A: While not directly related to desktop applications if you are looking for decent source code for well written projects I asked a similar question: Open source C# projects that have extremely high code quality to learn from. People gave some pretty good suggestions there: * *Scott Hanselman's The Weekly Source Code series (usually managed C#) *Code written by Microsoft Patterns & Practices team. *SharpDevelop (written in C#) *Mono (most of the framework in C#) *Paint.Net (written in C#) *NHibernate (written in C#) *The Castle Project (written in C#) *xUnit (written in C#) *.Net Framework Source Code A: There's a new .NET architectural guidance package from Microsoft patterns & practices for WPF that is code named "Prism" -- it's basically a "next generation" Composite UI Application Block (without the SCSF tooling). It uses Dependency injection, Composite pattern throughout, etc. There is a pretty good DNRTV screencast demoing it. A: In the lightweight app category, JSR 296 for Java (to be in future Java 7 possibly) is a framework handling the basics like resource management and actions. Lots of links here: * *http://tech.puredanger.com/java7#jsr296 Scaling up a bit, you could look at various RCP frameworks like: * *Eclipse RCP: http://wiki.eclipse.org/index.php/Rich_Client_Platform *NetBeans Platform: http://www.netbeans.org/products/platform/ *Spring RCP: http://spring-rich-c.sourceforge.net/1.0.0/index.html *Comparison article: http://www.infoq.com/news/eclipse-rcp-netbeans-platform UPDATE: It has been mentioned (by Mark Reinhold at Devoxx '08) that JSR 296 will be included in Java 7. Further update: JSR 296 is dead. JavaFX is the current direction for client-side Java. A: Check Microsoft's Smart Client Software Factory. It contains code samples and documentation. Overview This software factory provides proven solutions to common challenges found while building and operating composite smart client applications. It helps architects and developers build modular systems that can be built and deployed by independent teams. Applications built with the software factory use proven practices for operations, such as centralized exception logging. The software factory contains a collection of reusable components and libraries, Visual Studio 2008 solution templates, wizards and extensions, How-to topics, automated tests, extensive architecture documentation, patterns, and a reference implementation. The software factory uses Windows Forms, Windows Presentation Foundation, Windows Communication Foundation, and the Enterprise Library 3.1 – May 2007 release. With this release, the Composite UI Application Block is included in the software factory. A: In Java, Naked Objects -- http://nakedobjects.org/home/index.shtml JMatter -- implementation of naked objects -- http://jmatter.org/. pretty good. both of them are open source. A: On the Java side, there are several projects aimed at Rich Client Platforms (RCP is the new buzzword for 'desktop' apps): * *Eclipse RCP (if you are OK using SWT instead of Swing) *Spring RCP (which is in the process of being overhauled into Spring Desktop) *NetBeans RCP (which I'm not particularly impressed with, but that is getting some traction) *JSR 296 (Application Framework) - I actually really like this one Google any of the above and you'll get tons of info. A: You can use some of the same approaches in client development that you use in web development, such as Model View Presenter. The System.Windows.Forms namespace has everything you need to build a client application in C#, with the rest of the .NET Framework available to provide the services you need (such as IO and remoting). As far as source code for solid architectures in desktop apps, look at the code for Paint.NET and SharpDevelop. Both have very different approaches that will be interesting to you. Sorry for the .NET slant of this reply. It's what I know best. :) A: I would recommend CSLA .NET framework by Rockford Lhotka: http://www.lhotka.net/cslanet/Default.aspx It comes will full source code as well as sample client applications built in ASP.NET, WinForms and WPF. A: I just found the Composite Application Guidance for WPF and Silverlight which looks very interesting. It was published in February 2009. A: We develop in .NET technologies here. Our friends here working on client applications develop their software to the Model View Presenter design pattern that is often associated with Web Development. For them they find it works very well, I believe it may be worth checking out. The Smart Client Factory (mentioned by Panos) may also be useful to you, though it's not a framework but more of a library of best practice solutions to common problems. A: Specifically to organized presentation framework of ui functions we have been using infonode docking windows, that's a windowing framework using an eclipse like appearance (drag views anywhere, close them, undock them etc., skinnable of course). there's a gpl version for open source products out, altough afaik the developer licence is not that expensive ($299 each). A: Check IdeaBlade's Cabana For DotNet C#. http://www.ideablade.com/CAB.html Cabana Sample App The Cabana application is a simple smart client reference app with a crisp, feature-rich user experience that is easy to deploy and operate over the web. Cabana demonstrates: An easy approach to the Composite UI Application Block from Microsoft ’s Patterns & Practices Group. Maintainable, reusable code through UI composition. Separation of Model (business logic and data access) from Presentation. The Model-View-Presenter pattern. Performance tuning. And more. A: I recently published DesktopBootstrap. It's my attempt to factor out many of the common elements of creating medium to large scale desktop apps. You can find it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/150403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: What is the easiest way to read/manipulate query string params using javascript? The examples I've seen online seem much more complex than I expected (manually parsing &/?/= into pairs, using regular expressions, etc). We're using asp.net ajax (don't see anything in their client side reference) and would consider adding jQuery if it would really help. I would think there is a more elegant solution out there - so far this is the best code I've found but I would love to find something more along the lines of the HttpRequest.QueryString object (asp.net server side). Thanks in advance, Shane A: I am using this function in case i don't want to use a plugin: function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] == variable) { return pair[1]; } } return null; } A: Take a look at my post, as it tells you exactly how to do this: http://seattlesoftware.wordpress.com/2008/01/16/javascript-query-string/ A: For jQuery I suggest jQuery BBQ: Back Button & Query Library By "Cowboy" Ben Alman jQuery BBQ leverages the HTML5 hashchange event to allow simple, yet powerful bookmarkable #hash history. In addition, jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods. Example: // Parse URL, deserializing query string into an object. // http://www.example.com/foo.php?a=1&b=2&c=hello#test // search is set to ?a=1&b=2&c=hello // myObj is set to { a:"1", b:"2", c:"hello" } var search = window.location.search; var myObj = $.deparam.querystring( search ); A: There is indeed a QueryString plugin for jQuery, if you're willing to install the jQuery core and the plugin it could prove useful. A: Use the String utility from prototypejs.org, called toQueryParams(). Example from their site: http://prototypejs.org/api/string/toQueryParams 'section=blog&id=45'.toQueryParams(); // -> {section: 'blog', id: '45'} 'section=blog;id=45'.toQueryParams(); // -> {section: 'blog', id: '45'} 'http://www.example.com?section=blog&id=45#comments'.toQueryParams(); // -> {section: 'blog', id: '45'} 'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams(); // -> {section: 'blog', tag: ['javascript', 'prototype', 'doc']} 'tag=ruby%20on%20rails'.toQueryParams(); // -> {tag: 'ruby on rails'} 'id=45&raw'.toQueryParams(); // -> {id: '45', raw: undefined} Also, you may use the alias parseQuery() to obtain the same results. window.location.search.parseQuery(); Since window.location returns an object, you must obtain the string. A: *$(document).ready(function () { $("#a").click(function () { window.location.href = "secondpage.aspx?id='0' & name='sunil'& add='asr' & phone='1234'"; }); });* **then read the query string parameters on another using split method . Here as follows:** *$(document).ready(function () { var a = decodeURI(window.location.search); var id = window.location.search = "id=" + $().val(); var name = a.split("name=")[1].split("&")[0].split("'")[1]; var phone = a.split("phone=")[1].split("&")[0].split("'")[1]; var add = a.split("add=")[1].split("&")[0].split("'")[1]; alert(id+','+name+','+add+','+phone); });* A: If there's any possibility of encountering repeated parameters (e.g. ?tag=foo&tag=bar), most libraries out there won't be sufficient. In that case, you might want to consider this library that I developed from Jan Wolter's very comprehensive parser. I added .plus() and .minus() functions and roundtripping: https://github.com/timmc/js-tools/blob/master/src/QueryString.js
{ "language": "en", "url": "https://stackoverflow.com/questions/150404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Will upgrading Php 5.2.5 to 5.2.6 result in any problems? We're currently running with php 5.2.5. We have now encountered a bug that creates a seg fault. Our first idea at the solution is upgrading to version 5.2.6 but are skeptical of problems that it will create. We are running Apache and host a dozen or so sites. * *Will any existing code break? *Are there any significant changes to be aware of. I was reading the change log but didn't notice any. *Is it easy to revert back to 5.2.5 if something goes wrong? *Anything else to be aware of? A: With modern Virtual Machine options VMware Server, Microsft Virtual Server, Microsoft Virtual PC and others, why not set up a virtual environment running your existing platform, then upgrade and test that? If you are willing to spend money, you can buy tools to do P2V (Physical-to-Virtual) that will take your existing setup and provide you with a virtualized copy of it (this could be valuable if you've done a lot of customization to the configuration that might be difficult to produce to a virtualized version that matches the original well enough to do proper testing). A: Most likely not. The jump from 5.2.5 to 5.2.6 is small, it is a bug-fix release (see the changelog). But whenever upgrading anything, make sure to test your code in a dev environment before putting it into production. A: It's impossible for any of us to say definitely yes or no about your existing code breaking without performing an analysis on it first. This is exactly what test environments are for. If you have a test environment set up, you can perform the upgrade, then do regression testing to see if anything breaks. Without this environment, you're making a gamble. @Grant Wagner: Great point on virtualization. Setting up a good test environment doesn't have to be difficult. A: As everyone is saying, only testing will tell you for sure. However, minor version updates like this will only rarely cause compatibility problems. For what it's worth, here are the change notes. In the long run though, you will have to upgrade at some point or risk being exposed to known security vulnerabilities. A: Thanks for everyone's input. Getting a test server is definitely on the road map. This should be a good argument for finally getting one setup. We're a small enough company where we could easily get away with only having one, but there are so many advantages to having a test server. Unfortunately it will be hard to get this project moving forward without upgrading and i doubt there will be time for a test environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/150405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generating 'neighbours' for users based on rating I'm looking for techniques to generate 'neighbours' (people with similar taste) for users on a site I am working on; something similar to the way last.fm works. Currently, I have a compatibilty function for users which could come into play. It ranks users on having 1) rated similar items 2) rated the item similarly. The function weighs point 2 heigher and this would be the most important if I had to use only one of these factors when generating 'neighbours'. One idea I had would be to just calculate the compatibilty of every combination of users and selecting the highest rated users to be the neighbours for the user. The downside of this is that as the number of users go up then this process couls take a very long time. For just a 1000 users, it needs 1000C2 (0.5 * 1000 * 999 = = 499 500) calls to the compatibility function which could be very heavy on the server also. So I am looking for any advice, links to articles etc on how best to achieve a system like this. A: In the book Programming Collective Intelligence http://oreilly.com/catalog/9780596529321 Chapter 2 "Making Recommendations" does a really good job of outlining methods of recommending items to people based on similarities between users. You could use the similarity algorithms to find the 'neighbours' you are looking for. The chapter is available on google book search here: http://books.google.com/books?id=fEsZ3Ey-Hq4C&printsec=frontcover A: Be sure to look at Collaborative Filtering. Many recommendation systems use collaborative filtering to suggest items to users. They do it by finding 'neighbors' and then suggesting items your neighbors rated highly but you haven't rated. You could go as far as finding neighbors, and who knows, maybe you'll want recommendations in the future. GroupLens is a research lab at the University of Minnesota that studies collaborative filtering techniques. They have a ton of published research as well as a few sample datasets. The Netflix Prize is a competition to determine who can most effectively solve this sort of problem. Follow the links off their LeaderBoard. A few of the competitors share their solutions. As far as a computationally inexpensive solution, you could try this: * *Create categories for your items. If we're talking about music, they might be classical, rock, jazz, hip-hop... or go further: Grindcore, Math Rock, Riot Grrrl... *Now, every time a user rates an item, roll up their ratings at the category level. So you know 'User A' likes Honky Tonk and Acid House because they give those items high ratings frequently. Frequency and strength is probably important for your category aggregate score. *When it's time to find neighbors, instead of cruising through all ratings, just look for similar scores in the categories. This method wouldn't be as accurate but it's fast. Cheers. A: What you need is a clustering algorithm, which would automatically group similar users together. The first difficulty that you are facing is that most clustering algorithms expect the items they cluster to be represented as points in a Euclidean space. In your case, you don't have the coordinates of the points. Instead, you can compute the value of the "similarity" function between pairs of them. One good possibility here is to use spectral clustering, which needs precisely what you have: a similarity matrix. The downside is that you still need to compute your compatibility function for every pair of points, i. e. the algorithm is O(n^2). If you absolutely need an algorithm faster than O(n^2), then you can try an approach called dissimilarity spaces. The idea is very simple. You invert your compatibility function (e. g. by taking its reciprocal) to turn it into a measure of dissimilarity or distance. Then you compare every item (user, in your case) to a set of prototype items, and treat the resulting distances as coordinates in a space. For instance, if you have 100 prototypes, then each user would be represented by a vector of 100 elements, i. e. by a point in 100-dimensional space. Then you can use any standard clustering algorithm, such as K-means. The question now is how do you choose the prototypes, and how many do you need. Various heuristics have been tried, however, here is a dissertation which argues that choosing prototypes randomly may be sufficient. It shows experiments in which using 100 or 200 randomly selected prototypes produced good results. In your case if you have 1000 users, and you choose 200 of them to be prototypes, then you would need to evaluate your compatibility function 200,000 times, which is an improvement of a factor of 2.5 over comparing every pair. The real advantage, though, is that for 1,000,000 users 200 prototypes would still be sufficient, and you would need to make 200,000,000 comparisons, rather than 500,000,000,000 an improvement of a factor of 2500. What you get is O(n) algorithm, which is better than O(n^2), despite a potentially large constant factor. A: The problem seems like to be 'classification problems'. Yes there are so many solutions and approaches. To start exploration check this: http://en.wikipedia.org/wiki/Statistical_classification A: Have you heard of kohonen networks? Its a self organing learning algorithm that clusters similar variables into similar slots. Although most sites like the one I link you to displays the net as bidimensional there is little involved in extending the algorithm into a multiple dimension hypercube. With such a data structure finding and storing neighbours with similar tastes is trivial as similar users should be stores into similar locations (almost like a reverse hash code). This reduces your problem into one of finding the variables that will define similarity and establishing distances between possible enumerate values ,like for example classical and acoustic are close toghether while death metal and reggae are quite distant (at least in my oppinion) By the way in order to find good dividing variables the best algorithm is a decision tree. The nodes closer to the root will be the most important variables to establish 'closeness'. A: It looks like you need to read about clustering algorithms. The general idea is that instead of comparing every point with every other point each time you divide them in clusters of similar points. Then the neighborhood may be all the points in the same cluster. The number/size of the clusters is usually a parameter of the clustering algorithm. Yo can find a video about clustering in Google's series about cluster computing and mapreduce. A: Concerns over performance can be greatly mitigated if you consider this as a build/batch problem rather than a realtime query. The graph can be statically computed then latently updated e.g. hourly, daily etc. to then generate edges and storage optimized for runtime query e.g. top 10 similar users for each user. +1 for Programming Collective Intelligence too - it is very informative - wish it wasn't (or I was!) as Python-oriented, but still good.
{ "language": "en", "url": "https://stackoverflow.com/questions/150410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Tracking Globalization progress With our next major release we are looking to globalize our ASP.Net application and I was asked to think of a way to keep track of what code has been already worked on in this effort. My thought was to use a custom Attribute and place it on all classes that have been "fixed". What do you think? Does anyone have a better idea? A: Using an attribute to determine which classes have been globalized would then require a tool to process the code and determine which classes have and haven't been "processed", it seems like it's getting a bit complicated. A more traditional project tracking process would probably be better - and wouldn't "pollute" your code with attributes/other markup that have no functional meaning beyond the end of the globalisation project. How about having a defect raised for each class that requires work, and tracking it that way? A: What about just counting or listing the classes and then work class by class? While an attribute may be an interesting idea, I'd regard it as over-engineered. Globalizing does nothing more than, well, going through each class and globalizing the code :) You want to finish that anyway before the next release. So go ahead and just do it one by one, and there you have your progress. I'd regard a defect raised for each class as too much either. In my last project, I started full globalization a little late. I just went through the list of code files, from top to bottom. Alphabetically in my case, and folder after folder. So I always only had to remember which file I last worked on. That worked pretty well for me. Edit: Another thing: In my last project, globalizing mainly involved moving hard-coded strings to resource files, and re-generating all text when the language changes at runtime. But you'll also have to think about things like number formats and the like. Microsoft's FxCop helped me with that, since it marks all number conversions etc. without specifying a culture as violations. FxCop keeps track of this, so when you resolved such a violation and re-ran FxCop, it would report the violation as missing (i.e. solved). That's especially useful for these harder-to-see things. A: How about writing a unit test for each page in the app? The unit test would load the page and perform a foreach (System.Web.UI.Control c in Page.Controls) { //Do work here } For the work part, load different globalization settings and see if the .Text property (or relevant property for your app) is different. My assumption would be that no language should come out the same in all but the simplest cases. Use the set of unit tests that sucessfully complete to track your progress.
{ "language": "en", "url": "https://stackoverflow.com/questions/150416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the accepted way of storing quoted data in XML? What's the accepted way of storing quoted data in XML? For example, for a node, which is correct? * *(a) <name>Jesse "The Body" Ventura</name> *(b) <name>Jesse \"The Body\" Ventura</name> *(c) <name>Jesse &quot;The Body&quot; Ventura</name> *(d) none of the above (please specify) If (a), what do you do for attributes? If (c), is it really appropriate to mix HTML & XML? Similarly, how do you handle single and curly quotes? A: Double quotes in text nodes can be represented either as the double-quote character or as the &quot; entity. Double quotes in attribute values can be represented as the double-quote character if the value is delimited by single quotes, and vice versa; otherwise, escape them as &quot; This is only relevant if you're a) editing XML in a non-XML-aware text editor or b) creating XML programmatically through string manipulation. Generally speaking, you should avoid (a) unless you really know what you're doing, or at least have a way of checking the well-formedness of your XML after editing is complete. And you should avoid (b) under all circumstances. Never create XML through string manipulation; always use a DOM or some other tool. A: You shouldn't worry about how things are encoded in your XML. You should always use a proper library for generating XML documents. There's too many gotcha's to XML to get it right by yourself. I've seen tons of invalid XML documents come my way because somebody thought they could generate proper XML themselves, without using a library. All major programming languages in use today have XML libraries. A: For example, for a node, which is correct? The XML specification itself doesn't talk about nodes (other than when comparing DTD syntax to finite automaton regex). A DOM node can be attribute, element, text or any of the other node types. Inside a text node, you only need to escape characters which the parser would interpret as starting a different node - so you escape & and < as &amp; and &lt; . For portability, it's often a good idea to escape curly quotes, but there is no reason to escape plain quotes in XML text. Inside an attribute node, you have to escape less-than and ampersand as before, and also whichever quote you used to delimit the attribute. <foo attribute="'ok'" attribute2='"also-ok"' attribute3="&quot;needed&quot;"/> It's usually easier to get in the habit of only using one type and always escaping it. I write quite a bit of XSLT and favour using " outside and ' inside: <xsl:value-of select="person[@name = 'bob']"/> If you get paranoid with the escaping, the XPath becomes less readable: <xsl:value-of select="person[@name = &apos;bob&apos;"/> If (c), is it really appropriate to mix HTML & XML? XML defines the named entities amp, gt, lt, apos, & quot HTML defines many more entities. You can and should use the XML named entities in XML in preference of using a numeric entity. The lt entity escapes < and should be used in text and attribute values. The amp entity escapes & and should be used in text and attribute values. The apos and quot entities escape ' and " and should be used in attribute values. The gt entity is a bit useless - there is almost never a syntactic requirement to escape > in XML. Maybe > only agreed to work with < if it got equal billing. The other one I use a lot in XSLT that generates source code is &#xa; which inserts a new line. &nl; would have been more use than &gt; Similarly, how do you handle single and curly quotes? XML is designed to mark up Unicode text, and the curly quotes have no special meaning in it. However, it's not uncommon for the encoding used for and XML document to be misinterpreted in the wild. So if it's in a closed environment and can guarantee correct Unicode encoding at producer and consumer then I'd just put it in the XML. Otherwise use a numeric character entity. That's true of any character with a code-point above 127 - there's nothing special about curly quotes. A: Your correct answer is A & C as the " is not a character that must be encoded in element data. You should always be XML encoding characters such as >, <, and & to ensure that you don't have issues if they are NOT inside a CDATA section. These are key items to be concerned about for element data. When talking about attributes you have to then also be careful of ' and " inside attribute values depending on the type of symbol you use to surround the value. I've found that often encoding " and ' is a better idea in all aspects as it helps at times when converting to other formats, where the " or ' might cause problems there as well. A: Character data inside XML elements can contain quote characters without escaping them. The only characters that are not permitted inside an XML element are '<', '&' and '>' (and the '>' character is only disallowed if it's part of a "]]>" sequence of characters. That's not to say that escaping the quotes is not a good idea - I'm just saying that not escaping the quotes is perfectly valid XML. See section 2.4 - "Character Data and Markup" in the XML spec. So both (a) and (c) are OK. As far as attributes are concerned, attribute values can be enclosed in either single or double quotes, so if it contains one or the other you can use the opposite one to enclose the value. If it'll contain both, then you'll have to use a character entity for one or both. As far as 'curly-quotes' are concerned, if you're talking about the special, non-ASCII quotes that Word sometimes converts quotes to - they have no special meaning in XML, so you can do whichever (but they can't be used to enclose attribute values". You'll also need to make sure the character encoding for the document is correct, so they are interpreted correctly. A: The correct answer is 'C'. Single quotes don't really cause a problem, but you need to be careful of ampersands and left angle brackets. A: It depends really. If all you want to do is have quotes in your XML string, then 'A'. But if there is meaning or you need to abstract the quote (i18n for example), XML affords richer options. For example: <name> <given>Jesse</given> <family>Ventura</family> <nickName>the Body</nickName> </name> Overkill in many situations. But if you need to correctly handle many of the world's varied - and frequently inconsistent - naming schemes, I'd think about encoding your names along these lines. XML is great for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/150423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Retrieve NTLM Active Directory user data to Rails w/o IIS I believe that we can allow Firefox to sent NTLM data to SharePoint sites to do automatic authentication, and I think that this is doable with IIS. I'd like to do the same thing with an internal Rails site. Does anyone know of way that I could authenticate NTLM type user information through a Apache/mongrel setup (provided of course that it's already running on a Windows box inside of an Active Directory domain)? A: Bit of extra info in case anyone stumbles across this. I wanted to do something which I thought should be pretty simple - extract the users windows username using NTLM from a Rails app running on Mongrel/Windows (InstantRails actually). Having written the basic code manage the various handshaking operations (using the great NTLMRuby library at http://rubyforge.org/projects/rubyntlm/) and having got it to work wonderfully in Firefox I was somewhat frustrated to find IE not working. Mongrel doesn't support keep-alives during the type1/2/3 message exchange (at least natively, I believe there's a hack/fix for it), which IE demands and Firefox gets by without. So authenticating a Rails server running on Windows against a remote NTLM service (e.g. Sharepoint or another web site) is reasonably straight forward, but authenticating an IE browser against a Rails server running on Windows not so much with Mongrel. IIS would be an option, as might be basic Apache with FastCGI. The former feels a bit clunky and the latter won't be as fast as Mongrel. A: I'm assuming you've already worked out which HTTP headers you need to send in order to get firefox and IE to send back the NTLM authentication stuff, and are just needing to handle that on the server side? You could use some of ruby's win32 libraries to access the underlying windows authentication functions which handle the NTLM. I'd suggest the path of least resistance might be to see if there is a COM component which can do the authentication for you, and if so, to use it using the Win32OLE ruby library. If there's no COM component, you might be able to find something in one of those other libraries which can invoke the native win32 methods for you. If you can't find that, you'd have to write a ruby C extension. I've done this on linux, and extending ruby is pretty easy, but you may find the microsoft authentication API's a bit painful. Hope that gets you started on the right track :-) A: You could also use the Apache ntlm module, which should pass a header onwards to your application with the username of the authenticated user. That module looks a bit old, but suggests some other modules that may suit your needs. A: Old question I know but I came across this looking for a similar answer. you could use the methods described here (http://blog.rayapps.com/2008/12/02/ntlm-windows-domain-authentication-for-rails-application/). However mod_ntlm is for windows authentication on a UNIX/linux machine. mod_auth_sspi is what you'll need for winNT authentication from apache under windows. A: This particular project looks promising and is looking for contributors: * *Rack middleware for transparent authentication with NTLM. I haven't yet tried this out. For the moment I plan on implementing Raimonds' solution as it appears to have a lot of success. A: I created tutorial on how to install patched mod_ntlm module for Apache on Linux and how to pass NTLM authenticated username to Rails and how create Rails session from that. So as a result you do not need Windows server for running Rails application. There you can find also how to enable automatic NTLM authentication in Firefox — enter "about:config" in location field and then search for "network.automatic-ntlm-auth.trusted-uris". There you can enter servers for which you would like to use automatic NTLM authentication. A: Check out Waffle. It provides SSO on Windows to Java servers using Win32 API. There're a number of implemented filters (servlet, tomcat valve, spring-security).
{ "language": "en", "url": "https://stackoverflow.com/questions/150429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can a Sequence Diagram realistically capture your logic in the same depth as code? I use UML Sequence Diagrams all the time, and am familiar with the UML2 notation. But I only ever use them to capture the essence of what I intend to do. In other words the diagram always exists at a level of abstraction above the actual code. Every time I use them to try and describe exactly what I intend to do I end up using so much horizontal space and so many alt/loop frames that its not worth the effort. So it may be possible in theory but has anyone every really used the diagram in this level of detail? If so can you provide an example please? A: I have the same problem but when I realize that I am going low-level I re-read this: You should use sequence diagrams when you want to look at the behavior of several objects within a single use case. Sequence diagrams are good at showing collaborations among the objects; they are not so good at precise definition of the behavior. If you want to look at the behavior of a single object across many use cases, use a state diagram. If you want to look at behavior across many use cases or many threads, consider an activity diagram. If you want to explore multiple alternative interactions quickly, you may be better off with CRC cards, as that avoids a lot of drawing and erasing. It’s often handy to have a CRC card session to explore design alternatives and then use sequence diagrams to capture any interactions that you want to refer to later. [excerpt from Martin Fowler's UML Distilled book] A: It's all relative. The law of diminishing returns always applies when making a diagram. I think it's good to show the interaction between objects (objectA initializes objectB and calls method foo on it). But it's not practical to show the internals of a function. In that regard, a sequence diagram is not practical to capture the logic at the same depth as code. I would argue for intricate logic, you'd want to use a flowchart. A: I think there are two issues to consider. Be concrete Sequence diagrams are at their best when they are used to convey to a single concrete scenario (of a use case for example). When you use them to depict more than one scenario, usually to show what happens in every possible path through a use case, they get complicated very quickly. Since source code is just like a use case in this regard (i.e. a general description instead of a specific one), sequence diagrams aren't a good fit. Imagine expanding x levels of the call graph of some method and showing all that information on a single diagram, including all if & loop conditions.. That's why 'capturing the essence' as you put it, is so important. Ideally a sequence diagram fits on a single A4/Letter page, anything larger makes the diagram unwieldy. Perhaps as a rule of thumb, limit the number of objects to 6-10 and the number of calls to 10-25. Focus on communication Sequence diagrams are meant to highlight communication, not internal processing. They're very expressive when it comes to specifying the communication that happens (involved parties, asynchronous, synchronous, immediate, delayed, signal, call, etc.) but not when it comes to internal processing (only actions really) Also, although you can use variables it's far from perfect. The objects at the top are, well, objects. You could consider them as variables (i.e. use their names as variables) but it just isn't very convenient. For example, try depicting the traversal of a linked list where you need to keep tabs on an element and its predecessor with a sequence diagram. You could use two 'variable' objects called 'current' and 'previous' and add the necessary actions to make current=current.next and previous=current but the result is just awkward. A: Personally I have used sequence diagrams only as a description of general interaction between different objects, i.e. as a quick "temporal interaction sketch". When I tried to get more in depth, all quickly started to be confused... I've found that the best compromise is a "simplified" sequence diagram followed by a clear but in depth description of the logic underneath. A: The answer is no - it does capture it better then your source code! At least in some aspects. Let me elaborate. You - like the majority of the programmers, including me - think in source code lines. But the software end product - let's call it the System - is much more than that. It only exists in the mind of your team members. In better cases it also exists on paper or in other documented forms. There are plenty of standard 'views' to describe the System. Like UML Class diagrams, UML activity diagrams etc. Each diagram shows the System from another point of view. You have static views, dynamic views, but in an architectural/software document you don't have to stop there. You can present nonstandard views in your own words, e.g. deployment view, performance view, usability view, company-values view, boss's favourite things view etc. Each view captures and documents certain properties of the System. It's very important to realize that the source code is just one view. The most important though because it's needed to generate a computer program. But it doesn't contain every piece of information of your System, nor explicitly nor implicitly. (E.g. the shared data between program modules, what are only connected via offline user activity. No trace in the source). It's just a static view which helps very little to understand your processes, the runtime dynamics of your living-breathing program. A classic example of the Observer pattern. Especially if it used heavily, you'll hardly understand the System mechanis from the source code. That's why you use Sequence diagrams in that case. It captures the 'dynamic logic' of your system a lot better than your source code. But if you meant some kind of business logic in great detail, you are better off with plain text/source code/pseudocode etc. You don't have to use UML diagrams just because they are the standard. You can use usecase modeling without drawing usecase diagrams. Always choose the view what's the best for you and for your purpose. A: U.M.L. diagrams are guidelines, not strictly rules. You don't have to make them exactly & detailed as the source code, but, you may try it, if you want it. Sometimes, its possible to do it, sometimes, its not possible, because of the detail or complexity of systems, or don't have the time or details to do it. Cheers. P.D. Any cheese-burguer or tuna-fish-burguer for the cat ?
{ "language": "en", "url": "https://stackoverflow.com/questions/150445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I detect when someone shakes an iPhone? I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this? A: First, Kendall's July 10th answer is spot-on. Now ... I wanted to do something similar (in iPhone OS 3.0+), only in my case I wanted it app-wide so I could alert various parts of the app when a shake occurred. Here's what I ended up doing. First, I subclassed UIWindow. This is easy peasy. Create a new class file with an interface such as MotionWindow : UIWindow (feel free to pick your own, natch). Add a method like so: - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) { [[NSNotificationCenter defaultCenter] postNotificationName:@"DeviceShaken" object:self]; } } Change @"DeviceShaken" to the notification name of your choice. Save the file. Now, if you use a MainWindow.xib (stock Xcode template stuff), go in there and change the class of your Window object from UIWindow to MotionWindow or whatever you called it. Save the xib. If you set up UIWindow programmatically, use your new Window class there instead. Now your app is using the specialized UIWindow class. Wherever you want to be told about a shake, sign up for them notifications! Like this: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceShaken) name:@"DeviceShaken" object:nil]; To remove yourself as an observer: [[NSNotificationCenter defaultCenter] removeObserver:self]; I put mine in viewWillAppear: and viewWillDisappear: where View Controllers are concerned. Be sure your response to the shake event knows if it is "already in progress" or not. Otherwise, if the device is shaken twice in succession, you'll have a li'l traffic jam. This way you can ignore other notifications until you're truly done responding to the original notification. Also: You may choose to cue off of motionBegan vs. motionEnded. It's up to you. In my case, the effect always needs to take place after the device is at rest (vs. when it starts shaking), so I use motionEnded. Try both and see which one makes more sense ... or detect/notify for both! One more (curious?) observation here: Notice there's no sign of first responder management in this code. I've only tried this with Table View Controllers so far and everything seems to work quite nicely together! I can't vouch for other scenarios though. Kendall, et. al - can anyone speak to why this might be so for UIWindow subclasses? Is it because the window is at the top of the food chain? A: Check out the GLPaint example. http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html A: Add Following methods in ViewController.m file, its working properly -(BOOL) canBecomeFirstResponder { /* Here, We want our view (not viewcontroller) as first responder to receive shake event message */ return YES; } -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if(event.subtype==UIEventSubtypeMotionShake) { // Code at shake event UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Motion" message:@"Phone Vibrate"delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; [alert release]; [self.view setBackgroundColor:[UIColor redColor]]; } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self becomeFirstResponder]; // View as first responder } A: Sorry to post this as an answer rather than a comment but as you can see I'm new to Stack Overflow and so I'm not yet reputable enough to post comments! Anyway I second @cire about making sure to set the first responder status once the view is part of the view hierarchy. So setting first responder status in your view controllers viewDidLoad method won't work for example. And if you're unsure as to whether it is working [view becomeFirstResponder] returns you a boolean that you can test. Another point: you can use a view controller to capture the shake event if you don't want to create a UIView subclass unnecessarily. I know it's not that much hassle but still the option is there. Just move the code snippets that Kendall put into the UIView subclass into your controller and send the becomeFirstResponder and resignFirstResponder messages to self instead of the UIView subclass. A: First off, I know this is an old post, but it is still relevant, and I found that the two highest voted answers did not detect the shake as early as possible. This is how to do it: * *Link CoreMotion to your project in the target's build phases: *In your ViewController: - (BOOL)canBecomeFirstResponder { return YES; } - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake) { // Shake detected. } } A: Easiest solution is to derive a new root window for your application: @implementation OMGWindow : UIWindow - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.type == UIEventTypeMotion && motion == UIEventSubtypeMotionShake) { // via notification or something } } @end Then in your application delegate: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[OMGWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; //… } If you are using a Storyboard, this may be trickier, I don’t know the code you will need in the application delegate precisely. A: I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone: - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { if (self.lastAcceleration) { if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) { //Shaking here, DO stuff. shakeCount = 0; } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) { shakeCount = shakeCount + 5; }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) { if (shakeCount > 0) { shakeCount--; } } } self.lastAcceleration = acceleration; } - (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold { double deltaX = fabs(last.x - current.x), deltaY = fabs(last.y - current.y), deltaZ = fabs(last.z - current.z); return (deltaX > threshold && deltaY > threshold) || (deltaX > threshold && deltaZ > threshold) || (deltaY > threshold && deltaZ > threshold); } PS: I've set the update interval to 1/15th of a second. [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)]; A: In 3.0, there's now an easier way - hook into the new motion events. The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events: @implementation ShakingView - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if ( event.subtype == UIEventSubtypeMotionShake ) { // Put in code here to handle shake } if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) [super motionEnded:motion withEvent:event]; } - (BOOL)canBecomeFirstResponder { return YES; } @end You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view). In the view controller, you want to set this view to become first responder: - (void) viewWillAppear:(BOOL)animated { [shakeView becomeFirstResponder]; [super viewWillAppear:animated]; } - (void) viewWillDisappear:(BOOL)animated { [shakeView resignFirstResponder]; [super viewWillDisappear:animated]; } Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns! This method works even if you set applicationSupportsShakeToEdit to NO. A: From my Diceshaker application: // Ensures the shake is strong enough on at least two axes before declaring it a shake. // "Strong enough" means "greater than a client-supplied threshold" in G's. static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) { double deltaX = fabs(last.x - current.x), deltaY = fabs(last.y - current.y), deltaZ = fabs(last.z - current.z); return (deltaX > threshold && deltaY > threshold) || (deltaX > threshold && deltaZ > threshold) || (deltaY > threshold && deltaZ > threshold); } @interface L0AppDelegate : NSObject <UIApplicationDelegate> { BOOL histeresisExcited; UIAcceleration* lastAcceleration; } @property(retain) UIAcceleration* lastAcceleration; @end @implementation L0AppDelegate - (void)applicationDidFinishLaunching:(UIApplication *)application { [UIAccelerometer sharedAccelerometer].delegate = self; } - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { if (self.lastAcceleration) { if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) { histeresisExcited = YES; /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */ } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) { histeresisExcited = NO; } } self.lastAcceleration = acceleration; } // and proper @synthesize and -dealloc boilerplate code @end The histeresis prevents the shake event from triggering multiple times until the user stops the shake. A: I finally made it work using code examples from this Undo/Redo Manager Tutorial. This is exactly what you need to do: *Set the applicationSupportsShakeToEdit property in the App's Delegate: - (void)applicationDidFinishLaunching:(UIApplication *)application { application.applicationSupportsShakeToEdit = YES; [window addSubview:viewController.view]; [window makeKeyAndVisible]; } *Add/Override canBecomeFirstResponder, viewDidAppear: and viewWillDisappear: methods in your View Controller: -(BOOL)canBecomeFirstResponder { return YES; } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self becomeFirstResponder]; } - (void)viewWillDisappear:(BOOL)animated { [self resignFirstResponder]; [super viewWillDisappear:animated]; } *Add the motionEnded method to your View Controller: - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake) { // your code } } A: In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan or motionEnded methods in your view controller: class ViewController: UIViewController { override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) { println("started shaking!") } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { println("ended shaking!") } } A: You need to check the accelerometer via accelerometer:didAccelerate: method which is part of the UIAccelerometerDelegate protocol and check whether the values go over a threshold for the amount of movement needed for a shake. There is decent sample code in the accelerometer:didAccelerate: method right at the bottom of AppController.m in the GLPaint example which is available on the iPhone developer site. A: This is the basic delegate code you need: #define kAccelerationThreshold 2.2 #pragma mark - #pragma mark UIAccelerometerDelegate Methods - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { if (fabsf(acceleration.x) > kAccelerationThreshold || fabsf(acceleration.y) > kAccelerationThreshold || fabsf(acceleration.z) > kAccelerationThreshold) [self myShakeMethodGoesHere]; } Also set the in the appropriate code in the Interface. i.e: @interface MyViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UIAccelerometerDelegate> A: Just use these three methods to do it - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{ - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{ - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ for details you may check a complete example code over there A: A swiftease version based on the very first answer! override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if ( event?.subtype == .motionShake ) { print("stop shaking me!") } } A: In swift 5, this is how you can capture motion and check override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { print("shaking") } } A: To enable this app-wide, I created a category on UIWindow: @implementation UIWindow (Utils) - (BOOL)canBecomeFirstResponder { return YES; } - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake) { // Do whatever you want here... } } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/150446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "346" }
Q: Two questions regarding Scrum I have two related question regarding Scrum. Our company is trying to implement it and sure we are jumping over hoops. Both question are about "done means Done!" 1) It's really easy to define "Done" for tasks which are/have - clear test acceptance criterias - completely standalone - tested at the end by testers What should be done with tasks like: - architecture design - refactoring - some utility classes development The main issue with it, that it's almost completely internal entity and there is no way to check/test it from outside. As example feature implementation is kind of binary - it's done (and passes all test cases) or it's not done (don't pass some test cases). The best thing which comes to my head is to ask another developer to review that task. However, it's any way doesn't provide a clear way to determine is it completely done or not. So, the question is how do you define "Done" for such internal tasks? 2) Debug/bugfix task I know that agile methodology doesn't recommend to have big tasks. At least if task is big, it should be divided on smaller tasks. Let say we have some quite large problem - some big module redesign (to replace new outdate architecture with new one). Sure, this task is divided on dozens of small tasks. However, I know that at the end we will have quite long session of debug/fix. I know that's usually the problem of waterfall model. However, I think it's hard to get rid of it (especially for quite big changes). Should I allocate special task for debug/fix/system integrations and etc? In the case, if I do so, usually this task is just huge comparing to everything else and it's kind of hard to divide it on smaller tasks. I don't like this way, because of this huge monolith task. There is another way. I can create smaller tasks (associated with bugs), put them in backlog, prioritize and add them to iterations at the end of activity, when I will know what are the bugs. I don't like this way, because in such case the whole estimation will became fake. We estimate the task, mark it ask complete at any time. And we will open the new tasks for bugs with new estimates. So, we will end up with actual time = estimate time, which is definitely not good. How do you solve this problem? Regards, Victor A: For the first part " architecture design - refactoring - some utility classes development" These are never "done" because you do them as you go. In pieces. You want to do just enough architecture to get the first release going. Then, for the next release, a little more architecture. Refactoring is how you find utility classes (you don't set out to create utility classes -- you discover them during refactoring). Refactoring is something you do in pieces, as needed, prior to a release. Or as part of a big piece of functionality. Or when you have trouble writing a test. Or when you have trouble getting a test to pass and need to "debug". Small pieces of these things are done over and over again through the life of the project. They aren't really "release candidates" so they're just sprints (or parts of sprints) that gets done in the process of getting to a release. A: "Should I allocate special task for debug/fix/system integrations and etc?" Not the same way you did with a waterfall methodology where nothing really worked. Remember, you're building and testing incrementally. Each sprint is tested and debugged separately. When you get to a release candidate, you might want to do some additional testing on that release. Testing leads to bug discovery which leads to backlog. Usually this is high-priority backlog that needs to be fixed before the release. Sometimes integration testing reveals bugs that become low-priority backlog that doesn't need to be fixed before the next release. How big is that release test? Not very. You've already tested each sprint... There shouldn't be too many surprises. A: I would argue that if an internal activity has a benefit to the application (which all backlog items within scrum should have), done is the benefit is realized. For instance, "Design architecture" is too generic to identify the benefit of an activity. "Design architecture for user story A" identifies the scope of your activity. When you've created an architecture for story A, you're done with that task. Refactoring should likewise be done in context of achieving a user story. "Refactor Customer class to enable multiple phone numbers to support Story B" is something that can be identified as done when the Customer class supports multiple phone numbers. A: Third Question "some big module redesign (to replace new outdate architecture with new one). Sure, this task is divided on dozens of small tasks. However, I know that at the end we will have quite long session of debug/fix." Each sprint creates something that can be released. Maybe it won't be, but it could be. So, when you have major redesign, you have to eat the elephant one small piece at a time. First, look at the highest value -- most important -- biggest return to the users that you can do, get done, and release. But -- you say -- there is no such small piece; each piece requires massive redesign before anything can be released. I disagree. I think you can create a conceptual architecture -- what it will be when you're done -- but not implement the entire thing at once. Instead you create temporary interfaces, bridges, glue, connectors that will get one sprint done. Then you modify the temporary interfaces, bridges and glue so you can finish the next sprint. Yes, you've added some code. But, you've also created sprints that you can test and release. Sprints which are complete and any one can be a candidate release. A: Sounds like you're blurring the definition of user story and task. Simply: * *User stories add value. They're created by a product owner. *Tasks are activities undertaken to create that value. They're created by the engineers. You nailed key parts of the user story by saying they must have clear acceptance criteria, they're standalone, and they can be tested. Architecture, design, refactoring, and utility classes development are tasks. They're what's done to complete a user story. It's up to each development shop to set different standards for these, but at our company, at least one other developer must have looked at the code (pair programming, code reading, code review). If you have user stories which are "refactor class X" and "design feature Y", you're on the wrong track. It may be necessary to refactor X or design Y before you write code, but those could be tasks necessary to accomplish the user story "create new login widget". A: We've run into similar issues with "behind-the-scenes" code. By "behind-the-scenes" I mean, has no apparent or testable business value. In those cases, we've decided to define the developers of that portion of the code were the true "users". By creating sample applications and documentation that developers could use and test we had some "done" code. Usually with scrum though, you would be looking for a piece of business functionality that used a piece of code to determine "done". A: For technical tasks such as refactoring, you can check if the refactoring was really done, e.g. call X does no more have any f() method, or no more foobar() function. There should be Trust towards the team and inside the team as well. Why do you want to review if the task is actually done ? did you encounter situations where someone claim a task were done ans it wasn't ? For your second question, you should first really strive to break it into several smaller stories (backlog items). For instance, if you are re-architecturing the system, see if the new and the old architecture can coexist the time to do the portation of all your components from one to the other. If this is really not possible, then this shall be done separately of the rest of the sprint backlog items, and not integrated before it is "done done". If the sprint ends before the completion of all the tasks of the item, then you have to estimate the remaining amount of work and replan it for the next iteration. Here are twenty ways to split a story that could help having several smaller backlog items, with really is the recommended and safest way.
{ "language": "en", "url": "https://stackoverflow.com/questions/150447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there some way to make variables like $a and $b in regard to strict? In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking. Question: What is the standard--or cleanest way--to fake the special status that $a and $b have in regard to strict by simply importing a module? First of all some setup. The following works: #!/bin/perl use strict; print "\$a=$a\n"; print "\$b=$b\n"; If I add one more line: print "\$c=$c\n"; I get an error at compile time, which means that none of my dazzling print code gets to run. If I comment out use strict; it runs fine. Outside of strictures, $a and $b are mainly special in that sort passes the two values to be compared with those names. my @reverse_order = sort { $b <=> $a } @unsorted; Thus the main functional difference about $a and $b--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in List::Util. It's only when you use strict, that $a and $b become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared. : Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that $a and $b are special and that's it. If you want to use variables you don't have to declare $a and $b are your guys. If you want to have three variables by adding $c, suddenly there's a whole other way to do it. Nevermind that in manipulating hashes $k and $v might make more sense: my %starts_upper_1_to_25 = skim { $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash ;` Now, I use and I like strict. But I just want $k and $v to be visible to skim for the most compact syntax. And I'd like it to be visible simply by use Hash::Helper qw<skim>; I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the cleanest solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI. A: Others mentioned how to 'use vars' and 'our' - I just wanted to add that $a and $b are special cases, since they're used internally by the sort routines. Here's the note from the strict.pm docs: Because of their special use by sort(), the variables $a and $b are exempted from this check. A: If I understand correctly, what you want is: use vars qw($a $b); # Pre-5.6 or our ($a, $b); # 5.6 + You can read about it here. A: $a and $b are special because they're a part of the core language. While I can see why you might say that the inability to create similarly-special variables of your own is anti-TIMTOWTDI, I would say that it's no more so than the inability to create new basic commands on the order of 'print' or 'sort'. (You can define subs in modules, but that doesn't make them true keywords. It's the equivalent of using 'our $k', which you seem to be saying doesn't make $k enough like $a for you.) For pushing names into someone else's namespace, this should be a working example of Exporter: package SpecialK; use strict; use base 'Exporter'; BEGIN { our @EXPORT = qw( $k ); } our $k; 1; Save this to SpecialK.pm and 'use SpecialK' should then make $k available to you. Note that only 'our' variables can be exported, not 'my'. A: In Perl 5.6 and later, you can use our: our ($k, $v); Or you can stick with the older "use vars": use vars qw($k $v); Or you might just stick with "my", e.g.: my %hash; my ($k,$v); while (<>) { /^KEY=(.*)/ and $k = $1 and next; /^VALUE=(.*)/ and $v = $1; $hash{$k} = $v; print "$k $v\n"; } __END__ KEY=a VALUE=1 KEY=b VALUE=2 Making a global $v is not really necessary in the example above, but hopefully you get the idea ($k on the other hand needs to be scoped outside the while block). Alternatively, you can use fully qualified variable names: $main::k="foo"; $main::v="bar"; %main::hash{$k}=$v; A: If I'm understanding your question you want to write a module that declares variables in the user's namespace (so they don't have to) and which get localized automatically in callbacks. Is that right? You can do this by declaring globals and exporting them. (Though do note that it's generally considered bad form to export things without being asked to.) package Foo; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(*k *v hashmap); our ($k, $v); sub hashmap(&\%) { my $code = shift; my $hash = shift; while (local ($k, $v) = each %$hash) { $code->(); } } Note: The export is of *k and *v, not $k and $v. If you don't export the entire typeglob the local in hashmap won't work correctly from the user's package. A side effect of this is that all of the various forms of k and v (%k, @v, etc.) get declared and aliased. For a full explanation of this, see Symbol Tables in perlmod. Then in your script: use Foo; # exports $k and $v my %h = (a => 1, b => 2, c => 3); hashmap { print "$k => $v\n" } %h; __END__ c => 3 a => 1 b => 2 A: $a and $b are just global variables. You can achieve similar effects by simply declaring $k and $v: use strict; our ($k, $v); (In this case $k and $v are not global variables, but lexically scoped aliases for package variables. But if you don't cross the boundaries it's similarly enough.) A: It sounds like you want to do the sort of magic that List::MoreUtils does: use strict; my @a = (1, 2); my @b = (3, 4); my @x = pairwise { $a + $b } @a, @b; I'd suggest just looking at the pairwise sub in the List::MoreUtils source. It uses some clever symbol table fiddling to inject $a and $b into the caller's namespace and then localize them to just within the sub body. I think. A: This worked for me: package Special; use base qw<Exporter>; # use staging; -> commented out, my module for development our $c; our @EXPORT = qw<manip_c>; sub import { *{caller().'::c'} = *c; my $import_sub = Exporter->can( 'import' ); goto &$import_sub; } And it passes $c through strict, too. package main; use feature 'say'; use strict; use Special; use strict; say "In main: \$c=$c"; manip_c( 'f', sub { say "In anon sub: \$c=$c\n"; # In anon sub: $c=f }); say "In main: \$c=$c"; Yeah, it's kind of dumb that I bracketed my modules with "use strict", but I don't know the internals, and that takes care of potential sequencing issues. A: Is this what your after?..... use strict; use warnings; use feature qw/say/; sub hash_baz (&@) { my $code = shift; my $caller = caller; my %hash = (); use vars qw($k $v); no strict 'refs'; local *{ $caller . '::k' } = \my $k; local *{ $caller . '::v' } = \my $v; while ( @_ ) { $k = shift; $v = shift; $hash{ $k } = $code->() || $v; } return %hash; } my %hash = ( blue_cat => 'blue', purple_dog => 'purple', ginger_cat => 'ginger', purple_cat => 'purple' ); my %new_hash = hash_baz { uc $v if $k =~ m/purple/ } %hash; say "@{[ %new_hash ]}"; # => purple_dog PURPLE ginger_cat ginger purple_cat PURPLE blue_cat blue A: I'm not sure if anyone's clarified this, but strict does not whitelist $a and $b just because they are really convenient variable names for you to use in your own routines. $a and $b have special meaning for the sort operator. This is good from the point of view within such a sort routine, but kind of bad design from outside. :) You shouldn't be using $a and $b in other contexts, if you are. A: $a and $b aren't normal variables, though, and can't be easily replicated by either lexical declarations or explicit exports or messing about with the symbol table. For instance, using the debugger as a shell: DB<1> @foo = sort { $b cmp $a } qw(foo bar baz wibble); DB<2> x @foo 0 'wibble' 1 'foo' 2 'baz' 3 'bar' DB<3> x $a 0 undef DB<4> x $b 0 undef $a and $b only exist within the block passed to sort(), don't exist afterwards, and have scope in such a way that any further calls to sort don't tread on them. To replicate that, you probably need to start messing about with source filters, to turn your preferred notation my %starts_upper_1_to_25 = skim { $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash ; into effectively my %starts_upper_1_to_25 = map { my $k = $_; my $v = $my_hash{$v}; $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <=> 25 ) } keys %my_hash ; $a and $b are as special as $_ and @_, and while there's no easy way to change those names in Perl 5, Perl 6 does indeed fix this, with the given keyword. "given" is a rubbish term to search on, but http://dev.perl.org/perl6/doc/design/syn/S03.html may be a good place to start. A: The modules suggested that use export are really no different from use vars. But the use vars would need to be done in each package that used the $a-like variable. And our() would need to be done in each outer scope. Note that you can avoid using $a and $b even for sort by using a $$-prototyped sub: sub lccmp($$) { lc($_[0]) cmp lc($_[1]) } print join ' ', sort lccmp qw/I met this guy and he looked like he might have been a hat-check clerk/; This is essential when using a compare routine in a different package than the sort call. A: EDIT - this is actually incorrect, see the comments. Leaving it here to give other people a chance to learn from my mistake :) Oh, you're asking if there's a way for a module to declare $k and $v in the CALLER's namespace? You can use Exporter to push up your variables to the caller: use strict; package Test; use Exporter; my @ISA = qw/Exporter/; my $c = 3; my @EXPORT = qw/$c/; package main; print $c;
{ "language": "en", "url": "https://stackoverflow.com/questions/150454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Interfacing with Compris POS Does anyone have any data on how to interface with a Compris POS? I have a Compris POS, and I need to grab data from the database. I can't get information from NCR regarding the underlying data format, and I was wondering if anyone had reverse engineered the device, or had any documentation on the device. A: What kind of DB? Can you post the structure? I work with a POS software company and I'm quite sure I could deconstruct it rather easily... A: There are various tools such as pludump.exe, prtme.exe etc that you may already have which can provide extracts as text. These can then be imported into Excel.
{ "language": "en", "url": "https://stackoverflow.com/questions/150457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DataGridView's bound table only generates one RowChanged event on a double-click. How do I make it do two? I have a DataGridView whose DataSource is a DataTable. This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView. employeeSelectionTable.Columns.Add("IsSelected", typeof(bool)); ... employeeSelectionTable.RowChanged += selectionTableRowChanged; dataGridViewSelectedEmployees.DataSource = employeeSelectionTable; ... private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e) { if ((bool)e.Row["IsSelected"]) { Console.Writeline("Is Selected"); } else { Console.Writeline("Is Not Selected"); } break; } When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected." Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected." Here's where I have the problem: When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync. My solution right now is to subclass DataGridView and override WndProc to eat WM_LBUTTONDBLCLICK, so any double-clicking on the control is ignored. Is there a better solution? A: The reason that making an empty DoubleClick event method would not help would be that is executed in addition to the other operations that happen when a double click occurs. If you look at the windows generated code or examples of programatically adding event handlers, you use += to assign the event handler. This means you are adding that event handler in addition to the others that already exist, you could have multiple event handlers being triggered on the save event. My instinct would have been to override the DataGridView class, then override the OnDoubleClick method and not call the base OnDoubleClick method. However, I have tested this real quick and am seeing some interesting results. I put together the following test class: using System; using System.Windows.Forms; namespace TestApp { class DGV : DataGridView { private string test = ""; protected override void OnDoubleClick(EventArgs e) { MessageBox.Show(test + "OnDoubleClick"); } protected override void OnCellMouseDoubleClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e) { MessageBox.Show(test + "OnCellMouseDoubleClick"); } protected override void OnCellMouseClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e) { if (e.Clicks == 1) { // Had to do this with a variable as using a MessageBox // here would block us from pulling off a double click test = "1 click "; base.OnCellMouseClick(e); } else { MessageBox.Show("OnCellMouseClick"); } } } } Then inserted this into a windows form, adding a checkbox column and ran the program. On a fresh run, double clicking on the checkbox causes the messagebox display to say "1 click OnDoubleClick". This means that OnCellMouseClick executed on the first part of the double click and then OnDoubleClick executed on the second click. Also, unfortunately, the removal of the call to the base methods doesn't seem to be preventing the checkbox from getting the click passed to it. I suspect that for this approach to work it may have to be taken further and override the DataGridViewCheckBoxColumn and DataGridViewCheckBoxCell that ignores the double click. Assuming this works, you would be able to stop double click on the checkbox but allow it still on your other column controls. I have posted an answer on another question that talks about creating custom DataGridView columns and cells at here. A: In case you want a checkbox column inside a DataGridView, create something like this: DataGridViewCheckBoxCell checkBoxCell = new MyDataGridViewCheckBoxCell(); ... DataGridViewColumn col = new DataGridViewColumn(checkBoxCell); ... col.Name = "colCheckBox"; ... this.dgItems.Columns.Add(col); where dgItems is DataGridView instance. As you can see I have a MyDataGridViewCheckBoxCell class which is a subclass of the DataGridViewCheckBoxCell class. In this subclass I define: protected override void OnContentDoubleClick(DataGridViewCellEventArgs e) { //This the trick to keep the checkbox in sync with other actions. //base.OnContentDoubleClick(e); } When the user now double clicks a checkbox in the checkbox column the checkbox will behave as if it was single clicked. This should solve your sync problem. A: This isn't exactly an elegant solution, but why not simply do the following? private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { dgv_CellClick(sender, e); } This would explicitly force the second CellClick event and avoid out of sync. A: Is there some reason it needs to be done that low level? Can the DoubleClick Method just be an empty method that eats it? A: I already tried overriding the OnDoubleClick method in the DataGridView subclass to do nothing, but it still allowed the checkbox to be changed a second time. Ideally I was looking to have the DataTable's RowChanged event get called twice. Is there a way to affect the underlying DataTable via the overridden OnDoubleClick method? A: Why not just leave IsSelected column unbounded? Use CellContentClick event to push the data to underlying datatable and leave CellDoubleClick or RowChange event alone. private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.ColumnIndex == <columnIndex of IsSelected>) { string value = dgv[e.ColumnIndex, e.RowIndex].EditedFormattedValue; if( value == null || Convert.ToBoolean(value) == false) { //push false to employeeSelectionTable } else { //push true to employeeSelectionTable } } } A: Don't know why i had to, but i was able to put in a timer tick event attached to a datagridview refresh that just refreshed the dgv after the second click. In cell click event ** _RefreshTimer = new Timer(); _RefreshTimer.Tick += new EventHandler(RefreshTimer_Tick); _RefreshTimer.Interval = 100; _RefreshTimer.Start(); } } } void RefreshTimer_Tick(object sender, EventArgs e) { dgv.Refresh(); _RefreshTimer.Stop(); _RefreshTimer = null; }**
{ "language": "en", "url": "https://stackoverflow.com/questions/150471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Order of items in classes: Fields, Properties, Constructors, Methods Is there an official C# guideline for the order of items in terms of class structure? Does it go: * *Public Fields *Private Fields *Properties *Constructors *Methods ? I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere. The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor. Any tips/suggestions? A: As mentioned before there is nothing in the C# language that dictates the layout, I personally use regions, and I do something like this for an average class. public class myClass { #region Private Members #endregion #region Public Properties #endregion #region Constructors #endregion #region Public Methods #endregion } It makes sense to me anyway A: Usually I try to follow the next pattern: * *static members (have usually an other context, must be thread-safe, etc.) *instance members Each part (static and instance) consists of the following member types: * *operators (are always static) *fields (initialized before constructors) *constructors *destructor (is a tradition to follow the constructors) *properties *methods *events Then the members are sorted by visibility (from less to more visible): * *private *internal *internal protected *protected *public The order is not a dogma: simple classes are easier to read, however, more complex classes need context-specific grouping. A: My preference is to order by kind and then be decreasing visibility as follows public methods public events public properties protected methods protected events protected properties private methods private events private properties private fields public delegates public interfaces public classes public structs protected delegates protected interfaces protected classes protected structs private delegates private interfaces private classes private structs I know this violates Style Cop and if someone can give me a good reason why I should place the implementation details of a type before its interface I am willing to change. At present, I have a strong preference for putting private members last. Note: I don't use public or protected fields. A: From StyleCop private fields, public fields, constructors, properties, public methods, private methods As StyleCop is part of the MS build process you could view that as a de facto standard A: Rather than grouping by visibility or by type of item (field, property, method, etc.), how about grouping by functionality? A: This is an old but still very relevant question, so I'll add this: What's the first thing you look for when you open up a class file that you may or may not have read before? Fields? Properties? I've realized from experience that almost invariably I go hunting for the constructors, because the most basic thing to understand is how this object is constructed. Therefore, I've started putting constructors first in class files, and the result has been psychologically very positive. The standard recommendation of putting constructors after a bunch of other things feels dissonant. The upcoming primary constructor feature in C# 6 provides evidence that the natural place for a constructor is at the very top of a class - in fact primary constructors are specified even before the open brace. It's funny how much of a difference a reordering like this makes. It reminds me of how using statements used to be ordered - with the System namespaces first. Visual Studio's "Organize Usings" command used this order. Now usings are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner. A: The closest you're likely to find is "Design Guidelines, Managed code and the .NET Framework" (http://blogs.msdn.com/brada/articles/361363.aspx) by Brad Abrams Many standards are outlined here. The relevant section is 2.8 I think. A: I prefer to put the private fields up at the top along with the constructor(s), then put the public interface bits after that, then the private interface bits. Also, if your class definition is long enough for the ordering of items to matter much, that's probably a code smell indicating your class is too bulky and complex and you should refactor. A: I keep it as simple as possible (for me at least) Enumerations Declarations Constructors Overrides Methods Properties Event Handler A: I know this is old but my order is as follows: in order of public, protected, private, internal, abstract * *Constants *Static Variables *Fields *Events *Constructor(s) *Methods *Properties *Delegates I also like to write out properties like this (instead of the shorthand approach) // Some where in the fields section private int someVariable; // I also refrain from // declaring variables outside of the constructor // and some where in the properties section I do public int SomeVariable { get { return someVariable; } set { someVariable = value; } } A: I don't know about a language or industry standard, but I tend to put things in this order with each section wrapped in a #region: using Statements Namespace Class Private members Public properties Constructors Public methods Private methods A: the only coding guidelines I've seen suggested for this is to put fields at the top of the class definition. i tend to put constructors next. my general comment would be that you should stick to one class per file and if the class is big enough that the organization of properties versus methods is a big concern, how big is the class and should you be refactoring it anyway? does it represent multiple concerns? A: I would recommend using the coding standards from IDesign (webarchive) or the ones listed on Brad Abram's website. Those are the best two that I have found. Brad would say... Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types) A: According to the StyleCop Rules Documentation the ordering is as follows. Within a class, struct or interface: (SA1201 and SA1203) * *Constant Fields *Fields *Constructors *Finalizers (Destructors) *Delegates *Events *Enums *Interfaces (interface implementations) *Properties *Indexers *Methods *Structs *Classes Within each of these groups order by access: (SA1202) * *public *internal *protected internal *protected *private Within each of the access groups, order by static, then non-static: (SA1204) * *static *non-static Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215) * *readonly *non-readonly An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is: * *public static methods *public methods *internal static methods *internal methods *protected internal static methods *protected internal methods *protected static methods *protected methods *private static methods *private methods The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together. A: There certainly is nothing in the language that enforces it in any way. I tend to group things by visibility (public, then protected, then private) and use #regions to group related things functionally, regardless of whether it is a property, method, or whatever. Construction methods (whether actual ctors or static factory functions) are usually right at the top since they are the first thing clients need to know about. A: I have restructured the accepted answer, as to what I think is a better layout: Within a class, struct or interface: * *Constant Fields *Readonly Fields *Fields *Events *Properties *Indexers *Constructors *Finalizers (Destructors) *Interfaces (interface implementations) *Methods *Classes *Structs *Enums *Delegates Within each of these groups order by access: * *public *internal *protected internal *protected *private Within each of the access groups, order by static, then non-static: * *static *non-static I also feel that nested types should be kept to a minimum. All to often I see people having nested classes, enums, delegates that would be better of being a separate instance. There hardly ever is any gain of making a type nested. Put them in separate files as well. A file with 5 classes feels cluttered to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/150479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "787" }
Q: Adding AutoComplete to an Infragisitcs UltraDateTimeEditor control I'm attempting to modify an Infragisitcs UltraDateTimeEditor control so that the current year and a default time are inserted when the user only enters values for the month and day. The control has an AutoFillDate property, however setting this to "year" seems to overwrite user input entirely. Also changing the InvalidTextBehavior doesn't seem to help since the control starts out empty. What event(s) would I need to modify in order get the fill-in data to populate before the validation reverts to an empty string? A: Turns out the Event to handle for this is "BeforeExitEditMode." I was able to inspect and modify the user input before the validators fired.
{ "language": "en", "url": "https://stackoverflow.com/questions/150499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Slicehost installation profile I'm no UNIX Guru, but I've had to set up a handful of slices for various web projects. I've used the articles on there to set up users, a basic firewall, nginx or apache, and other bits and pieces of a basic web server. I foresee more slice administration in my future. Is there a more efficient way to set up users, permissions, and software on a clean slice than configuration by hand? A: It sounds like you can create a new slice from the backup of an existing one. This might not work for you if the slices would be different sizes, different distros, etc. Their forums mention this: Clone a slice? A: Depending on the number of machines you might find it makes sense to use something like CFEngine, or Puppet, to configure the new installs. That brings your work down to configuring each new machine as a CFEngine, for example, client. Then that may be used to install the packages, edit files, & etc. There are a few articles I wrote on the subject, with a Debian bias, here: http://www.debian-administration.org/tag/cfengine
{ "language": "en", "url": "https://stackoverflow.com/questions/150501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Capturing URL parameters in request.GET I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object. I'd like to learn how to do this without a library, so I can get to know Django better. A: This is not exactly what you asked for, but this snippet is helpful for managing query_strings in templates. A: If you only have access to the view object, then you can get the parameters defined in the URL path this way: view.kwargs.get('url_param') If you only have access to the request object, use the following: request.resolver_match.kwargs.get('url_param') Tested on Django 3. A: Using GET request.GET["id"] Using POST request.POST["id"] A: When a URL is like domain/search/?q=haha, you would use request.GET.get('q', ''). q is the parameter you want, and '' is the default value if q isn't found. However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments). Such as: (r'^user/(?P<username>\w{0,50})/$', views.profile_page,), Then in your views.py you would have def profile_page(request, username): # Rest of the method A: views.py from rest_framework.response import Response def update_product(request, pk): return Response({"pk":pk}) pk means primary_key. urls.py from products.views import update_product from django.urls import path urlpatterns = [ ..., path('update/products/<int:pk>', update_product) ] A: Someone would wonder how to set path in file urls.py, such as domain/search/?q=CA so that we could invoke query. The fact is that it is not necessary to set such a route in file urls.py. You need to set just the route in urls.py: urlpatterns = [ path('domain/search/', views.CityListView.as_view()), ] And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though request.GET.get('q', None). Here is an example (file views.py) class CityListView(generics.ListAPIView): serializer_class = CityNameSerializer def get_queryset(self): if self.request.method == 'GET': queryset = City.objects.all() state_name = self.request.GET.get('q', None) if state_name is not None: queryset = queryset.filter(state__name=state_name) return queryset In addition, when you write query string in the URL: http://servername:port/domain/search/?q=CA Do not wrap query string in quotes. For example, http://servername:port/domain/search/?q="CA" A: You might as well check request.META dictionary to access many useful things like PATH_INFO, QUERY_STRING # for example request.META['QUERY_STRING'] # or to avoid any exceptions provide a fallback request.META.get('QUERY_STRING', False) you said that it returns empty query dict I think you need to tune your url to accept required or optional args or kwargs Django got you all the power you need with regrex like: url(r'^project_config/(?P<product>\w+)/$', views.foo), more about this at django-optional-url-parameters A: This is another alternate solution that can be implemented: In the URL configuration: urlpatterns = [path('runreport/<str:queryparams>', views.get)] In the views: list2 = queryparams.split("&") A: To clarify camflan's explanation, let's suppose you have * *the rule url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page') *an incoming request for http://domain/user/thaiyoshi/?message=Hi The URL dispatcher rule will catch parts of the URL path (here "user/thaiyoshi/") and pass them to the view function along with the request object. The query string (here message=Hi) is parsed and parameters are stored as a QueryDict in request.GET. No further matching or processing for HTTP GET parameters is done. This view function would use both parts extracted from the URL path and a query parameter: def profile_page(request, username=None): user = User.objects.get(username=username) message = request.GET.get('message') As a side note, you'll find the request method (in this case "GET", and for submitted forms usually "POST") in request.method. In some cases, it's useful to check that it matches what you're expecting. Update: When deciding whether to use the URL path or the query parameters for passing information, the following may help: * *use the URL path for uniquely identifying resources, e.g. /blog/post/15/ (not /blog/posts/?id=15) *use query parameters for changing the way the resource is displayed, e.g. /blog/post/15/?show_comments=1 or /blog/posts/2008/?sort_by=date&direction=desc *to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories, and/or slugs: /blog/post/2008/09/30/django-urls/ A: def some_view(request, *args, **kwargs): if kwargs.get('q', None): # Do something here .. A: For situations where you only have the request object you can use request.parser_context['kwargs']['your_param'] A: You have two common ways to do that in case your URL looks like that: https://domain/method/?a=x&b=y Version 1: If a specific key is mandatory you can use: key_a = request.GET['a'] This will return a value of a if the key exists and an exception if not. Version 2: If your keys are optional: request.GET.get('a') You can try that without any argument and this will not crash. So you can wrap it with try: except: and return HttpResponseBadRequest() in example. This is a simple way to make your code less complex, without using special exceptions handling. A: I would like to share a tip that may save you some time. If you plan to use something like this in your urls.py file: url(r'^(?P<username>\w+)/$', views.profile_page,), Which basically means www.example.com/<username>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist. I've just experienced it myself; hope it helps! A: These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following: http://myserver:port/resource/?status=1 request.query_params.get('status', None) => 1 If you want to access the parameters passed by POST, you need to access this way: request.data.get('role', None) Accessing the dictionary (QueryDict) with 'get()', you can set a default value. In the cases above, if 'status' or 'role' are not informed, the values ​​are None. A: If you don't know the name of params and want to work with them all, you can use request.GET.keys() or dict(request.GET) functions A: url parameters may be captured by request.query_params A: It seems more recommended to use request.query_params. For example, When a URL is like domain/search/?q=haha, you would use request.query_params.get('q', None) https://www.django-rest-framework.org/api-guide/requests/ "request.query_params is a more correctly named synonym for request.GET. For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests."
{ "language": "en", "url": "https://stackoverflow.com/questions/150505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "603" }
Q: Get list of available Windows audio file formats I've got a C# program that's supposed to play audio files. I've figured out how to play any sound file for which Windows has a codec by using DirectShow, but now I want to properly fill in the file type filter box on the Open dialog. I'd like to automatically list any file format for which Windows has a codec. If some random user installs a codec for an obscure format, its associated extension(s) and file type description(s) need to show up in the list. Any ideas? A: If I remember correctly, a codec does not know which file types, i.e. file extensions, it supports, since a codec takes some stream as input and not actually a file. So if what you want is to display the file extensions of the supported audio file formats, you'll most likely be out of luck unless you have a extensive list of file extensions and associated codecs, but even then you'll get problems with container formats and all that. For example, my Windows Media Player happily plays m4b files, but does not know anything about them. I had to manually associate it with the file type. A: You could look in the Windows Registry for all file types with a content type of "audio/*". Specifically, look at all of the keys under HKCR/Software/*/Content Type. A: Just Use mm codec apis. Never use registry. A: You can use the NAudio open source .NET audio library to enumerate all the ACM codecs installed on your system. Take a look at the AcmDriver class.
{ "language": "en", "url": "https://stackoverflow.com/questions/150509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML input style to hide the box but show the contents I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way. I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts? A: Assuming you only want to remove the border and such from texts, you'll need to give them a class. Maybe something like: <input type="text" class="print-clean" .../> And css, loaded with media="print": <link rel="stylesheet" type="text/css" media="print" href="/css/print.css" /> would contain something like this: .print-clean { border: none; background: transparent; } A: <input type="text" style="border: 0; background-color: #fff;" /> Where #fff is your background color.. A: Add a separate CSS file for printing by doing something like this: <link rel="stylsheet" type="text/css" media="print" href="print.css"> add it to the <head> section of the page. In this(print.css) file include styling relevant to what you want to see when the page is printed, for example: input{border: 0px} should hide the border of input boxes when printing.
{ "language": "en", "url": "https://stackoverflow.com/questions/150513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Custom method in model to return an object In the database I have a field named 'body' that has an XML in it. The method I created in the model looks like this: def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = Array.new personal_info = {:studies => (item_module/"studies").inner_html, :birth_place => (item_module/"birth_place").inner_html, :marrital_status => (item_module/"marrital_status").inner_html} return personal_info end I want the function to return an object instead of an array. So I can use Module.studies instead of Model[:studies]. A: This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this: class PersonalData attr_accessor :studies attr_accessor :birth_place attr_accessor :marital_status def initialize(studies,birth_place,marital_status) @studies = studies @birth_place = birth_place @marital_status = marital_status end end And your translation code would look like: def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = PersonalData.new((item_module/"studies").inner_html, (item_module/"birth_place").inner_html, (item_module/"marital_status").innner_html) return personal_info end A: Or, if you want to avoid a model class, you could do something weird: class Hash def to_obj self.inject(Object.new) do |obj, ary| # ary is [:key, "value"] obj.instance_variable_set("@#{ary[0]}", ary[1]) class << obj; self; end.instance_eval do # do this on obj's metaclass attr_reader ary[0].to_sym # add getter method for this ivar end obj # return obj for next iteration end end end Then: h = {:foo => "bar", :baz => "wibble"} o = h.to_obj # => #<Object:0x30bf38 @foo="bar", @baz="wibble"> o.foo # => "bar" o.baz # => "wibble" It's like magic! A: on a slightly different tack. The idea of using a class method to do this feels wrong from an OO point of view. You should really refactor this so that it works from an instance method. def personal_data_module item_module = Hpricot(body) { :studies => (item_module/"studies").inner_html, :birth_place => (item_module/"birth_place").inner_html, :marrital_status => (item_module/"marrital_status").inner_html } end Then, where you need to use it, instead of doing.... Foobar.get_personal_data_module(the_id) you would do Foobar.find_by_person_id(the_id).personal_data_module This looks worse, but in fact, thats a bit artificial, normally, you would be referencing this from some other object, where in fact you would have a 'handle' on the person object, so would not have to construct it yourself. For instance, if you have another class, where you reference person_id as a foreign key, you would have class Organisation belongs_to :person end then, where you have an organisation, you could go organisation.person.personal_information_module Yes, I know, that breaks demeter, so it would be better to wrap it in a delegate class Organisation belongs_to :person def personal_info_module person.personal_info_module end end And then from controller code, you could just say organisation.personal_info_module without worrying about where it comes from at all. This is because a 'personal_data_module' is really an attribute of that class, not something to be accessed through a class method. But this also brings up some questions, for instance, is person_id the primary key of this table? is this a legacy situation where the primary key of the table is not called 'id'? If this is the case, have you told ActiveRecord about this or do you have to use 'find_by_person_id' all over where you would really want to write 'find'?
{ "language": "en", "url": "https://stackoverflow.com/questions/150514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send file using POST from a Python script This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean. A: Best thing I can think of is to encode it yourself. How about this subroutine? from urllib2 import Request, urlopen from binascii import b2a_base64 def b64open(url, postdata): req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'}) return urlopen(req) conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité") # returns a file-like object (Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.) A: PyCURL provides an interface to CURL from Python. http://curl.haxx.se/libcurl/python/ Curl will do all you need. It can transfer binary files properly, and supports many encodings. However, you have to make sure that the proper character encoding as a custom header when POSTing files. Specifically, you may need to do a 'file upload' style POST: http://curl.haxx.se/docs/httpscripting.html (Section 4.3) With curl (or any other HTTP client) you may have to set the content encoding: Content-Type: text/html; charset=UTF-8 Also, be aware that the request headers must be ascii, and this includes the url (so make sure you properly escape your possibly unicode URLs. There are unicode escapes for the HTTP headers) This was recently fixed in Python: http://bugs.python.org/issue3300 I hope this helps, there is more info on the topic, including setting your default character set on your server, etc. A: Just use this library and send in files. http://github.com/seisen/urllib2_file/
{ "language": "en", "url": "https://stackoverflow.com/questions/150517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Restlet - serving up static content Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a Directory, but in testing, I've found it will only serve 'index.html', everything else results in a 404. router.attach("/", new Directory(context, new Reference(baseRef, "./content")); So... http://service and http://service/index.html both work, but http://service/other.html gives me a 404 Can anyone shed some light on this? I want any file within the ./content directory to be available. PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is. A: Well, I figured out the issue. Actually Restlet appears to route requests based on prefix, but does not handle longest matching prefix correctly, it also seems to ignore file extensions. So for example, if I had a resource attached to "/other"... and a directory on "/". And I request /other.html, what actually happens is I get the "/other" resource. (The extension is ignored?), and not the static file from the directory as I would expect. If aynone knows why this is, or how to change it, I'd love to know. It's not a big deal, just for testing. I think we'll be putting apache or nginx in front of this in production anyway. A: Routers in Restlet by default use the "Template.MODE_STARTS_WITH" matching mode. You could always set the Router default by doing router.setMatchingMode(Template.MODE_EQUALS). This will turn on strict matching by default for attach. You can choose to override individual routes with setMatchingMode. Good documentation on Restlet Routing
{ "language": "en", "url": "https://stackoverflow.com/questions/150522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How Does One Read Bytes from File in Python Similar to this question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them. The struct package seems to be what I want, but I can't get it to work. Here is my code so-far (I am very new to python btw...so take it easy on me): def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] Printing out any value except is obviously crap because they are not formatted correctly. A: Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my answer over at this question. A: I was going to recommend the struct package but then you said you had tried it. Try this: self.major_version = struct.unpack('H', self.whole_string[3:5]) The pack() function convers Python data types to bits, and the unpack() function converts bits to Python data types. A: I am trying to read in an ID3v2 tag header FWIW, there's already a module for this. A: If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by: >>> s = '\0\x02' >>> struct.unpack('>H', s) (2,) Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use. For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details. You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value: >>> a,b,c = struct.unpack('>HHi', some_string) Going by your code, you are looking for (in order): * *a 3 char string *2 single byte values (major and minor version) *a 1 byte flags variable *a 32 bit length quantity The format string for this would be: ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)
{ "language": "en", "url": "https://stackoverflow.com/questions/150532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Jagged Button edges in Internet Explorer How do you remove the jagged edges from a wide button in internet explorer? For example: A: You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the background-color and/or border-color on your buttons. Try the following styles: background-color: black; color: white; border-color: red green blue yellow; You can of course make this much more pleasing to the eyes. But you get my point :) Stack Overflow uses this approach. A: As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery: input.button { padding: 0 .25em; width: 0; /* for IE only */ overflow: visible; } input.button[class] { /* IE ignores [class] */ width: auto; } $(function(){ $('input[type=button]').addClass('button'); }); The jQuery is for adding the button class. A more in depth write up can be found here. A: You can change the border style of the button with CSS, like this: /************************************************************************** Nav Button format settings **************************************************************************/ .navButtons { font-size: 9px; font-family: Verdana, sans-serif; width: 80; height: 20; position: relative; border-style: solid; border-width: 1; } A: Setting overflow: visible; on the button will cure the issue in IE 6 and 7. (See http://jehiah.cz/archive/button-width-in-ie) Exceptions * *In IE 6, if display:block; is also applied to the button, the above fix won't work. Setting the button to display:inline; in IE 6 will make the fix work. *If you have a button like this within a table cell, then the table cell won't contract to the new, smaller width of the button. You can fix this in IE 6 by setting width: 0; on the button. However, in IE 7 this will make everything but the text of the button disappear. (See http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie) More info on styling buttons: http://natbat.net/2009/Jun/10/styling-buttons-as-links/ A: Not too much you can do about it, but the good news is that it is fixed in IE8 http://webbugtrack.blogspot.com/2007/08/bug-101-buttons-render-stretched-and.html
{ "language": "en", "url": "https://stackoverflow.com/questions/150535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How robust is the asp.net profile system? Is it ready for prime time? I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance? A: Running against this via SQL I have found is a bit tricky, but i have worked with clients that have scaled it up to a few hundred properties, and 10K+ users without difficulty. Granted not a lot of users but it is working thus far. I think it really depends on the specific project, and your exact needs when it comes to working with the profile information. Do you need to query on it regularly via SQL? Do you just need to for user display only, these types of things might help provide a more solid answer for your needs. A: The SQL provider performance is more closely correlated to big iron throughput. Performance is more or less directly proportional to a single SQL Server's ability to handle the number of queries. Scale-up is the only option, so as such its not really five-nines robust out the box. You'll have to figure out if you need scale-out performance and availability e.g. through partitioning, replication, redundancy etc. and at what cost to performance. Some of the capabilities are are possible as is - the current implementation is more aimed at the middle-market and enterprise. Good thing is you can put your own implementation of the profile provider - then attach it to services and systems with capabilities outlined above. We wrote a custom authn,authz and profile provider and strapped it to large AD/LDS LDAP cluster across 3 datacenters. We're in the Comscore Top 10 - so you could say that we deal with a good slice of internet every day. 1000's of profile queries per second and 100'millions of profiles - it can scale with good planning, engineering and operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/150539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Forward an invocation of a variadic function in C In C, is it possible to forward the invocation of a variadic function? As in, int my_printf(char *fmt, ...) { fprintf(stderr, "Calling printf with fmt %s", fmt); return SOMEHOW_INVOKE_LIBC_PRINTF; } Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf. [Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition.] A: Not directly, however it is common (and you will find almost universally the case in the standard library) for variadic functions to come in pairs with a varargs style alternative function. e.g. printf/vprintf The v... functions take a va_list parameter, the implementation of which is often done with compiler specific 'macro magic', but you are guaranteed that calling the v... style function from a variadic function like this will work: #include <stdarg.h> int m_printf(char *fmt, ...) { int ret; /* Declare a va_list type variable */ va_list myargs; /* Initialise the va_list variable with the ... after fmt */ va_start(myargs, fmt); /* Forward the '...' to vprintf */ ret = vprintf(fmt, myargs); /* Clean up the va_list */ va_end(myargs); return ret; } This should give you the effect that you are looking for. If you are considering writing a variadic library function you should also consider making a va_list style companion available as part of the library. As you can see from your question, it can be prove useful for your users. A: C99 supports macros with variadic arguments; depending on your compiler, you might be able to declare a macro that does what you want: #define my_printf(format, ...) \ do { \ fprintf(stderr, "Calling printf with fmt %s\n", format); \ some_other_variadac_function(format, ##__VA_ARGS__); \ } while(0) In general, though, the best solution is to use the va_list form of the function you're trying to wrap, should one exist. A: Use vfprintf: int my_printf(char *fmt, ...) { va_list va; int ret; va_start(va, fmt); ret = vfprintf(stderr, fmt, va); va_end(va); return ret; } A: There's no way to forward such function calls because the only location where you can retrieve raw stack elements is in my_print(). The usual way to wrap calls like that is to have two functions, one that just converts the arguments into the various varargs structs, and another that actually operates upon those structs. Using such a double-function model, you can (for example) wrap printf() by initializing the structs in my_printf() with va_start(), and then pass them to vfprintf(). A: Not sure if this helps to answer OP's question since I do not know why the restriction for using a helper function akin to vfprintf in the wrapper function applies. I think the key problem here is that forwarding the variadic argument list without interpreting them is difficult. What is possible, is to perform the formatting (using a helper function akin to vfprintf: vsnprintf) and forward the formatted output to the wrapped function with variadic arguments (i.e. not modifying the definition of the wrapped function). So, here we go: #include <stdio.h> #include <stdarg.h> int my_printf(char *fmt, ...) { if (fmt == NULL) { /* Invalid format pointer */ return -1; } else { va_list args; int len; /* Initialize a variable argument list */ va_start(args, fmt); /* Get length of format including arguments */ len = vsnprintf(NULL, 0, fmt, args); /* End using variable argument list */ va_end(args); if (len < 0) { /* vsnprintf failed */ return -1; } else { /* Declare a character buffer for the formatted string */ char formatted[len + 1]; /* Initialize a variable argument list */ va_start(args, fmt); /* Write the formatted output */ vsnprintf(formatted, sizeof(formatted), fmt, args); /* End using variable argument list */ va_end(args); /* Call the wrapped function using the formatted output and return */ fprintf(stderr, "Calling printf with fmt %s", fmt); return printf("%s", formatted); } } } int main() { /* Expected output: Test * Expected error: Calling printf with fmt Test */ my_printf("Test\n"); //printf("Test\n"); /* Expected output: Test * Expected error: Calling printf with fmt %s */ my_printf("%s\n", "Test"); //printf("%s\n", "Test"); /* Expected output: %s * Expected error: Calling printf with fmt %s */ my_printf("%s\n", "%s"); //printf("%s\n", "%s"); return 0; } I came across this solution here. Editted: fixed mistakes pointed out by egmont A: If you don't have a function analogous to vfprintf that takes a va_list instead of a variable number of arguments, you can't do it. See http://c-faq.com/varargs/handoff.html. Example: void myfun(const char *fmt, va_list argp) { vfprintf(stderr, fmt, argp); } A: gcc offers an extension that can do this: __builtin_apply and relatives. See Constructing Function Calls in the gcc manual. An example: #include <stdio.h> int my_printf(const char *fmt, ...) { void *args = __builtin_apply_args(); printf("Hello there! Format string is %s\n", fmt); void *ret = __builtin_apply((void (*)())printf, args, 1000); __builtin_return(ret); } int main(void) { my_printf("%d %f %s\n", -37, 3.1415, "spam"); return 0; } Try it on godbolt There are some cautions in the documentation that it might not work in more complicated situations. And you have to hardcode a maximum size for the arguments (here I used 1000). But it might be a reasonable alternative to the other approaches that involve dissecting the stack in either C or assembly language. A: As it is not really possible to forward such calls in a nice way, we worked around this by setting up a new stack frame with a copy of the original stack frame. However this is highly unportable and makes all kinds of assumptions, e.g. that the code uses frame pointers and the 'standard' calling conventions. This header file allows to wrap variadic functions for x86_64 and i386 (GCC). It doesn't work for floating-point arguments, but should be straight forward to extend for supporting those. #ifndef _VA_ARGS_WRAPPER_H #define _VA_ARGS_WRAPPER_H #include <limits.h> #include <stdint.h> #include <alloca.h> #include <inttypes.h> #include <string.h> /* This macros allow wrapping variadic functions. * Currently we don't care about floating point arguments and * we assume that the standard calling conventions are used. * * The wrapper function has to start with VA_WRAP_PROLOGUE() * and the original function can be called by * VA_WRAP_CALL(function, ret), whereas the return value will * be stored in ret. The caller has to provide ret * even if the original function was returning void. */ #define __VA_WRAP_CALL_FUNC __attribute__ ((noinline)) #define VA_WRAP_CALL_COMMON() \ uintptr_t va_wrap_this_bp,va_wrap_old_bp; \ va_wrap_this_bp = va_wrap_get_bp(); \ va_wrap_old_bp = *(uintptr_t *) va_wrap_this_bp; \ va_wrap_this_bp += 2 * sizeof(uintptr_t); \ size_t volatile va_wrap_size = va_wrap_old_bp - va_wrap_this_bp; \ uintptr_t *va_wrap_stack = alloca(va_wrap_size); \ memcpy((void *) va_wrap_stack, \ (void *)(va_wrap_this_bp), va_wrap_size); #if ( __WORDSIZE == 64 ) /* System V AMD64 AB calling convention */ static inline uintptr_t __attribute__((always_inline)) va_wrap_get_bp() { uintptr_t ret; asm volatile ("mov %%rbp, %0":"=r"(ret)); return ret; } #define VA_WRAP_PROLOGUE() \ uintptr_t va_wrap_ret; \ uintptr_t va_wrap_saved_args[7]; \ asm volatile ( \ "mov %%rsi, (%%rax)\n\t" \ "mov %%rdi, 0x8(%%rax)\n\t" \ "mov %%rdx, 0x10(%%rax)\n\t" \ "mov %%rcx, 0x18(%%rax)\n\t" \ "mov %%r8, 0x20(%%rax)\n\t" \ "mov %%r9, 0x28(%%rax)\n\t" \ : \ :"a"(va_wrap_saved_args) \ ); #define VA_WRAP_CALL(func, ret) \ VA_WRAP_CALL_COMMON(); \ va_wrap_saved_args[6] = (uintptr_t)va_wrap_stack; \ asm volatile ( \ "mov (%%rax), %%rsi \n\t" \ "mov 0x8(%%rax), %%rdi \n\t" \ "mov 0x10(%%rax), %%rdx \n\t" \ "mov 0x18(%%rax), %%rcx \n\t" \ "mov 0x20(%%rax), %%r8 \n\t" \ "mov 0x28(%%rax), %%r9 \n\t" \ "mov $0, %%rax \n\t" \ "call *%%rbx \n\t" \ : "=a" (va_wrap_ret) \ : "b" (func), "a" (va_wrap_saved_args) \ : "%rcx", "%rdx", \ "%rsi", "%rdi", "%r8", "%r9", \ "%r10", "%r11", "%r12", "%r14", \ "%r15" \ ); \ ret = (typeof(ret)) va_wrap_ret; #else /* x86 stdcall */ static inline uintptr_t __attribute__((always_inline)) va_wrap_get_bp() { uintptr_t ret; asm volatile ("mov %%ebp, %0":"=a"(ret)); return ret; } #define VA_WRAP_PROLOGUE() \ uintptr_t va_wrap_ret; #define VA_WRAP_CALL(func, ret) \ VA_WRAP_CALL_COMMON(); \ asm volatile ( \ "mov %2, %%esp \n\t" \ "call *%1 \n\t" \ : "=a"(va_wrap_ret) \ : "r" (func), \ "r"(va_wrap_stack) \ : "%ebx", "%ecx", "%edx" \ ); \ ret = (typeof(ret))va_wrap_ret; #endif #endif In the end you can wrap calls like this: int __VA_WRAP_CALL_FUNC wrap_printf(char *str, ...) { VA_WRAP_PROLOGUE(); int ret; VA_WRAP_CALL(printf, ret); printf("printf returned with %d \n", ret); return ret; } A: Almost, using the facilities available in <stdarg.h>: #include <stdarg.h> int my_printf(char *format, ...) { va_list args; va_start(args, format); int r = vprintf(format, args); va_end(args); return r; } Note that you will need to use the vprintf version rather than plain printf. There isn't a way to directly call a variadic function in this situation without using va_list. A: Yes you can do it, but it is somewhat ugly and you have to know the maximal number of arguments. Furthermore if you are on an architecture where the arguments aren't passed on the stack like the x86 (for instance, PowerPC), you will have to know if "special" types (double, floats, altivec etc.) are used and if so, deal with them accordingly. It can be painful quickly but if you are on x86 or if the original function has a well defined and limited perimeter, it can work. It still will be a hack, use it for debugging purpose. Do not build you software around that. Anyway, here's a working example on x86: #include <stdio.h> #include <stdarg.h> int old_variadic_function(int n, ...) { va_list args; int i = 0; va_start(args, n); if(i++<n) printf("arg %d is 0x%x\n", i, va_arg(args, int)); if(i++<n) printf("arg %d is %g\n", i, va_arg(args, double)); if(i++<n) printf("arg %d is %g\n", i, va_arg(args, double)); va_end(args); return n; } int old_variadic_function_wrapper(int n, ...) { va_list args; int a1; int a2; int a3; int a4; int a5; int a6; int a7; int a8; /* Do some work, possibly with another va_list to access arguments */ /* Work done */ va_start(args, n); a1 = va_arg(args, int); a2 = va_arg(args, int); a3 = va_arg(args, int); a4 = va_arg(args, int); a5 = va_arg(args, int); a6 = va_arg(args, int); a7 = va_arg(args, int); va_end(args); return old_variadic_function(n, a1, a2, a3, a4, a5, a6, a7, a8); } int main(void) { printf("Call 1: 1, 0x123\n"); old_variadic_function(1, 0x123); printf("Call 2: 2, 0x456, 1.234\n"); old_variadic_function(2, 0x456, 1.234); printf("Call 3: 3, 0x456, 4.456, 7.789\n"); old_variadic_function(3, 0x456, 4.456, 7.789); printf("Wrapped call 1: 1, 0x123\n"); old_variadic_function_wrapper(1, 0x123); printf("Wrapped call 2: 2, 0x456, 1.234\n"); old_variadic_function_wrapper(2, 0x456, 1.234); printf("Wrapped call 3: 3, 0x456, 4.456, 7.789\n"); old_variadic_function_wrapper(3, 0x456, 4.456, 7.789); return 0; } For some reason, you can't use floats with va_arg, gcc says they are converted to double but the program crashes. That alone demonstrates that this solution is a hack and that there is no general solution. In my example I assumed that the maximum number of arguments was 8, but you can increase that number. The wrapped function also only used integers but it works the same way with other 'normal' parameters since they always cast to integers. The target function will know their types but your intermediary wrapper doesn't need to. The wrapper also doesn't need to know the right number of arguments since the target function will also know it. To do useful work (except just logging the call), you probably will have to know both though. A: There are essentially three options. One is to not pass it on but to use the variadic implementation of your target function and not pass on the ellipses. The other one is to use a variadic macro. The third option is all the stuff i am missing. I usually go with option one since i feel like this is really easy to handle. Option two has a drawback because there are some limitations to calling variadic macros. Here is some example code: #include <stdio.h> #include <stdarg.h> #define Option_VariadicMacro(f, ...)\ printf("printing using format: %s", f);\ printf(f, __VA_ARGS__) int Option_ResolveVariadicAndPassOn(const char * f, ... ) { int r; va_list args; printf("printing using format: %s", f); va_start(args, f); r = vprintf(f, args); va_end(args); return r; } void main() { const char * f = "%s %s %s\n"; const char * a = "One"; const char * b = "Two"; const char * c = "Three"; printf("---- Normal Print ----\n"); printf(f, a, b, c); printf("\n"); printf("---- Option_VariadicMacro ----\n"); Option_VariadicMacro(f, a, b, c); printf("\n"); printf("---- Option_ResolveVariadicAndPassOn ----\n"); Option_ResolveVariadicAndPassOn(f, a, b, c); printf("\n"); } A: The best way to do this is static BOOL(__cdecl *OriginalVarArgsFunction)(BYTE variable1, char* format, ...)(0x12345678); //TODO: change address lolz BOOL __cdecl HookedVarArgsFunction(BYTE variable1, char* format, ...) { BOOL res; va_list vl; va_start(vl, format); // Get variable arguments count from disasm. -2 because of existing 'format', 'variable1' uint32_t argCount = *((uint8_t*)_ReturnAddress() + 2) / sizeof(void*) - 2; printf("arg count = %d\n", argCount); // ((int( __cdecl* )(const char*, ...))&oldCode)(fmt, ...); __asm { mov eax, argCount test eax, eax je noLoop mov edx, vl loop1 : push dword ptr[edx + eax * 4 - 4] sub eax, 1 jnz loop1 noLoop : push format push variable1 //lea eax, [oldCode] // oldCode - original function pointer mov eax, OriginalVarArgsFunction call eax mov res, eax mov eax, argCount lea eax, [eax * 4 + 8] //+8 because 2 parameters (format and variable1) add esp, eax } return res; } A: If it is possible to compile your code using a C++11 or higher compiler, you can use a variadic function template: #include <stdio.h> template<typename... Targs> int my_printf(const char *fmt, Targs... Fargs) { fprintf(stderr, "Calling printf with fmt %s", fmt); return printf(fmt, Fargs...);; } int main() { my_printf("test %d\n", 1); return 0; } Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/150543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "231" }
Q: Can you catch a native exception in C# code? In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it? A: Somewhere using a .NET Reflector I've seen the following code: try { ... } catch(Exception e) { ... } catch { ... } Hmm, C# does not allow to throw an exception not deriving from the System.Exception class. And as far as I known any exception cautch by the interop marshaller is wrapped by the exception class that inherits the System.Exception. So my question is whether it's possible to catch an exception that is not a System.Exception. A: This depends on what type of native exception you are talking about. If you're referring to an SEH exception then the CLR will do one of two things. * *In the case of a known SEH error code it will map it to the appropriate .Net exception (i.e. OutOfMemoryException) *In the case of an un-mappable (E_FAIL) or unknown code it will just throw an SEHException instance. Both of these will be caught with a simple "catch (Exception)" block. The other type of native exception which can cross the native/managed boundary are C++ exceptions. I'm not sure how they are mapped/handled. My guess is that since Windows implements C++ exceptions on top of SEH, they are just mapped the same way. A: With .Net Framework 4.8 IF the exception is handled nicely within the native code then you can catch it with a standard try catch. try { //call native code method } catch (Exception ex) { //do stuff } HOWEVER, if the native code is in a 3rd party dll you have no control over, you may find that the developers are inadvertently throwing unhandled exceptions. I have found NOTHING will catch these, except a global error handler. private static void Main() { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; try { //call native code method } catch (Exception ex) { //unhandled exception from native code WILL NOT BE CAUGHT HERE } } private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject as Exception; //do stuff } There is a reason for this. Unhandled native exceptions can indicate a corrupted state that you can't recover from (eg stack overflow or access violation). However, there are cases you still want to do stuff before terminating the process, like log the error that just tried to crash your windows service!!! A bit of History None of the following is required any more. From .Net 2.0 - 3.5 you could use an empty catch: try { //call native code method } catch (Exception ex) { //do stuff } catch { //do same stuff but without any exception detail } From .Net 4 they turned off native exceptions being abled to be caught by default and you needed to explicitly turn it back on by decorating your methods with attributes. [HandleProcessCorruptedStateExceptions] [SecurityCritical] private static void Main() { try { //call native code method } catch (Exception ex) { //do stuff } } also required was a change to the app.config file: <configuration> <runtime> <legacyCorruptedStateExceptionsPolicy enabled="true" /> </runtime> </configuration> A: You can use Win32Exception and use its NativeErrorCode property to handle it appropriately. // http://support.microsoft.com/kb/186550 const int ERROR_FILE_NOT_FOUND = 2; const int ERROR_ACCESS_DENIED = 5; const int ERROR_NO_APP_ASSOCIATED = 1155; void OpenFile(string filePath) { Process process = new Process(); try { // Calls native application registered for the file type // This may throw native exception process.StartInfo.FileName = filePath; process.StartInfo.Verb = "Open"; process.StartInfo.CreateNoWindow = true; process.Start(); } catch (Win32Exception e) { if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND || e.NativeErrorCode == ERROR_ACCESS_DENIED || e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED) { MessageBox.Show(this, e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } A: Almost, but not quite. You will catch the exception with try { ... } catch (Exception e) { ... } but you will still have potential problems. According to MSDN, in order to insure exception destructors are called you would have to catch like: try { ... } catch { ... } This is the only way to insure an exception destructor is called (though I'm not sure why). But that leaves you with the tradeoff of brute force versus a possible memory leak. Incidentally, if you use the (Exception e) approach you should know the different types of exceptions you might come across. RuntimeWrappedException is what any managed non-exception type will be mapped to (for languages that can throw a string), and others will be mapped, such as OutOfMemoryException and AccessViolationException. COM Interop HRESULTS or exceptions other than E___FAIL will map to COMException, and finally at the end you have SEHException for E_FAIL or any other unmapped exception. So what should you do? Best choice is don't throw exceptions from your unamanaged code! Hah. Really though if you have a choice, put up barriers and failing that make the choice of which is worse, a chance of a memory leak during exception handling, or not knowing what type your exception is. A: Catch without () will catch non-CLS compliant exceptions including native exceptions. try { } catch { } See the following FxCop rule for more info http://msdn.microsoft.com/en-gb/bb264489.aspx A: The interop layer between C# and native code will convert the exception into a managed form, allowing it to be caught by your C# code. As of .NET 2.0, catch (Exception) should catch anything other than a nonrecoverable error. A: If you use a try { } catch(Exception ex) { } it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error. A: A standard try catch should do the trick i believe. I run into a similar problem with a System.data exception throwing a sqlClient exception which was uncaught, adding a try..catch into my code did the trick in the instance
{ "language": "en", "url": "https://stackoverflow.com/questions/150544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: In ActionScript (NaN==parseFloat(input.text)) warns that it will always be false. Why? Despite the rather clear documentation which says that parseFloat() can return NaN as a value, when I write a block like: if ( NaN == parseFloat(input.text) ) { errorMessage.text = "Please enter a number." } I am warned that the comparison will always be false. And testing shows the warning to be correct. Where is the corrected documentation, and how can I write this to work with AS3? A: isNaN(parseFloat(input.text)) A: Because comparing anything to NaN is always false. Use isNaN() instead. A: BTW, if for some reason you don't have access to isNaN(), the traditional method is to compare the number to itself: if( number != number ) { //Is NaN } A: Documentation can be found in the Adobe Flex Language Reference Here as well as other globally available functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/150548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Executing dynamic SQL in a SQLServer 2005 function I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is just easier to code the sections where I need this checksum using a function. This code will not work because of the Exec SP_ExecuteSQL @SQL calls. Anyone know how to execute dynamic SQL in a function? (and once again, I do not think it is possible. If it is though, I'd love to know how to get around it!) Create Function Get_Checksum ( @DatabaseName varchar(100), @TableName varchar(100) ) RETURNS FLOAT AS BEGIN Declare @SQL nvarchar(4000) Declare @ColumnName varchar(100) Declare @i int Declare @Checksum float Declare @intColumns table (idRecord int identity(1,1), ColumnName varchar(255)) Declare @CS table (MyCheckSum bigint) Set @SQL = 'Insert Into @IntColumns(ColumnName)' + Char(13) + 'Select Column_Name' + Char(13) + 'From ' + @DatabaseName + '.Information_Schema.Columns (NOLOCK)' + Char(13) + 'Where Table_Name = ''' + @TableName + '''' + Char(13) + ' and Data_Type = ''int''' -- print @SQL exec sp_executeSql @SQL Set @SQL = 'Insert Into @CS(MyChecksum)' + Char(13) + 'Select ' Set @i = 1 While Exists( Select 1 From @IntColumns Where IdRecord = @i) begin Select @ColumnName = ColumnName From @IntColumns Where IdRecord = @i Set @SQL = @SQL + Char(13) + CASE WHEN @i = 1 THEN ' Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' ELSE ' + Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' END Set @i = @i + 1 end Set @SQL = @SQL + Char(13) + 'From ' + @DatabaseName + '..' + @TableName + ' (NOLOCK)' -- print @SQL exec sp_executeSql @SQL Set @Checksum = (Select Top 1 MyChecksum From @CS) Return isnull(@Checksum,0) END GO A: Here is the solution Solution 1: Return the dynamic string from Function then Declare @SQLStr varchar(max) DECLARE @tmptable table (<columns>) set @SQLStr=dbo.function(<parameters>) insert into @tmptable Exec (@SQLStr) select * from @tmptable Solution 2: call nested functions by passing parameters. A: You can get around this by calling an extended stored procedure, with all the attendant hassle and security problems. http://decipherinfosys.wordpress.com/2008/07/16/udf-limitations-in-sql-server/ http://decipherinfosys.wordpress.com/2007/02/27/using-getdate-in-a-udf/ A: It "ordinarily" can't be done as SQL Server treats functions as deterministic, which means that for a given set of inputs, it should always return the same outputs. A stored procedure or dynamic sql can be non-deterministic because it can change external state, such as a table, which is relied on. Given that in SQL server functions are always deterministic, it would be a bad idea from a future maintenance perspective to attempt to circumvent this as it could cause fairly major confusion for anyone who has to support the code in future. A: Because functions have to play nicely with the query optimiser there are quite a few restrictions on them. This link refers to an article that discusses the limitations of UDF's in depth. A: Thank you all for the replies. Ron: FYI, Using that will throw an error. I agree that not doing what I originally intended is the best solution, I decided to go a different route. My two choices were to use sum(cast(BINARY_CHECKSUM(*) as float)) or an output parameter in a stored procedure. After unit testing speed of each, I decided to go with sum(cast(BINARY_CHECKSUM(*) as float)) to get a comparable checksum value for each table's data.
{ "language": "en", "url": "https://stackoverflow.com/questions/150552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: What is the minimum length number the luhn algorithm will work on? Excluding the check digit, what is the minimum length number the luhn algorithm will work on? My thoughts are that it would work on any number greater than 2 digits (again, excluding the check digit). The reason I ask is this: if i iterates over all digits in the number from right to left. This causes i%2 == 0 (used to find alternate positions in the number) in my luhn validation to fail if the number is 3 digits or smaller (e.g. 125 -- which on paper seems to be a valid number) Obviously I could change my condition from i%2== 0 to something else but if it's not the correct behavior for the algorithm it'd be nice to know. A: Luhn's algorithm would work on two digits. It will warn if a single digit is wrong and some (but not all) of the cases where digits are transposed. Heck, it would theoretically work with one digit, but that's not very useful. You can see for yourself by fixing one digit, then changing the other and verifying that each value of the other digit will give a unique "checksum". With just two digits, however, just adding digits mod 10 would give you the same property, but it wouldn't catch any transposition errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/150554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find out if a Timer is running? If I have an instance of a System.Timers.Timer that has a long interval - say 1 minute, how can I find out if it is started without waiting for the Tick? A: Use the timer's Enabled property. A: You should check that timer is enabled A: if (timer1.Enabled) { // Do Something } A: If Timer.Enabled is true, your timer is running. Calling Timer.Start sets Enabled to true. Calling Timer.Stop sets Enabled to false. If Timer.AutoReset is true, then Enabled will automatically be set to false the first time the timer expires. A: System.Timer.Timer.Enabled should work, when you call "Start" it sets Enabled to TRUE, "Stop" sets it to FALSE.
{ "language": "en", "url": "https://stackoverflow.com/questions/150575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: Which browser has the best support for HTML 5 currently? Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out! A: http://wiki.whatwg.org/wiki/Implementations_in_Web_browsers has information maintained by the WHATWG community (and everyone who drops by and edits it). Disclaimer: I'm a member of that community. A: Major browsers are providing increased support now. http://radar.oreilly.com/2009/05/google-bets-big-on-html-5.html A: To test your browser, go to http://html5test.com/. The code is being maintained at: github dot com slash NielsLeenheer slash html5test. A: Ones that are built using a recent webkit build, and Presto. Safari 3.1 for webkit Opera for Presto. I'm pretty sure firefox will start supporting html5 partially in 3.1 All support is extremely partial. Check here for information on what is supported. A: Seems that new browsers support most of the tags: <header>, <section> etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags: document.createElement('header'); Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it. This means that you can now use the new tags without any loss of functionality, which is a good start! A: Opera also has some support. Generally however, it is too early to test out. You'll probably have to wait a year or 2 before any browser will have enough realistic support to test against. EDIT Wikipedia has a good article on how much of HTML 5 various layout engines have implemented. It includes specific aspects of HTML 5. A: i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5 A: This page is a neat summary, but is not entirely accurate: http://findmebyip.com/litmus#target-selector
{ "language": "en", "url": "https://stackoverflow.com/questions/150577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: When to use IEnumerable over IEnumerable<> Due to the lack of generic variance in the .NET framework, is it more "correct" to have methods that handle the non-generic versions of the System.Collection interfaces, if the methods are being designed to handle multiple types? Ideally, once moved to .NET 3.5, the code would modified to change these methods into extension methods. A: No, the more "correct" thing to do is to make the methods that handle multiple types generic themselves. A: In this case (IEnumerable), implementing the generic version is better, as it derives from IEnumerable (non-Generic), so it becomes a moot point, both are available to you. A: Define "Multiple types" do you mean, for example, a List that contains both Cars and Dogs? Or one List that contains Cars and another that contains Dogs? Unless you're doing something "special" I'd say the correct thing to do is to implement the Generic version and not the non-generic version. A: Here is a decent article explaining it. The only solution that I can see is to follow the advice of the article, and make the method a generic method as well. But, I am not sure how well it will stand up to being an extension method.
{ "language": "en", "url": "https://stackoverflow.com/questions/150581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How much difference does BLOB or TEXT make in comparison with VARCHAR()? If I don't know the length of a text entry (e.g. a blog post, description or other long text), what's the best way to store it in MYSQL? A: use TEXT if you want it treated as a character string, with a character set. use BLOB if you want it treated as a binary string, without a character set. I recommend using TEXT. A: TEXT would be the most appropriate for unknown size text. VARCHAR is limited to 65,535 characters from MYSQL 5.0.3 and 255 chararcters in previous versions, so if you can safely assume it will fit there it will be a better choice. BLOB is for binary data, so unless you expect your text to be in binary format it is the least suitable column type. For more information refer to the Mysql documentation on string column types.
{ "language": "en", "url": "https://stackoverflow.com/questions/150588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Whats the best way to start using Mylyn? I've heard a lot of good things about using Mylyn in eclipse. How could I set it up to give me a taste of how I could use it? A: Simple define tasks for yourself and let Mylyn focus on it. I'm not able to use the bugtracking connections of Mylyn because we use a non-standard tracking solution at work (home grown and awfull), but the fast task-context switching with Mylyn is very usefull in daily work. I work as senior developer so many times come orthers to ask something about their part of the code. I have a task for this interrupts, activate it and after they've gone i could simple swith back to my work. A: Another tip: start out by preventing Mylyn from actually hiding things not relevant to your current task so it will just shade them gray instead. Hiding used to be automatic (maybe it still is?) and it tended to throw people off. I actually find the hiding more distracting and prefer the graying-out. A: I would recommend a two step process if you'd like to start using Mylyn. * *Get an overview of Mylyn and its advantages *Configure Mylyn to work with your setup In order to get an overview of Mylyn consider one of the following resources: * *Why Mylyn is Indispensable, blog by Marc Esher *Code at the Speed of Thought, presentation by Mik Kersten (47 minutes) To configure Mylyn in a way that optimizes your productivity it helps to follow a few simple steps. I would recommend using one of the following as your guide to getting setup: * *Getting Started Video Series (one, two) *Getting Started Wizard in Tasktop Pro (screenshot) *Tasktop Pro/Mylyn How-to Series Hope this helps! David Shepherd, Tasktop Technologies Inc. A: http://www.vogella.de/articles/Mylyn/article.html is an excellent introduction to Mylyn and is frequently updated A: The Developer Works articles serg10 points out are great. Another great way to learn more about Mylyn is to watch the video, "Mylyn 3.0: Code at the speed of thought". See http://tasktop.com/mylyn/ for the most relevant Mylyn resources. A: Connect it to your bugtracker and use "Focus On Active Task". A: The seminal Developerworks article from the 2.0 release is a great introduction to Mylyn, and still relevant. Written by the Mik Kirsten who is the Mylyn project lead, it is a very clear explanation of something quite unique. Lots of pretty pictures showing it in action too. * *Mylyn Part one - Integrated Task Management *Mylyn Part two - Automated Context Management A: Good tip, Uri. Recent versions of Mylyn now display a message in the package explorer "empty task context, unfocus or alt+click" when you activate a new task. As Uri points out, one way to get started is to unfocus using the toolbar button and work on your task normally for a while (with uninteresting resources automatically greyed-out). You can then focus the package explorer when you only want to see relevant resources. Other users prefer to keep the package explorer in focus mode and hold down the "Alt" key while clicking in the package explorer to add new resources to the active task context. In this way of working, only the interesting resources will be visible, but you can always un-focus to see everything if needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/150600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: JavaScript highlight table cell on tab in field I have a website laid out in tables. (a long mortgage form) in each table cell is one HTML object. (text box, radio buttons, etc) What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)? A: Use jQuery to make your life easier, and you can do something like this: $('#mytableid input').focus( function() { $(this).addClass('highlight'); }).blur( function() { $(this).removeClass('highlight'); }); This is basically saying when any input element in your table is under focus add the "highlight" class to it, and once it loses focus remove the class. Setup your css as: input.highlight { background-color: red; } and you should be set. A: This is the table I tested my code on: <table id="myTable"> <tr> <td><input type="text" value="hello" /></td> <td><input type="checkbox" name="foo" value="2" /></td> <td><input type="button" value="hi" /></td> </tr> </table> Here is the code that worked: // here is a cross-browser compatible way of connecting // handlers to events, in case you don't have one function attachEventHandler(element, eventToHandle, eventHandler) { if(element.attachEvent) { element.attachEvent(eventToHandle, eventHandler); } else if(element.addEventListener) { element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false); } else { element[eventToHandle] = eventHandler; } } attachEventHandler(window, "onload", function() { var myTable = document.getElementById("myTable"); var myTableCells = myTable.getElementsByTagName("td"); for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) { var currentTableCell = myTableCells[cellIndex]; var originalBackgroundColor = currentTableCell.style.backgroundColor; for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) { var currentChildNode = currentTableCell.childNodes[childIndex]; attachEventHandler(currentChildNode, "onfocus", function(e) { (e.srcElement || e.target).parentNode.style.backgroundColor = "red"; }); attachEventHandler(currentChildNode, "onblur", function(e) { (e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor; }); } } }); There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell. This would be much easier, it should go without saying, if you used a library to assist you in this work - jQuery and MochiKit are the two I favor, though there are others that would work just as well. Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job. A: Possibly: <script type="text/javascript"> //getParent(startElement,"tagName"); function getParent(elm,tN){ var parElm = elm.parentNode; while(parElm.tagName.toLowerCase() != tN.toLowerCase()) parElm = parElm.parentNode; return parElm; } </script> <tr><td><input type="..." onfocus="getParent(this,'td').style.backgroundColor='#400';" onblur="getParent(this,'td').style.backgroundColor='';"></td></tr>
{ "language": "en", "url": "https://stackoverflow.com/questions/150606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting unique rows in a set of two possibilities The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation: I will let my original explenation stand, but here's a set of sample data and the result i expect: Ok, so here's some sample data, i separated pairs by a blank line ------------- | Key | Col | (Together they from a Unique Pair) -------------- | 1 Foo | | 1 Bar | | | | 2 Foo | | | | 3 Bar | | | | 4 Foo | | 4 Bar | -------------- And the result I would expect, after running the query once, it need to be able to select this result set in one query: 1 - Foo 2 - Foo 3 - Bar 4 - Foo Original explenation: I have a table, call it TABLE where I have a two columns say ID and NAME which together form the primary key of the table. Now I want to select something where ID=1 and then first checks if it can find a row where NAME has the value "John", if "John" does not exist it should look for a row where NAME is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course. Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem. I could be completely blinded by my own code and line of thought but I just can't figure this out. A: This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN... mysql> select * from foo; +----+-----+ | id | col | +----+-----+ | 1 | Bar | | 1 | Foo | | 2 | Foo | | 3 | Bar | | 4 | Bar | | 4 | Foo | +----+-----+ SELECT id , col FROM foo f1 WHERE col = 'Foo' OR ( col = 'Bar' AND NOT EXISTS( SELECT * FROM foo f2 WHERE f1.id = f2.id AND f2.col = 'Foo' ) ); +----+-----+ | id | col | +----+-----+ | 1 | Foo | | 2 | Foo | | 3 | Bar | | 4 | Foo | +----+-----+ A: You can join the initial table to itself with an OUTER JOIN like this: create table #mytest ( id int, Name varchar(20) ); go insert into #mytest values (1,'Foo'); insert into #mytest values (1,'Bar'); insert into #mytest values (2,'Foo'); insert into #mytest values (3,'Bar'); insert into #mytest values (4,'Foo'); insert into #mytest values (4,'Bar'); go select distinct sc.id, isnull(fc.Name, sc.Name) sel_name from #mytest sc LEFT OUTER JOIN #mytest fc on (fc.id = sc.id and fc.Name = 'Foo') like that. A: No need to make this overly complex, you can just use MAX() and group by ... select id, max(col) from foo group by id A: try this: select top 1 * from ( SELECT 1 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'John' union SELECT 2 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'Bruce' ) t order by num A: I came up with a solution myself, but it's kind of complex and slow - nor does it expand well to more advanced queries: SELECT * FROM users WHERE name = "bruce" OR ( name = "john" AND NOT id IN ( SELECT id FROM posts WHERE name = "bruce" ) ) No alternatives without heavy joins, etc. ? A: Ok, so here's some sample data, i separated pairs by a blank line ------------- | Key | Col | (Together they from a Unique Pair) -------------- | 1 Foo | | 1 Bar | | | | 2 Foo | | | | 3 Bar | | | | 4 Foo | | 4 Bar | -------------- And the result I would expect: 1 - Foo 2 - Foo 3 - Bar 4 - Foo I did solve it above, but that query is horribly inefficient for lager tables, any other way? A: Here's an example that works in SQL Server 2005 and later. It's a useful pattern where you want to choose the top row (or top n rows) based on a custom ordering. This will let you not just choose among two values with custom priorities, but any number. You can use the ROW_NUMBER() function and a CASE expression: CREATE TABLE T (id int, col varchar(10)); INSERT T VALUES (1, 'Foo') INSERT T VALUES (1, 'Bar') INSERT T VALUES (2, 'Foo') INSERT T VALUES (3, 'Bar') INSERT T VALUES (4, 'Foo') INSERT T VALUES (4, 'Bar') SELECT id,col FROM (SELECT id, col, ROW_NUMBER() OVER ( PARTITION BY id ORDER BY CASE col WHEN 'Foo' THEN 1 WHEN 'Bar' THEN 2 ELSE 3 END ) AS RowNum FROM T ) AS X WHERE RowNum = 1 ORDER BY id A: You can use joins instead of the exists and this may improve the query plan in cases where the optimizer is not smart enough: SELECT f1.id ,f1.col FROM foo f1 LEFT JOIN foo f2 ON f1.id = f2.id AND f2.col = 'Foo' WHERE f1.col = 'Foo' OR ( f1.col = 'Bar' AND f2.id IS NULL ) A: In PostgreSQL, I believe it would be this: SELECT DISTINCT ON (id) id, name FROM mytable ORDER BY id, name = 'John' DESC; Update - false sorts before true - I had it backwards originally. Note that DISTINCT ON is a PostgreSQL feature and not part of standard SQL. What happens here is that it only shows you the first row for any given id that it comes across. Since we order by weather the name is John, rows named John will be selected over all other names. With your second example, it would be: SELECT DISTINCT ON (key) key, col FROM mytable ORDER BY key, col = 'Foo' DESC; This will give you: 1 - Foo 2 - Foo 3 - Bar 4 - Foo
{ "language": "en", "url": "https://stackoverflow.com/questions/150610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to select from Varchar where where `Value` is not part of a group I'm trying to do this SELECT `Name`,`Value` FROM `Constants` WHERE `Name` NOT IN ('Do not get this one'|'or this one'); But it doesn't seem to work. How do I get all the values, except for a select few, without doing this: SELECT `Name`,`Value` FROM `Constants` WHERE `Name` != 'Do not get this one' AND `Name` != 'or this one' The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query? A: You should put the constants in a table and then do a select statement from that table. If you absolutely don't want a permanent table you can use a temp table. And if don't want to do that, you can use the IN syntax: NOT IN ('one', 'two') A: It's IN('foo', 'bar'), with a comma, not a pipe. A: The IN syntax uses comma-seperated lists SELECT `Name`,`Value` FROM `Constants` WHERE `Name` NOT IN ('Do not get this one','or this one');
{ "language": "en", "url": "https://stackoverflow.com/questions/150622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby off the rails Sometimes it feels that my company is the only company in the world using Ruby but not Ruby on Rails, to the point that Rails has almost become synonymous with Ruby. I'm sure this isn't really true, but it'd be fun to hear some stories about non-Rails Ruby usage out there. A: Ruby with a homebrew extension written in C++ does all the heavy pixel pushing for my photography processing. I was using Python+numpy but when doing artsy stuff, Ruby is just more fun. Also the relative lack of, or lesser maturity of, good image processing libraries makes me feel less like i'm reinventing wheels. I am clueless about Rails, other than i've heard of it, have a fuzzy idea what it is, and actually have a book on it (unopened) A: We use Watir (Ruby library) to test our .net web application. A: Check out Shoes, a simple API for building GUIs in Ruby aimed at novice programmers. A: Or you could use Ruby to make music ala Giles Bowkett's Archaeopteryx. This presentation by Giles about Archaeopteryx is one of the best presentations ever. I highly recommend it. A: RubyCocoa and MacRuby. Possible to make full Cocoa-based GUI apps without Rails. And then you get to use Interface Builder, too. A: I worked on a museum project last year that used a lot of Ruby. (http://http://ourspace.tepapa.com/home) The part that I spent most of my time on was an interactive floor map. The Map on the floor has sensors so when people walk on it lights are triggered and displays in the wall show images or videos and audio tracks are played. All the control code for this part of the exhibit is ruby. I wrote C interfaces with ruby wrappers to communicate with the floor sensors and the lighting controllers. The system queries a MYSQL database for the media files to be displayed and then tells computers in the walls to play the media via UDP. It's the most reliable part of the entire exhibit. Ruby was used for the other major part of the exhibit, the Wall though I didn't have much to do with that. Most of the graphics were prototyped in ruby using interfaces to OpenGL, a bit of Cocoa and a physics library before being ported to pure Obj-C. A: Puppet and Chef: DevOps I didn't see a mention of Puppet or Chef in the 30 answers that preceded my arrival. Ruby appears to dominate current work in cloud automation and is the base, extension, and templating language of these two big players. They are used primarily to distribute system and application configuration information for server arrays and for general IT workstation management. The DevOps field is quite Ruby-aware. Today, Perl has a competitor. While a really simple script may often still be written directly for sh(1), a complex task now might be done in Ruby rather than Perl. A: One of the huge benefits of Ruby is the ability to create DSLs very easily. Ruby allows you to create "business rules" in a natural language way that is usually easy enough for a business analyst to use. Many Ruby apps outside of web development exist for this purpose. I highly recommend Googling "ruby dsl" for some excellent reading, but I would like to leave you with one post in particular. Russ Olsen wrote a two part blog post on DSLs. I saw him give a presentation on DSLs and it was very good. I highly recommend reading these posts. I also found this excellent presentation on Ruby DSLs by Obie Fernandez. Highly recommended reading! A: The only site I've done with Ruby at work is using Rails, but I'd like to try Merb. Other than that I do a lot of little utility programs in Ruby - for instance an app that reads RSS feeds and imports new posts into a dabase. It's fun, so I also write some dumb stuff just because it's so quick. Yesterday I wrote an app to play the Monty Hall problem 100,000 times to help a friend convince her professor that switching is the correct strategy. A: I almost take insult that ruby is a rails thing. It is like back when CGI was the latest trend and everyone figured that if you knew perl you must be doing it only because you programmed CGI apps. Ruby is just a scripting language for me, although not as mature as python so I somewhat regret having to jump through some of its hoops and recent changes, I still like it and use it. Although I work in a java shop and therefore groovy is the ideal choice for a scripting language, I still use ruby at home and for throw away scripts that aren't needed to be shared at work. I was considering getting into RoR from all the buzz and how quick/simple it is, but after looking over rails I didn't see anything at all that was amazing or even the least bit innovative or rapidly fast about its development compared to any other framework. The only benefit I saw was that I could code in ruby, which would be nice, but initial setup, server maintenance and scaling is more difficult, thus re-offsetting the pleasure of coding in ruby. A: I created a presentation -- coincidentally named Off The Rails -- to discuss Rack-based web applications: https://github.com/alexch/Off-The-Rails The git repo includes slides in Markdown format and sample code (in the form of running applications and middleware). Here's the abstract: Ruby on Rails is the most popular web application framework for Ruby. But it's not the only one! If you think Rails is too big, or too opinionated, or too anything, you might be happy to learn about the new generation of so-called microframeworks built on Rack. And since Rails 3 is itself a Rack app, you don't have to give up Rails to get the benefit of Sinatra routes or Grape APIs. And here are some references: * *This talk lives at https://github.com/alexch/off-the-rails *Yehuda's #10 Favorite Thing About Ruby *Rack * *rack-test *rack-client *Sinatra *Grape *Vegas *Siesta *Rerun Hope you find it useful! A: I'm mostly a Web developer, and I learned Ruby to use Rails, but I like the language so much that I started developing a desktop Swing application in Ruby, using JRuby and Monkeybars. I'm competent in Java, but don't much like using it, and the Swing API is horrible, so putting Ruby on top has been a big win. A: We mainly use rails, but we have plenty of other non-rails ruby things - for example a standalone authentication daemon thing for centralized authentication of users, and an 'image processing server' which runs arbitrary numbers of ruby processes to process images in parallel. Oh, and don't forget good old Rake :-) A: Ruby is also used for Desktop application. Especially the use of JRuby to develop Swing desktop application. A: I've used Ruby at work for * *A data extractor, generating csv files from binary output. *A .ini file generator, turning a simple syntax into a repetitive .ini format. *A simple TCP/IP server, acting as stand-in for the customer's system during testing. A: We use Ruby to implement our test automation software. This includes test framework and driver code for Selenium RC, WATIR and AutoIT. Ruby is powerful enough to create comprehensive applications that can interface with Test tools like Selenium or WATIR, while at the same time reading from data files, interacting with a remote Windows UI and performing near transparent network communication. All while running on Windows or Linux. The uncluttered syntax makes it ideal for new and inexperienced programmers to read. While its totally OO nature makes it easy for these same programmers to apply good (recently learned) OO techniques, from the start. The flexible nature of Ruby's syntax also makes the use and creation of DSLs much easier. This allows less-technical people to get invovled, read and possibly create there own tests. A: I have used Ruby for code generation of C# and T-SQL stored procedures in a project with unstable requirements. The data model was encoded in a YAML file and .erb templates were used for the classes and stored procedures. It also allowed for a much more DRY solution than would have been possible with straight C# as repetitve code could be factored out into a single method in the code generator. A: Where I work, we use Ruby to do a number of different one-off type batch jobs. One example of that is a job that interacts with Amazon's S3 service. At the time, the Ruby S3 library was probably the easiest one out there for us to get up and running in a short amount of time. A: I wrote an order processing expert system (see DSL answer as well), converted 100k lines of customer specific perl into about 10k lines of ruby handling dozens of customers. No web components at all, no Rails. A: I am a webdriver user. ruby is used by webdriver for automating the build process thanks to rake. see http://code.google.com/p/webdriver/ for details A: Heh, great question. I used Ruby to convert Excel spreadsheet airport facility data to sqlite3 for the android phone platform while making an app for pilots. A: I use Ruby with Sinatra which is much simpler than Rails. I did use Rails but just found that it has turned into a bit of a monster, although Rails is still amazing compared to web frameworks available for Java. The main feature of Ruby that I love however is "eval" and "method_missing", which Rails actually uses for example in ActiveRecord so that you can use the amazing "find_by-field-name-" queries. A: I used Ruby for a lot of back-end code simply because I was the only person who was tasked to do it and needed a nice clean language that allowed me to be very productive and write easy to maintain code. I find Ruby allows me to do that easier than Perl and Python. Other people's mileage might vary on that but it works well for me. Besides that, I like how Sequel and Nokogiri work. I also used ActiveRecord for a while separately from Rails. A: We use some Ruby for file manipulation but have not been able to incorporate rails yet. A: I've used Ruby a lot professionally for quick scripts for things like shuffling files around. I'm the same way in that I was using Ruby first before touching Rails at all. A: In Boulder there was an excellent group of Ruby users who met monthly. This point was made - that Ruby does have an existence beside its use in Rails. Plain Ruby users do exist, are begging for attention, have neat things to show, and can find each other at user group meetings. They also had better pizza than the Python group, who met also the same day of the month. Can only pick one... A: While we do have several Rails apps at work, we also use Ruby for some fairly intensive non-web stuff. We've got an SMS delivery daemon, which pulls messages from a queue and then delivers them, and credit card processing daemon which other apps can call out to, which makes sure there's a central audit trail. A: I use Ruby extensively in my work, and none of it is Rails (or even web) based. My domain is usually client-side Windows applications (wxRuby GUI) and scripts, automating Excel, Internet Explorer, SQL Server queries and report generation (win32ole COM automation). I also use the sqlite, pdf-writer, and gruff libraries for various data munging and graph generation tasks. Rails' success has been great for Ruby, but I agree that Rails has received so much attention that Ruby's value beyond the web is often overlooked. A: We are mainly a C++ shop, but we've found several areas where Ruby has proven quite useful. Here are a few: * *Code Generation - Built several DSLs to generate C++/Java/C# code from single input files *Build Support * *scripts to generate Makefiles for unix from Visual Studio Project Files *scripts for building projects and formatting the output for Cruise Control *scripts for running our unit tests and formatting the output for Cruise Control *scripts for manipulating Visual Studio projects and solutions from the command line *Integration Tests - We can crank out tests much quicker and cleaner using Ruby than C++ *QA's entire testing suite is written in Ruby Ruby is basically my go to tool for where it makes sense. And it makes sense in a lot of places. A: Google Sketchup uses Ruby as an embedded scripting language. You can use it to perform all sorts of 3d modeling and import/export tasks. The scripting works with the free version and there's even decent documentation. A: I myself use both ruby on its own and combined with the framework rails. I made a ruby application which daily pulls all the highscores from a website and puts it in a mysql database. It is sofar the first and only application i made in ruby on it's own i made A: I use Rails a lot at work, but for smaller applications or simple REST-based services I tend to use Sinatra. I'm also writing text-adventure game in Ruby for fun. A: At work I do all my scripting for Windows with Ruby. Thanks to that I can say bye bye to Dos script A: Other than Rails I've been using ruby extensively in the following small/medium projects: * *In large hierarchical text file parsing (to some extent similar to YAML structure) *Specialized small range web-spiders. *Three Sinatra apps. A: Ruby is hugely powerfull, and Rails was a good proof-of-concept of it's power applied to web-services. Nonetheless, Ruby continues (and will continue) to become more widespread in different contexts, like system-administration, scripting, automation, ... The thing was that in some point along the way, Rails got so much fame that "shadowed" Ruby and make it look like that it was Ruby following Rails. But as the number of answers in this post prove it, Ruby is much more than Rails. I too feel an "itch" when I'm searching about Ruby, and have to constantly deviate Rails info that gets in the way... but hey, Rails also contributed a lot to the Ruby growth and marketing :) A: I haven't done any non-Rails Ruby web dev, but all of my Project Euler solutions are in Ruby, as well as some other small projects, like my IRC bot. A: Does part of Rails count? We've used Ruby for an ETL application and plugged in ActiveRecord just for its model validations. A: I have inherited a legacy application that supports mobile for some well-known dating sites (which I won't name due to confidentiality). The legacy application uses Ruby but not Rails. The original application uses a predecessor to Rails, called "Merb" (https://en.wikipedia.org/wiki/Merb) Part of the application has been ported to use different technology to separate the technology into a backend and frontend layer. The backend layer uses pure ruby and the front-end uses ReactJS with some NodeJS integration.
{ "language": "en", "url": "https://stackoverflow.com/questions/150638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "114" }
Q: When ThreadPool.QueueUserWorkItem returns false The MSDN states that the method returns true if the method is successfully queued; NotSupportedException is thrown if the work item is not queued. For testing purposes how to get the method to return false? Or it is just a "suboptimal" class design? A: In looking at the source code in Reflector, it seems the only part of the code that could return "false" is a call to the following: [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool AdjustThreadsInPool(uint QueueLength); A: This is probably a case of "reserved for future use". You may want to treat it as failure, but it'll be hard to test. I pretty much treat this method as a void/Sub. A: It is imaginable that the entire API (thread-pools) becomes obsolete, when the Task Parallel Library (TPL) arrives. A: true if the method is successfully queued; NotSupportedException is thrown if the work item is not queued. Treat a return false in the same way that you treat a NotSupportedException. To get it to return false, use a mock method or object. You want to be testing your own code that you wrote, not the underlying windows code. I'm sure microsoft have plenty of their own tests already for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/150645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How Do I Create a New Excel File Using JXL? I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online. A: I know that it's a very old question. However, I think I can contribute with an example that also adds the cell values: /** * * @author Almir Campos */ public class Write01 { public void test01() throws IOException, WriteException { // Initial settings File file = new File( "c:/tmp/genexcel.xls" ); WorkbookSettings wbs = new WorkbookSettings(); wbs.setLocale( new Locale( "en", "EN" ) ); // Creates the workbook WritableWorkbook wwb = Workbook.createWorkbook( file, wbs ); // Creates the sheet inside the workbook wwb.createSheet( "Report", 0 ); // Makes the sheet writable WritableSheet ws = wwb.getSheet( 0 ); // Creates a cell inside the sheet //CellView cv = new CellView(); Number n; Label l; Formula f; for ( int i = 0; i < 10; i++ ) { // A n = new Number( 0, i, i ); ws.addCell( n ); // B l = new Label( 1, i, "by" ); ws.addCell( l ); // C n = new Number( 2, i, i + 1 ); ws.addCell( n ); // D l = new Label( 3, i, "is" ); ws.addCell( l ); // E f = new Formula(4, i, "A" + (i+1) + "*C" + (i+1) ); ws.addCell( f ); } wwb.write(); wwb.close(); } } A: First of all you need to put Jxl Api into your java directory , download JXL api from http://www.andykhan.com/ extract it,copy jxl and paste like C:\Program Files\Java\jre7\lib\ext. try { String fileName = "file.xls"; WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName)); WritableSheet writablesheet1 = workbook.createSheet("Sheet1", 0); WritableSheet writablesheet2 = workbook.createSheet("Sheet2", 1); WritableSheet writablesheet3 = workbook.createSheet("Sheet3", 2); Label label1 = new Label("Emp_Name"); Label label2 = new Label("Emp_FName"); Label label3 = new Label("Emp_Salary"); writablesheet1.addCell(label1); writablesheet2.addCell(label2); writablesheet3.addCell(label3); workbook.write(); workbook.close(); } catch (WriteException e) { } A: After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found: try { String fileName = "file.xls"; WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName)); workbook.createSheet("Sheet1", 0); workbook.createSheet("Sheet2", 1); workbook.createSheet("Sheet3", 2); workbook.write(); workbook.close(); } catch (WriteException e) { } A: Not sure if you need to stick with JXL, but the best library for handling Excel files is Apache's POI HSSF. I think there are plenty of examples on the website I provided, but if you need further assistence, let me know. I may have a few examples laying around. Just out of curiosity, POI stands for Poor Obfuscation Interface and HSSF is Horrible SpreadSheet Format. You see how much Apache loves Microsoft Office formats :-) A: public void exportToExcel() { final String fileName = "TodoList2.xls"; //Saving file in external storage File sdCard = Environment.getExternalStorageDirectory(); File directory = new File(sdCard.getAbsolutePath() + "/javatechig.todo"); //create directory if not exist if(!directory.isDirectory()){ directory.mkdirs(); } //file path File file = new File(directory, fileName); WorkbookSettings wbSettings = new WorkbookSettings(); wbSettings.setLocale(new Locale("en", "EN")); WritableWorkbook workbook; try { workbook = Workbook.createWorkbook(file, wbSettings); //Excel sheet name. 0 represents first sheet WritableSheet sheet = workbook.createSheet("MyShoppingList", 0); Cursor cursor = mydb.rawQuery("select * from Contact", null); try { sheet.addCell(new Label(0, 0, "id")); // column and row sheet.addCell(new Label(1, 0, "name")); sheet.addCell(new Label(2,0,"ff ")); sheet.addCell(new Label(3,0,"uu")); if (cursor.moveToFirst()) { do { String title =cursor.getString(0) ; String desc = cursor.getString(1); String name=cursor.getString(2); String family=cursor.getString(3); int i = cursor.getPosition() + 1; sheet.addCell(new Label(0, i, title)); sheet.addCell(new Label(1, i, desc)); sheet.addCell(new Label(2,i,name)); sheet.addCell(new Label(3,i,family)); } while (cursor.moveToNext()); } //closing cursor cursor.close(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } workbook.write(); try { workbook.close(); } catch (WriteException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/150646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Java obfuscation - ProGuard/yGuard/other? This is along similar lines as these recent questions: Best Java Obfuscation Application For Size Reduction Creating non-reverse-engineerable Java programs However, one ends up recommending yGuard and the other ProGuard but neither mention both. I wonder if we could get a comparison of each one and hear peoples experiences from both sides of the fence. Looking at this comparison chart on the ProGuard website its clearly angled towards ProGuard. But what about real-world experience of each - which one produces smaller output? which one is harder to decompile from? what Java versions are supported by each? Personally I'm particularly interested from a J2ME point of view but please don't limit the discussion to that. A: Results for my project. * *Obfuscation - both fine. *Optimisation - ProGuard produced 20% faster code (for the measured app bottleneck). *Compactness - ProGuard about 5% smaller. *Configuration / Ant - YGuard is much easier to configure. So, I'd advise ProGuard - but configuration and ant integration could definitely be improved. A: Proguard is a better product; especially if you take the time to go through the settings for J2ME. Specifically for J2ME there is a far better (commercial) product called mBooster I've been getting around 25% improvement in size on my application after its been through Proguard. This is mainly to do with the better Zip compression on the Jar file and comprehensive support for class merging and preverification. A: My opinion is - ProGuard is better. Output is smaller a bit. Optimizing is better and much faster. Decompiling is simple in both cases. Well, i mean, if u know Java well and really know business-logic of what you're decompiling, there is no problem to get it back to sources from obfuscated classes. So, my opinion is ProGuard is better.
{ "language": "en", "url": "https://stackoverflow.com/questions/150653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to create a custom log filter in enterprise library 4.0? I am using Enterprise Library 4.0 and I can't find any documentation on creating a custom logging filter. Has anyone done this or seen any good online documentation on this? A: Using Custom Filters in the Enterprise Library Logging Block Great Article. A: Perusing through EntLib's source code would probably help you if the documentation is scant; it's well-written and well-commented.
{ "language": "en", "url": "https://stackoverflow.com/questions/150666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Do you use Microformats, RDF, Dublin Core or another type of semantic markup? Do you use any of these technologies? Which ones are current and hence sensible to include in a site? Documentation on any seems to be relatively sparse, and usage of any of them limited, as search engines get better, are they even relevant any more? A: I use microformats whenever I can. Usually it just makes sense anyway, as frequently when I have an address block, I may want to style some elements differently then other elements, and that makes it super easy. It's not like microformats are that hard to figure out. There has been a couple of instances where, because I was using a microformat, I was able to re-use the markup of a certain portion of a site somewhere else (as an include), and not have to change the markup, only the styling. Finally, ever since I really stated exploring microformats, I got better at writing semantic markup and better at naming CSS classes. A: I use SIOC, FOAF, DOAP and some other lightweight RDF vocabularies. A popular trend these days is to embed RDF in web documents using RDFa. At that point the border b/w RDF vocabs and microformats starts to disapper. With search engines getting better the need for semantic markup will rather rise. For an example, take a look at microformats and vocabs that Yahoo SearchMonkey apps can use: SearchMonkey vocabularies Once search engines can make sense of richer data (even if at first it is just to display richer data about a match found) people will also get more motivation to use semantic markup. What additional documentation do you think is missing and would be useful to have? A: I've used all three, but of the lot I'd have to say microformats have the most momentum these days. It has the advantage of being very easy to implement, even as an afterthought, on existing sites. And while there don't seem to be a lot of microformat consumers in the wild at this point, that situation is starting to change with the next generation of browsers. As for the relevance of semantic markup in general, anything that makes it easier to automate the gathering of data is going to contribute to a richer ecosystem of applications that use that data. Relying on search engines for this kind of contextual processing does not address the needs of more focused or niche applications. A: We baked microformats in the publisher tools we develop at Praized (mostly in the plugin tools we provide to bloggers) Since the core Object in our system is "places", we thought it was sensible for us to output microformats. A: I use RDFa as it has the important feature of being able to say anything, even really bizarre or obscure facts (such as the properties of archaeological finds, or the number of friends Paris Hilton has on MySpace), and doing so unambiguously. I was recently working on a Search Monkey plugin to display VCal data embedded as RDFa, and stumbled upon a couple of cases where you just need that extra little bit of data to connect things. They were: connecting a presentation to the slides used during the presentation, and connecting a web page to its primary topic so you can tell exactly what the page is about. Its difficult to see how you would answer those use cases with Microformats, there is neither context or precision in the markup. Over time I'll want to add more detail to my RDFa to help different groups of people find my pages and buy stuff. Dublin Core is available in RDF and RDFa, but the old DC meta tags have similar issues to Microformats and even lower active use as far as I know. I agree with CaptSolo that while DC and other meta data standards are old hat, RDFa is a growth area. RDFa.info chronicle each new user as it comes along. I'd go further and predict that microformats will quickly die off as more people 'get' RDF and more RDF-aware tools are produced. A: At yahoo we support RDFa, eRDF, and microformats in page's markup. To see what we have harvested, install my SearchMonkey plugin, and then do any search using Yahoo. You should see an infobar below showing the semantic data. I can't post links since I'm a new user, but goto the SearchMonkey gallery, and look for "Structured Data Display". Its under technology.
{ "language": "en", "url": "https://stackoverflow.com/questions/150669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: AJAX.NET Subscribe to Reorderlist ItemCommand or DeleteCommand? I would like to subscribe to the ItemCommand event of a Reorderlist I have on my page. The front end looks like this... <cc1:ReorderList id="ReorderList1" runat="server" CssClass="Sortables" Width="400" OnItemReorder="ReorderList1_ItemReorder" OnItemCommand="ReorderList1_ItemCommand"> ... <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="delete.jpg" CommandName="delete" CssClass="playClip" /> ... </cc1:ReorderList> in the back-end I have this on Page_Load ReorderList1.ItemCommand += new EventHandler<AjaxControlToolkit.ReorderListCommandEventArgs>(ReorderList1_ItemCommand); and this function defined protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { if (e.CommandName == "delete") { //do something here that deletes the list item } } } Despite my best efforts though, I can't seem to get this event to fire off. How do you properly subscribe to this events in a ReorderList control? A: this works: <cc2:ReorderList ID="rlEvents" runat="server" AllowReorder="True" CssClass="reorderList" DataKeyField="EventId" DataSourceID="odsEvents" PostBackOnReorder="False" SortOrderField="EventOrder" OnDeleteCommand="rlEvents_DeleteCommand"> ... <asp:ImageButton ID="btnDeleteEvent" runat="server" CommandName="Delete" CommandArgument='<%# Eval("EventId") %>' ImageUrl="~/images/delete.gif" /> ... </cc2:ReorderList> code behind: protected void rlEvents_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e) { // delete the item // this will give you the DataKeyField for the current record -> int.Parse(e.CommandArgument.ToString()); //rebind the ReorderList } A: Since your ImageButton's CommandName="delete" you should be hooking up to the DeleteCommand event instead of ItemCommand.
{ "language": "en", "url": "https://stackoverflow.com/questions/150687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find the prefix substring which gives best compression Problem: Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length. Example: "foo", "fool", "bar" The result is: "foo" as the base string with the strings "\0", "\0l", "bar" and a total length of 9 bytes. "\0" is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte. A naive algorithm would look like: for string in list for i = 1, i < length of string calculate total length based on prefix of string[0..i] if better than last best, save it return the best prefix That will give us the answer, but it's something like O((n*m)^2), which is too expensive. A: Use a forest of prefix trees (trie)... f_2 b_1 / | o_2 a_1 | | o_2 r_1 | l_1 then, we can find the best result, and guarantee it, by maximizing (depth * frequency) which will be replaced with your escape character. You can optimize the search by doing a branch and bound depth first search for the maximum. On the complexity: O(C), as mentioned in comment, for building it, and for finding the optimal, it depends. If you order the first elements frequency (O(A) --where A is the size of the languages alphabet), then you'll be able to cut out more branches, and have a good chance of getting sub-linear time. I think this is clear, I am not going to write it up --what is this a homework assignment? ;) A: I would try starting by sorting the list. Then you simply go from string to string comparing the first character to the next string's first char. Once you have a match you would look at the next char. You would need to devise a way to track the best result so far. A: Well, first step would be to sort the list. Then one pass through the list, comparing each element with the previous, keeping track of the longest 2-character, 3-character, 4-character etc runs. Then figure is the 20 3-character prefixes better than the 15 4-character prefixes.
{ "language": "en", "url": "https://stackoverflow.com/questions/150690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where are all the places Sql Reporting Server Logs Errors? It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place? A: For SSRS 2008 R2: C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\LogFiles A: As far as I know SSRS logs to the Event Log, the filesystem and its own database. The database is typically the most easily available one. You just login to the ReportServer database and execute select * from executionlog This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary): C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\LogFiles These are quite verbose and not really fun to look through. But they do log a lot of stuff. If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel) Edit Found a nice link: https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources
{ "language": "en", "url": "https://stackoverflow.com/questions/150695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }