qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
251,155
<p>I am developing an iPhone application that persists data to a SQLite3 database. </p> <p>For each row I persist I wish to include a 'created date' and a 'last modified date'</p> <p>My question is what is the recommend approach for storing this information in a table? </p> <p>The properties are represented as NSDate in my application but I am unsure how to represent this information in my table.</p> <p>It appears that SQLite3 provides a DATETIME type but does not have a native understanding of how to parse this information.</p> <p>Any help would be much appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 251194, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.sqlite.org/datatype3.html\" rel=\"nofollow noreferrer\">According to the docs</a> there's no DATETIME data type! I use a <em>real</em> data type and convert an NSDate to a <em>real</em> using the <em>timeIntervalSinceReferenceDate</em> method.</p>\n" }, { "answer_id": 251197, "author": "drewh", "author_id": 1967, "author_profile": "https://Stackoverflow.com/users/1967", "pm_score": 5, "selected": true, "text": "<p>I typically use a double, something like:</p>\n\n<pre><code>sqlite3_bind_double(statement, index, [dateObject timeIntervalSince1970]);\n</code></pre>\n\n<p>where dateObject is an NSDate*. Then, when getting the data out of the DB, use</p>\n\n<pre><code>[NSDate dateWithTimeIntervalSince1970:doubleValueFromDatabase];\n</code></pre>\n" }, { "answer_id": 251371, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 3, "selected": false, "text": "<p>Store as a typical C-time (e.g. the time_t/int value returned by time()) value in an UNSIGNED INT column. Convert like <b>drewh</b> said with NSDate: </p>\n\n<pre><code>- timeIntervalSince1970\n- dateWithTimeIntervalSince1970:(double)value\n</code></pre>\n\n<p>Except store as an integer, unless you need sub-second granularity (which, generally, for created-on/last-modified, is overkill). Unsigned ints are a lot smaller and easier to process than doubles. While this may not matter in most desktop and web applications anymore, it certainly helps on the iPhone. Every little bit helps.</p>\n\n<p>One side benefit of C-times that most people don't realize is that they're timezone-agnostic. If you ever need to support multiple timezones, this comes in handy.</p>\n" }, { "answer_id": 251936, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 3, "selected": false, "text": "<p>I convert to/from ISO8601 strings: <a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/ISO_8601</a></p>\n\n<p>Far more readible/hackable than time intervals.</p>\n" }, { "answer_id": 1711697, "author": "xyzzycoder", "author_id": 207213, "author_profile": "https://Stackoverflow.com/users/207213", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/1711504/how-get-datetime-column-in-sqlite-objecite-c/1711591#1711591\">How get a datetime column in SQLite with Objective C</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3596/" ]
I am developing an iPhone application that persists data to a SQLite3 database. For each row I persist I wish to include a 'created date' and a 'last modified date' My question is what is the recommend approach for storing this information in a table? The properties are represented as NSDate in my application but I am unsure how to represent this information in my table. It appears that SQLite3 provides a DATETIME type but does not have a native understanding of how to parse this information. Any help would be much appreciated. Thanks in advance.
I typically use a double, something like: ``` sqlite3_bind_double(statement, index, [dateObject timeIntervalSince1970]); ``` where dateObject is an NSDate\*. Then, when getting the data out of the DB, use ``` [NSDate dateWithTimeIntervalSince1970:doubleValueFromDatabase]; ```
251,181
<p>I have a DTS package that drops a table then creates it and populates it but sometimes something happens and the package fails after the drop table. If it's rerun it fails cuz the table hasn't been created yet. </p> <p>Is there something like "if exists" for SQLServer 2000 like in MySQL?</p> <p>thanks.</p>
[ { "answer_id": 251190, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<pre><code>IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))\nDROP TABLE TableName;\nGO\n</code></pre>\n\n<p>You can check a <a href=\"http://msdn.microsoft.com/en-us/library/ms177596.aspx\" rel=\"nofollow noreferrer\">list of type definitions in the sys.objects table here</a> if you want to check if other objects in your database exist. </p>\n" }, { "answer_id": 251201, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 1, "selected": false, "text": "<p>You need to check the <a href=\"http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx\" rel=\"nofollow noreferrer\">sysobjects</a> table </p>\n" }, { "answer_id": 251206, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>The following works, just replace TABLENAME with your table</p>\n\n<pre><code>IF EXISTS( SELECT * FROM dbo.sysobjects where id = object_id(N'TABLENAME') AND OBJECTPROPERTY(id, N'IsTable') = 1)\nBEGIN\n DROP TABLE TABLENAME\nEND\n</code></pre>\n" }, { "answer_id": 251210, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 6, "selected": true, "text": "<p>Or quicker:</p>\n\n<pre><code>IF OBJECT_ID('temp_ARCHIVE_RECORD_COUNTS') IS NOT NULL \n DROP TABLE temp_ARCHIVE_RECORD_COUNTS \n</code></pre>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/aa276843%28v=sql.80%29.aspx\" rel=\"noreferrer\">OBJECT_ID - MSDN Reference - SQL Server 2000</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms190328(v=SQL.100).aspx\" rel=\"noreferrer\" title=\"MSDN SQL Server 2000\">OBJECT_ID - MSDN Reference - SQL Server 2008</a></li>\n</ul>\n" }, { "answer_id": 251219, "author": "user8605", "author_id": 8605, "author_profile": "https://Stackoverflow.com/users/8605", "pm_score": 2, "selected": false, "text": "<p>Sure:</p>\n\n<p><code>IF OBJECT_ID('YOURTABLENAME') IS NOT NULL</code></p>\n\n<p>where <code>YOURTABLENAME</code> is whatever the name of your table is.</p>\n\n<p>If it's a temp table, then just add <code>tempdb.#</code> before before the <code>OBJECT_ID</code> function call.</p>\n" }, { "answer_id": 251284, "author": "Mike Daniels", "author_id": 31339, "author_profile": "https://Stackoverflow.com/users/31339", "pm_score": 2, "selected": false, "text": "<p>One thing to remember when you drop and object and then add back to the database is also add any permissions back to the table. This has tripped us up a number of times. </p>\n\n<p>I up voted TracyNixon's answer. I would say you want to stay away from querying the sysobjects table directly because a Microsoft update could break that kind of code. You isolate yourself from that by using the OBJECT_ID function.</p>\n" }, { "answer_id": 251376, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 3, "selected": false, "text": "<p>Noone has mentioned this method yet:</p>\n\n<pre><code>if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME='MyTable') \nbegin \n drop table MyTable\nend\n</code></pre>\n\n<p>This is the most portable method - it works on at least MSSQL2000 up to MSSQL2008. </p>\n\n<p>The INFORMATION_SCHEMA tables are part of the SQL-92 standard.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I have a DTS package that drops a table then creates it and populates it but sometimes something happens and the package fails after the drop table. If it's rerun it fails cuz the table hasn't been created yet. Is there something like "if exists" for SQLServer 2000 like in MySQL? thanks.
Or quicker: ``` IF OBJECT_ID('temp_ARCHIVE_RECORD_COUNTS') IS NOT NULL DROP TABLE temp_ARCHIVE_RECORD_COUNTS ``` * [OBJECT\_ID - MSDN Reference - SQL Server 2000](http://msdn.microsoft.com/en-us/library/aa276843%28v=sql.80%29.aspx) * [OBJECT\_ID - MSDN Reference - SQL Server 2008](http://msdn.microsoft.com/en-us/library/ms190328(v=SQL.100).aspx "MSDN SQL Server 2000")
251,198
<p>I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage. For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app. If you provide a class, it would be fantastic.</p>
[ { "answer_id": 251220, "author": "dpurrington", "author_id": 5573, "author_profile": "https://Stackoverflow.com/users/5573", "pm_score": 5, "selected": true, "text": "<p>I don't know if you can do that, but you can change the thread priority of the executing thread via the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx\" rel=\"noreferrer\">Priority</a> property. You would set that by:</p>\n\n<pre><code>Thread.CurrentThread.Priority = ThreadPriority.Lowest;\n</code></pre>\n\n<p>Also, I don't think you really want to cap it. If the machine is otherwise idle, you'd like it to get busy on with the task, right? ThreadPriority helps communicate this to the scheduler.</p>\n" }, { "answer_id": 251229, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>You can slow down a loop by calling Thread.Sleep(milliseconds) within the loop. That hands the CPU back to the scheduler. </p>\n\n<p>But 'consuming too much CPU' makes me think you might have more fundamental problems. Is this thread polling and waiting for something else? If so, you should consider the use of Events or some other kernel-based signalling mechanism.</p>\n" }, { "answer_id": 252305, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 0, "selected": false, "text": "<p>I guess you need to query some kind of OS API to find out how much of the CPU are you consuming and take throttling decisions (like Thread.Sleep) from that on.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage. For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app. If you provide a class, it would be fantastic.
I don't know if you can do that, but you can change the thread priority of the executing thread via the [Priority](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx) property. You would set that by: ``` Thread.CurrentThread.Priority = ThreadPriority.Lowest; ``` Also, I don't think you really want to cap it. If the machine is otherwise idle, you'd like it to get busy on with the task, right? ThreadPriority helps communicate this to the scheduler.
251,204
<p>I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.</p>
[ { "answer_id": 251214, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 7, "selected": true, "text": "<pre><code>setTimeout(function() { $('#foo').fadeOut(); }, 5000);\n</code></pre>\n\n<p>The 5000 is five seconds in milliseconds.</p>\n" }, { "answer_id": 454387, "author": "Sampson", "author_id": 54680, "author_profile": "https://Stackoverflow.com/users/54680", "pm_score": 1, "selected": false, "text": "<p>You can avoid using setTimeout by using the fadeTo() method, and setting a 5 second delay on that.</p>\n\n<pre><code>$(\"#hideAfterFiveSeconds\").click(function(){\n $(this).fadeTo(5000,1,function(){\n $(this).fadeOut(\"slow\");\n });\n});\n</code></pre>\n" }, { "answer_id": 552551, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 5, "selected": false, "text": "<p>I use this pause plugin I just wrote</p>\n\n<pre><code>$.fn.pause = function(duration) {\n $(this).animate({ dummy: 1 }, duration);\n return this;\n};\n</code></pre>\n\n<p>Call it like this :</p>\n\n<pre><code>$(\"#mainImage\").pause(5000).fadeOut();\n</code></pre>\n\n<p>Note: you don't need a callback.</p>\n\n<hr>\n\n<p><strong>Edit: You should now use the <a href=\"http://api.jquery.com/delay/\" rel=\"nofollow noreferrer\">jQuery 1.4. built in delay()</a> method. I haven't checked but I assume its more 'clever' than my plugin.</strong></p>\n" }, { "answer_id": 1101950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've written a plugin to let you add a delay into the chain.</p>\n\n<p>for example $('#div').fadeOut().delay(5000).fadeIn(); // fade element out, wait 5 seconds, fade element back in. </p>\n\n<p>It doesn't use any animation hacks or excessive callback chaining, just simple clean short code.</p>\n\n<p><a href=\"http://blindsignals.com/index.php/2009/07/jquery-delay/\" rel=\"nofollow noreferrer\">http://blindsignals.com/index.php/2009/07/jquery-delay/</a></p>\n" }, { "answer_id": 2069155, "author": "Drew", "author_id": 217965, "author_profile": "https://Stackoverflow.com/users/217965", "pm_score": 4, "selected": false, "text": "<p>Previously you would do something like this </p>\n\n<pre><code>$('#foo').animate({opacity: 1},1000).fadeOut('slow');\n</code></pre>\n\n<p>The first animate isn't doing anything since you already have opacity 1 on the element, but it would pause for the amount of time.</p>\n\n<p>In jQuery 1.4, they have built this into the framework so you don't have to use the hack like above.</p>\n\n<pre><code>$('#foo').delay(1000).fadeOut('slow');\n</code></pre>\n\n<p>The functionality is the same as the original <code>jQuery.delay()</code> plugin <a href=\"http://www.evanbot.com/article/jquery-delay-plugin/4\" rel=\"noreferrer\">http://www.evanbot.com/article/jquery-delay-plugin/4</a></p>\n" }, { "answer_id": 2647806, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The best way is by using the jQuery delay method:</p>\n\n<p>$('#my_id').delay(2000).fadeOut(2000);</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.
``` setTimeout(function() { $('#foo').fadeOut(); }, 5000); ``` The 5000 is five seconds in milliseconds.
251,209
<p>I want to do validation on my business code. I'm thinking of 2 ways to do this.</p> <p>One, do the validation on my class property setters in the following fashion</p> <pre><code>class Student{ public string Name{ get { return _name; } set { if (value.IsNullOrEmpty) throw exception ... } } } </code></pre> <p>Now, the problem with this approach is that, validation code is run every time Name gets assigned, which we may not need, like when fill it in with data from DB.</p> <p>Two, which I prefer, put static methods on these entity classes, like</p> <pre><code>class Student { public **static** void ValidateName(**string name**) { if (string.IsNullorEmpty(name)) { throw ... } ... } </code></pre> <p>Notice I'm using a static method instead of a instance method, like</p> <pre><code>class Student{ public void Validate() { // validation logic on instance properties if (string.IsNullorEmpty(Name)) { throw ... } ... } </code></pre> <p>is because I'm not always getting a Student obj passed in, I do get primitive types like string name passed into a method often time, like</p> <pre><code>public static FindStudentByName(string name) { // here I want to first do validation Student.ValidateName(name); // query DB ... } </code></pre> <p>If I do get passed in a student obj, then of course I can do</p> <pre><code>public static AddStudent(Student s) { // call the instance method s.Validate(); } </code></pre> <p>Now, I'd like to keep things very simple, so I <strong>don't want</strong> to go any one of the following approaches</p> <ol> <li><p>Use attributes on properties, like [StringLength(25)]. </p> <p>One, because this requires reflection and affects performance, there are tricks to get performance hit low, but again I want to keep it simpler the better. </p> <p>Two, I want my site to be able to run in Medium Trust. As reflection as I understand it requires Full Trust.</p></li> <li><p>Use any of the validation blocks out there, like MS. Enterprise Library etc found on CodePlex.</p></li> </ol> <p>Now, I want to get your opinion on this, </p> <p>what are some of the potential problems with the approach I'm going with?<br> Would this approach perform better, more readable, easier to maintain than the other approaches? </p> <p>How are you doing validation on your middle tier?</p> <p>Thank a bunch!</p> <p>Ray. </p>
[ { "answer_id": 251221, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>Option two is something that doesn't actually enforce validation, at least not without you manually calling validate. Therefore consumers of your objects could violate the rules.</p>\n\n<p>I personally would go with something similar to your first example, as it ensures that ALL data is valid. it is an additional check on the DB side of things, but from what i have noticed, typically isn't a big deal.</p>\n" }, { "answer_id": 251254, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>I perform domain validation in the middle tier with a rules engine, very similar to the one <a href=\"http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx\" rel=\"nofollow noreferrer\">written about here</a>. A friend's project uses an approach similar to what you're proposing in your latter example and the end result is unmaintainable (brittle, hard to implement generic validation UIs). The rules engine approach is maintainable because it localizes all the validation and persistence rules in a single well organized location AND has each rule as a fully fledged class - but exposes the validation on domain classes similar to what you have proposed. Some people like dynamically compiling so they store them in a database for a high level of post-deployment configuration; in my case I like them compile time checked so there are rule definitions with lambdas exposed on a static class.</p>\n\n<p>I know this isn't in line with what you want to do, but asking how I would do it and saying other approaches aren't simple enough would be like saying \"how can you write reliable code, I want to keep it simple so unit tests are out of the question.\" To me treating each rule as its own class is good because its easier to maintain and document albeit more complex to implement.</p>\n" }, { "answer_id": 251268, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 1, "selected": false, "text": "<p>The approach you suggest seems to indicate that the set of validation should not be applied always. Which is ok. I've seen plenty of rules and validations we want 'most of the times' but not really always. So, the question becomes 'when do you want these validations to apply' ?</p>\n\n<p>Say that, for instance, you have some validations you <em>always</em> want to apply and some you want to verify only when... I don't know.. you're about to save to the storage (database).\nIn that case, the checks that apply always should be in the properties (see more on this below), and those that apply only when you're about to save to the storage should be in a method (maybe named along the lines of 'VerifyRulesForStorage') that will be called when appropriate (e.g. in the middle of your 'SaveToStorage' method).</p>\n\n<p>One thing worth considering, I think, is the duplication you risk incurring when you have the same validation across multiple entities. Be it in the property, or in a 'VerifyRulesForStorage' method, it is likely that you'll have the same check (e.g.: String.IsNullOrEmpty, or CheckItsANumber, or CheckItsOneOfTheAcceptedValues, etc etc) in many places, across many classes.\nOf course, you can resolve this via inheritance (e.g. all your entities inherit from a base Entity class that has methods implementing each type of check), or composition (probably a better approach, so that your entities' class tree is driven by other, more appropriate, considerations, e.g.: all your entities have a Validator object that implements all those checks).\nEither way, you might want to stay away from static methods, cine they tend to create problematic situations if you are Test-Driven (there are ways around, when needed).</p>\n\n<p>In our system, we actually have metadata describing the validation rules. The class' property name is used to retrieve the proper metadata, which then tells the system which rules to apply. We then have a validator object that instantiates the proper type of object to actually perform the validation, through a factory (e.g. we have one class implementing the IsRequiredString rule, one implementing the IsNumber rule, etc etc). Sounds like a lot of complexity, but, in a lrge system like ours, it was definitely worth it.</p>\n\n<p>Finally, the off-the-shelves libraries out there might be a good alternative. In our case they weren't because of particular requirements we had - but in general.. there are benefits in using a wheel someone else has developed (and will support) over building your own (trust me, I love to rebuild wheels when I can.. I'm just saying there are cases where each approach is better than the other).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32240/" ]
I want to do validation on my business code. I'm thinking of 2 ways to do this. One, do the validation on my class property setters in the following fashion ``` class Student{ public string Name{ get { return _name; } set { if (value.IsNullOrEmpty) throw exception ... } } } ``` Now, the problem with this approach is that, validation code is run every time Name gets assigned, which we may not need, like when fill it in with data from DB. Two, which I prefer, put static methods on these entity classes, like ``` class Student { public **static** void ValidateName(**string name**) { if (string.IsNullorEmpty(name)) { throw ... } ... } ``` Notice I'm using a static method instead of a instance method, like ``` class Student{ public void Validate() { // validation logic on instance properties if (string.IsNullorEmpty(Name)) { throw ... } ... } ``` is because I'm not always getting a Student obj passed in, I do get primitive types like string name passed into a method often time, like ``` public static FindStudentByName(string name) { // here I want to first do validation Student.ValidateName(name); // query DB ... } ``` If I do get passed in a student obj, then of course I can do ``` public static AddStudent(Student s) { // call the instance method s.Validate(); } ``` Now, I'd like to keep things very simple, so I **don't want** to go any one of the following approaches 1. Use attributes on properties, like [StringLength(25)]. One, because this requires reflection and affects performance, there are tricks to get performance hit low, but again I want to keep it simpler the better. Two, I want my site to be able to run in Medium Trust. As reflection as I understand it requires Full Trust. 2. Use any of the validation blocks out there, like MS. Enterprise Library etc found on CodePlex. Now, I want to get your opinion on this, what are some of the potential problems with the approach I'm going with? Would this approach perform better, more readable, easier to maintain than the other approaches? How are you doing validation on your middle tier? Thank a bunch! Ray.
I perform domain validation in the middle tier with a rules engine, very similar to the one [written about here](http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx). A friend's project uses an approach similar to what you're proposing in your latter example and the end result is unmaintainable (brittle, hard to implement generic validation UIs). The rules engine approach is maintainable because it localizes all the validation and persistence rules in a single well organized location AND has each rule as a fully fledged class - but exposes the validation on domain classes similar to what you have proposed. Some people like dynamically compiling so they store them in a database for a high level of post-deployment configuration; in my case I like them compile time checked so there are rule definitions with lambdas exposed on a static class. I know this isn't in line with what you want to do, but asking how I would do it and saying other approaches aren't simple enough would be like saying "how can you write reliable code, I want to keep it simple so unit tests are out of the question." To me treating each rule as its own class is good because its easier to maintain and document albeit more complex to implement.
251,218
<p>I'm using Wise Package Studio 7.0 SP2 on Windows XP.</p> <p>I've got an MSI Wrapped EXE installation that goes about happily installing some files and then running one of the files from the installation which we can refer to as app.exe.</p> <p>So on the "Execute Deferred" tab of the MSI Editor, I had to add the lines:</p> <pre><code>If Not Installed then Execute Installed Program app.exe (Action) End </code></pre> <p>This ensured that my app.exe would be run <em>only</em> on an installation and not during a modify/repair/removal. When app.exe runs, it conveniently adds itself to the system tray.</p> <p>I'm looking for something that will do the reverse during a removal. I want to stop the app.exe process thus removing it from the system tray.</p> <p>Currently my removal gets rid of all the files however the app.exe remains running and still shows up in the systems tray. I've looked at adding the conditional statement:</p> <pre><code>If REMOVE~="ALL" then *remove the app from the systray!* End </code></pre> <p>The conditional statement will let me do something only on a removal, however I'm not sure of the best approach to go about actually terminating the process. Is there an MSI command I can run that will let me do that? Should I write my own .exe that will do that?</p>
[ { "answer_id": 252627, "author": "Froosh", "author_id": 26000, "author_profile": "https://Stackoverflow.com/users/26000", "pm_score": 0, "selected": false, "text": "<p>You can insert VBscript elements into the MSI as custom actions. Something like this should do the job:</p>\n\n<pre><code>strMachine = \"localhost\"\nstrAppName = \"notepad.exe\"\n\nSet objProcesses = GetObject(\"winmgmts://\" &amp; strMachine).ExecQuery(\"SELECT * FROM Win32_Process WHERE Caption LIKE '\" &amp; strAppName &amp; \"'\")\n\nFor Each objProcess In objProcesses\n intRetVal = objProcess.Terminate(0)\nNext\n</code></pre>\n" }, { "answer_id": 252769, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 3, "selected": true, "text": "<p>6 months ago we were using VBScript actions to do the same thing, then right around the time that SP3 was released the objProcess.Terminate() function just refused to work on some machines. No matter what we did, it just froze. This happened on around 10% of our test machines so we were forced to find an alternative solution (who knows how many customers it might have frozen on!)</p>\n\n<p>My first discovery was the inbuilt (since Windows 2000) command TASKKILL\neg: <code>TASKKILL /IM app.exe /F</code> but as that seems to use similar means of killing a process as we used in VBScript, that method would also fail.</p>\n\n<p>So now we're using the <code>pskill.exe</code> tool from sysinternals, you need to use a command line switch to supress the license agreement prompt but other than that, it's been the most foolproof way of killing a running EXE that I've found.</p>\n\n<p>Of course the best solution would be to build your own EXE or DLL to do it should you happen to know a little C++ ;)</p>\n" }, { "answer_id": 1462543, "author": "Edward Brey", "author_id": 145173, "author_profile": "https://Stackoverflow.com/users/145173", "pm_score": 1, "selected": false, "text": "<p>Just terminating processes isn't sufficient, since that doesn't clean up the Windows Notification Area (however, Windows will clean up an icon with no matching process when the mouse next hovers over in). Yet one more reason why terminating apps abruptly is generally best reserved for debugging. Unfortunately, a more proper solution is also more involved. You could create a named event in the app and register a callback method to be called when it is set. The callback would close the app. Then you'd write a custom action that set the event and waited until process terminated.</p>\n\n<p>If you need to support cancellation (e.g. the user is prompted that he has unsaved changes and decides not to cancel), you may use another named event to indicate that, so the custom action may wait for either the process to end or a cancellation event, whichever comes first.</p>\n" }, { "answer_id": 4630759, "author": "RobH", "author_id": 21255, "author_profile": "https://Stackoverflow.com/users/21255", "pm_score": 0, "selected": false, "text": "<p>If your app.exe was created in house, you could add a command line that tells it to kill the one that's currently running. When given that command line, it would send that first instance of the program a message or something that tells it to quit and then hang around just waiting until that first instance of the program has actually terminated. The installer would then be able to run the program with the kill switch and know that the original instance of it is gone when the kill switched instance has returned.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26853/" ]
I'm using Wise Package Studio 7.0 SP2 on Windows XP. I've got an MSI Wrapped EXE installation that goes about happily installing some files and then running one of the files from the installation which we can refer to as app.exe. So on the "Execute Deferred" tab of the MSI Editor, I had to add the lines: ``` If Not Installed then Execute Installed Program app.exe (Action) End ``` This ensured that my app.exe would be run *only* on an installation and not during a modify/repair/removal. When app.exe runs, it conveniently adds itself to the system tray. I'm looking for something that will do the reverse during a removal. I want to stop the app.exe process thus removing it from the system tray. Currently my removal gets rid of all the files however the app.exe remains running and still shows up in the systems tray. I've looked at adding the conditional statement: ``` If REMOVE~="ALL" then *remove the app from the systray!* End ``` The conditional statement will let me do something only on a removal, however I'm not sure of the best approach to go about actually terminating the process. Is there an MSI command I can run that will let me do that? Should I write my own .exe that will do that?
6 months ago we were using VBScript actions to do the same thing, then right around the time that SP3 was released the objProcess.Terminate() function just refused to work on some machines. No matter what we did, it just froze. This happened on around 10% of our test machines so we were forced to find an alternative solution (who knows how many customers it might have frozen on!) My first discovery was the inbuilt (since Windows 2000) command TASKKILL eg: `TASKKILL /IM app.exe /F` but as that seems to use similar means of killing a process as we used in VBScript, that method would also fail. So now we're using the `pskill.exe` tool from sysinternals, you need to use a command line switch to supress the license agreement prompt but other than that, it's been the most foolproof way of killing a running EXE that I've found. Of course the best solution would be to build your own EXE or DLL to do it should you happen to know a little C++ ;)
251,225
<p>We have a large application in Ruby on Rails with many filters. Some of these filters can be complex. I am looking for a way to individually test these filters with a unit test. Right now I test them by testing them through an action that uses them with a functional test. This just doesn't feel like the right way.<br> Does anyone have advice or experience with this?</p>
[ { "answer_id": 251263, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>It depends on what your filters are doing.</p>\n\n<p>This: <a href=\"http://movesonrails.com/journal/2008/1/23/testing-your-application-controller-with-rspec.html\" rel=\"nofollow noreferrer\">http://movesonrails.com/journal/2008/1/23/testing-your-application-controller-with-rspec.html</a></p>\n\n<p>And also learning how to use mocha will get you a long way.</p>\n" }, { "answer_id": 251616, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>Remember a filter is just a method.<br>\nGiven this:</p>\n\n<pre><code>class SomeController\n before_filter :ensure_awesomeness\n\n ...\nend\n</code></pre>\n\n<p>There's no reason you can't just do this:</p>\n\n<pre><code>SomeController.new.ensure_awesomeness\n</code></pre>\n\n<p>and then check that it calls redirect_to or whatever it's supposed to do</p>\n" }, { "answer_id": 251981, "author": "scottd", "author_id": 5935, "author_profile": "https://Stackoverflow.com/users/5935", "pm_score": 0, "selected": false, "text": "<p>Orion I have messed with doing that in a few occurrences. Also, most of the time filters are private so you have to do a send:</p>\n\n<pre><code>SomeController.new.send(:some_filter)\n</code></pre>\n" }, { "answer_id": 856781, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have <a href=\"http://smsohan.blogspot.com/2009/05/unit-test-actioncontroller-filters.html\" rel=\"nofollow noreferrer\">a post</a> on unit testing before_filters easily, you may wish to take a look. Hope it will help.</p>\n" }, { "answer_id": 4317776, "author": "John Hinnegan", "author_id": 461974, "author_profile": "https://Stackoverflow.com/users/461974", "pm_score": 0, "selected": false, "text": "<p>I've come across this issue.</p>\n\n<p>What about filters that perform actions requiring a request. i.e. using Flash</p>\n\n<p>Example being Authlogic require_user method won't work just by using ApplicationController.new.send(:some_filter).</p>\n\n<p><a href=\"https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/application_controller.rb\" rel=\"nofollow\">https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/application_controller.rb</a></p>\n\n<p>Anyone have some non-hack ideas on how to test this kind of thing in isolation? (I'm doing it by creating a extra dummy controller that I only use for testing.)</p>\n" }, { "answer_id": 26382339, "author": "Bruno Mucelini Mergen", "author_id": 2441745, "author_profile": "https://Stackoverflow.com/users/2441745", "pm_score": 1, "selected": false, "text": "<p>You can testing with this code:</p>\n\n<pre><code>require \"test_helper\"\ndescribe ApplicationController do\n\n context 'ensure_manually_set_password' do\n setup do\n class ::TestingController &lt; ApplicationController\n def hello\n render :nothing =&gt; true\n end\n end\n\n NameYourApp::Application.routes.draw do \n get 'hello', to: 'testing#hello', as: :hello\n end\n end\n\n after do\n Rails.application.reload_routes!\n end\n\n teardown do\n Object.send(:remove_const, :TestingController)\n end\n\n context 'when user is logged in' do\n setup do\n @controller = TestingController.new\n end\n\n context 'and user has not manually set their password' do\n let(:user) { FactoryGirl.build(:user, manually_set_password: false) }\n setup do\n login_as user\n get :hello\n end\n\n should 'redirect user to set their password' do\n assert_redirected_to new_password_path(user.password_token)\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>It's code is original from <a href=\"http://robots.thoughtbot.com/testing-a-before-filter\" rel=\"nofollow\">http://robots.thoughtbot.com/testing-a-before-filter</a>,\nI changed for Rails 3 </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935/" ]
We have a large application in Ruby on Rails with many filters. Some of these filters can be complex. I am looking for a way to individually test these filters with a unit test. Right now I test them by testing them through an action that uses them with a functional test. This just doesn't feel like the right way. Does anyone have advice or experience with this?
Remember a filter is just a method. Given this: ``` class SomeController before_filter :ensure_awesomeness ... end ``` There's no reason you can't just do this: ``` SomeController.new.ensure_awesomeness ``` and then check that it calls redirect\_to or whatever it's supposed to do
251,246
<p>Ok I have an <code>apache IBM HTTP Server WAS 6.1</code> setup </p> <p>I have my <code>certs</code> correctly installed and can successfully load <code>http</code> and <code>https</code> pages.</p> <p>After a successful <code>j_security_check</code> authentication via <code>https</code>, I want the now authorized page (and all subsequent pages) to load as <code>http</code>.</p> <p>I want this all to work with <code>mod_rewrite</code> because I don't want to change application code for something that really should be simple to do on the webserver.</p> <p>I would think this would work but it doesn't and I fear it's because <code>j_security_check</code> is bypassing <code>mod_rewrite</code> somehow.</p> <pre><code>RewriteCond %{HTTPS} =off RewriteCond %{THE_REQUEST} login\.jsp.*action=init [OR] RewriteCond %{THE_REQUEST} login\.jsp.*action=submit RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L] &lt;&lt;-- this rule is working RewriteCond %{HTTPS} =on RewriteCond %{THE_REQUEST} !login\.jsp.*action=init [OR] RewriteCond %{THE_REQUEST} !login\.jsp.*action=submit RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R,L] &lt;--- this rule is not working or the condition is not returning true </code></pre> <p>I know the <code>[R,L]</code> will force the executed rule to be the last rule to run on a request and redirect accordingly.</p> <p>I found this little jewel after a little googleing.</p> <pre><code>mod_rewrite: My rules are ignored. Nothing is written to the rewrite log. The most common cause of this is placing mod_rewrite directives at global scope (outside of any VirtualHost containers) but expecting the directives to apply to requests which were matched by a VirtualHost container. In this example, the mod_rewrite configuration will be ignored for requests which are received on port 443: RewriteEngine On RewriteRule ^index.htm$ index.html &lt;VirtualHost *:443&gt; existing vhost directives &lt;/VirtualHost&gt; Unlike most configurable features, the mod_rewrite configuration is not inherited by default within a &lt;VirtualHost &gt; container. To have global mod_rewrite directives apply to a VirtualHost, add these two extra directives to the VirtualHost container: &lt;VirtualHost *:443&gt; existing vhost directives RewriteEngine On RewriteOptions Inherit &lt;/VirtualHost&gt; </code></pre> <p>Adding the Inherit declaration to my single <code>virtualhost</code> declaration that points to the machine ip and <code>port 443</code> did NOT help one bit.</p> <p>Now I know that my app server communicates on <code>9080</code> and <code>9443</code> respectively but I can't find a single <code>virtualhost</code> in the web server <code>httpd.conf</code>. </p> <p>I did some testing with different rewrite rules while not authenticated and saw that my <code>mod rewrite</code> code worked.. </p> <p><strong>So: how do I make websphere use mod rewrite after authentication?</strong> </p> <p>It's like the web server is only used for unauthenticated requests and after that some blackbox container serves up everything somehow.</p>
[ { "answer_id": 251871, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": -1, "selected": false, "text": "<p>Wild guess: should the second logical OR be an AND (i.e. no [OR] and the RewriteCond defaults to AND)?</p>\n\n<pre><code>RewriteCond %{THE_REQUEST} !login\\.jsp.*action=init\nRewriteCond %{THE_REQUEST} !login\\.jsp.*action=submit\n</code></pre>\n" }, { "answer_id": 253765, "author": "branchgabriel", "author_id": 30807, "author_profile": "https://Stackoverflow.com/users/30807", "pm_score": 1, "selected": true, "text": "<p>This is the solution for http to https to http</p>\n\n<p>You have to put the condition and the rewrite rule in the virtual host like the arcticle said but for some reason inheritance didn't want to work.</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTPS} !=on\nRewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\\ /path/login\\.jsp\\ HTTP/1\\.1\nRewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n\n &lt;VirtualHost 000.000.000.000:443&gt;\n ServerName servername\n ServerAlias url.com machinename\n DocumentRoot d:/ibmhttpserver61/htdocs/en_US\n ErrorLog d:/ibmhttpserver61/logs/secerr.log\n TransferLog d:/ibmhttpserver61/logs/sectrans.log\n SSLEnable\n Keyfile d:/ibmhttpserver61/ssl/ctxroot.kdb\n SSLV2Timeout 100\n SSLV3Timeout 1000 \n\n RewriteEngine On\n RewriteCond %{REQUEST_URI} /path/secure/index.jsf\n RewriteRule ^(.*)$ http://url/path/secure/index.jsf [R,L] \n\n &lt;/VirtualHost&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30807/" ]
Ok I have an `apache IBM HTTP Server WAS 6.1` setup I have my `certs` correctly installed and can successfully load `http` and `https` pages. After a successful `j_security_check` authentication via `https`, I want the now authorized page (and all subsequent pages) to load as `http`. I want this all to work with `mod_rewrite` because I don't want to change application code for something that really should be simple to do on the webserver. I would think this would work but it doesn't and I fear it's because `j_security_check` is bypassing `mod_rewrite` somehow. ``` RewriteCond %{HTTPS} =off RewriteCond %{THE_REQUEST} login\.jsp.*action=init [OR] RewriteCond %{THE_REQUEST} login\.jsp.*action=submit RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L] <<-- this rule is working RewriteCond %{HTTPS} =on RewriteCond %{THE_REQUEST} !login\.jsp.*action=init [OR] RewriteCond %{THE_REQUEST} !login\.jsp.*action=submit RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R,L] <--- this rule is not working or the condition is not returning true ``` I know the `[R,L]` will force the executed rule to be the last rule to run on a request and redirect accordingly. I found this little jewel after a little googleing. ``` mod_rewrite: My rules are ignored. Nothing is written to the rewrite log. The most common cause of this is placing mod_rewrite directives at global scope (outside of any VirtualHost containers) but expecting the directives to apply to requests which were matched by a VirtualHost container. In this example, the mod_rewrite configuration will be ignored for requests which are received on port 443: RewriteEngine On RewriteRule ^index.htm$ index.html <VirtualHost *:443> existing vhost directives </VirtualHost> Unlike most configurable features, the mod_rewrite configuration is not inherited by default within a <VirtualHost > container. To have global mod_rewrite directives apply to a VirtualHost, add these two extra directives to the VirtualHost container: <VirtualHost *:443> existing vhost directives RewriteEngine On RewriteOptions Inherit </VirtualHost> ``` Adding the Inherit declaration to my single `virtualhost` declaration that points to the machine ip and `port 443` did NOT help one bit. Now I know that my app server communicates on `9080` and `9443` respectively but I can't find a single `virtualhost` in the web server `httpd.conf`. I did some testing with different rewrite rules while not authenticated and saw that my `mod rewrite` code worked.. **So: how do I make websphere use mod rewrite after authentication?** It's like the web server is only used for unauthenticated requests and after that some blackbox container serves up everything somehow.
This is the solution for http to https to http You have to put the condition and the rewrite rule in the virtual host like the arcticle said but for some reason inheritance didn't want to work. ``` RewriteEngine on RewriteCond %{HTTPS} !=on RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /path/login\.jsp\ HTTP/1\.1 RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L] <VirtualHost 000.000.000.000:443> ServerName servername ServerAlias url.com machinename DocumentRoot d:/ibmhttpserver61/htdocs/en_US ErrorLog d:/ibmhttpserver61/logs/secerr.log TransferLog d:/ibmhttpserver61/logs/sectrans.log SSLEnable Keyfile d:/ibmhttpserver61/ssl/ctxroot.kdb SSLV2Timeout 100 SSLV3Timeout 1000 RewriteEngine On RewriteCond %{REQUEST_URI} /path/secure/index.jsf RewriteRule ^(.*)$ http://url/path/secure/index.jsf [R,L] </VirtualHost> ```
251,248
<p>I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don't want to go that route.</p> <p>Apologies to everybody that answered in C# for not specifying it's C++. :-)</p>
[ { "answer_id": 251251, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/cs/processownersid.aspx\" rel=\"nofollow noreferrer\">CodeProject</a> has a few different methods you can try... You didn't mention what languages you wanted a solution in.</p>\n\n<p>If you want to access it via a batch file or something, you can look as PsGetSid by <a href=\"http://www.sysinternals.com\" rel=\"nofollow noreferrer\">Sysinternals</a>. It translates SIDs to names and vice versa.</p>\n" }, { "answer_id": 251258, "author": "Mel Green", "author_id": 32226, "author_profile": "https://Stackoverflow.com/users/32226", "pm_score": 0, "selected": false, "text": "<p>You didn't specify what language you want. But if you're up for C# this article offers both the WMI method as well as a faster (while more verbose) method utilizing the Win32 API.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/processownersid.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/processownersid.aspx</a></p>\n\n<p>I don't think there's currently another way of doing this without using WMI or the Win32 API.</p>\n" }, { "answer_id": 251266, "author": "Jeffrey Meyer", "author_id": 2323, "author_profile": "https://Stackoverflow.com/users/2323", "pm_score": 3, "selected": false, "text": "<p>This should give you what you need:</p>\n\n<p>using System.Security.Principal;</p>\n\n<p>...</p>\n\n<p>var sid = WindowsIdentity.GetCurrent().User;</p>\n\n<p>The User property of WindowsIdentity returns the SID, per <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity_members.aspx\" rel=\"noreferrer\">MSDN Docs</a></p>\n" }, { "answer_id": 251267, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 7, "selected": true, "text": "<p>In Win32, call <a href=\"http://msdn.microsoft.com/en-us/library/aa446671.aspx\" rel=\"nofollow noreferrer\">GetTokenInformation</a>, passing a token handle and the <code>TokenUser</code> constant. It will fill in a <a href=\"http://msdn.microsoft.com/en-us/library/aa379634.aspx\" rel=\"nofollow noreferrer\">TOKEN_USER</a> structure for you. One of the elements in there is the user's SID. It's a BLOB (binary), but you can turn it into a string by using <a href=\"http://msdn.microsoft.com/en-us/library/aa376399.aspx\" rel=\"nofollow noreferrer\">ConvertSidToStringSid</a>.</p>\n<p>To get hold of the current token handle, use <a href=\"http://msdn.microsoft.com/en-us/library/aa379296(VS.85).aspx\" rel=\"nofollow noreferrer\">OpenThreadToken</a> or <a href=\"http://msdn.microsoft.com/en-us/library/aa379295(VS.85).aspx\" rel=\"nofollow noreferrer\">OpenProcessToken</a>.</p>\n<p>If you prefer ATL, it has the <a href=\"https://learn.microsoft.com/en-za/cpp/atl/reference/caccesstoken-class?view=msvc-160\" rel=\"nofollow noreferrer\">CAccessToken</a> class, which has all sorts of interesting things in it.</p>\n<p>.NET has the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx\" rel=\"nofollow noreferrer\">Thread.CurrentPrinciple</a> property, which returns an IPrincipal reference. You can get the SID:</p>\n<pre><code>IPrincipal principal = Thread.CurrentPrincipal;\nWindowsIdentity identity = principal.Identity as WindowsIdentity;\nif (identity != null)\n Console.WriteLine(identity.User);\n</code></pre>\n<p>Also in .NET, you can use WindowsIdentity.GetCurrent(), which returns the current user ID:</p>\n<pre><code>WindowsIdentity identity = WindowsIdentity.GetCurrent();\nif (identity != null)\n Console.WriteLine(identity.User);\n</code></pre>\n" }, { "answer_id": 251308, "author": "silverbugg", "author_id": 29650, "author_profile": "https://Stackoverflow.com/users/29650", "pm_score": 2, "selected": false, "text": "<p>In C# you can use either</p>\n\n<p><code>using Microsoft.Win32.Security;</code></p>\n\n<p>...</p>\n\n<p><code>string username = Environment.UserName + \"@\" + Environment.GetEnvironmentVariable(\"USERDNSDOMAIN\");</code></p>\n\n<p><code>Sid sidUser = new Sid (username);</code></p>\n\n<p><strong>Or...</strong></p>\n\n<p><code>using System.Security.AccessControl;</code></p>\n\n<p><code>using System.Security.Principal;</code></p>\n\n<p>...</p>\n\n<p><code>WindowsIdentity m_Self = WindowsIdentity.GetCurrent();</code></p>\n\n<p><code>SecurityIdentifier m_SID = m_Self.Owner;\");</code></p>\n" }, { "answer_id": 8850569, "author": "cigar huang", "author_id": 659882, "author_profile": "https://Stackoverflow.com/users/659882", "pm_score": 2, "selected": false, "text": "<p>I found another way to get SID: <br/></p>\n\n<pre><code>System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();\nstring sid = id.User.AccountDomainSid.ToString();\n</code></pre>\n" }, { "answer_id": 13032855, "author": "nullpotent", "author_id": 661797, "author_profile": "https://Stackoverflow.com/users/661797", "pm_score": 0, "selected": false, "text": "<p>This one is the shortest of them all I believe. </p>\n\n<pre><code>UserPrincipal.Current.Sid;\n</code></pre>\n\n<p>Available with .net >= 3.5 </p>\n" }, { "answer_id": 13356252, "author": "dex black", "author_id": 635976, "author_profile": "https://Stackoverflow.com/users/635976", "pm_score": 3, "selected": false, "text": "<pre><code>ATL::CAccessToken accessToken;\nATL::CSid currentUserSid;\nif (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) &amp;&amp;\n accessToken.GetUser(&amp;currentUserSid))\n return currentUserSid.Sid();\n</code></pre>\n" }, { "answer_id": 45717256, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 1, "selected": false, "text": "<p>And in native code:</p>\n\n<pre><code>function GetCurrentUserSid: string;\n\n hAccessToken: THandle;\n userToken: PTokenUser;\n dwInfoBufferSize: DWORD;\n dw: DWORD;\n\n if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then\n dw &lt;- GetLastError;\n if dw &lt;&gt; ERROR_NO_TOKEN then\n RaiseLastOSError(dw);\n\n if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then\n RaiseLastOSError;\n try\n userToken &lt;- GetMemory(1024);\n try\n if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then\n RaiseLastOSError;\n Result &lt;- SidToString(userToken.User.Sid);\n finally\n FreeMemory(userToken);\n finally\n CloseHandle(hAccessToken);\n</code></pre>\n" }, { "answer_id": 53256910, "author": "BattleTested_закалённый в бою", "author_id": 4134099, "author_profile": "https://Stackoverflow.com/users/4134099", "pm_score": 1, "selected": false, "text": "<p>This question is tagged as <code>c++</code> And I answer in <code>c++</code> language, So I recommend use of <strong><em>WMI</em></strong> tool :</p>\n\n<p>So, As <strong><em>WMI</em></strong> commands in <code>powershell</code>, bellow command get <code>SID</code> of <code>system-pc1</code> user :</p>\n\n<blockquote>\n<pre><code>Get-WmiObject win32_useraccount -Filter \"name = 'system-pc1'\" | Select-Object sid\n</code></pre>\n</blockquote>\n\n<p>First, you need to get current <code>username</code> with bellow <code>code</code> :</p>\n\n<pre><code>char username[UNLEN+1];\nDWORD username_len = UNLEN+1;\nGetUserName(username, &amp;username_len);\n</code></pre>\n\n<p>Now you can try with <code>WQL</code> language and execute this query in <code>c++</code> as bellow (in this example , I used of <code>system-pc1</code> username in <code>WQL_WIN32_USERACCOUNT_QUERY</code> query :</p>\n\n<pre><code>#define NETWORK_RESOURCE \"root\\\\CIMV2\"\n#define WQL_LANGUAGE \"WQL\"\n#define WQL_WIN32_USERACCOUNT_QUERY \"SELECT * FROM Win32_Useraccount where name='system-pc1'\"\n#define WQL_SID \"SID\"\n\nIWbemLocator *pLoc = 0; // Obtain initial locator to WMI to a particular host computer\nIWbemServices *pSvc = 0; // To use of connection that created with CoCreateInstance()\nULONG uReturn = 0;\nHRESULT hResult = S_OK; // Result when we initializing\nIWbemClassObject *pClsObject = NULL; // A class for handle IEnumWbemClassObject objects\nIEnumWbemClassObject *pEnumerator = NULL; // To enumerate objects\nVARIANT vtSID = { 0 }; // OS name property\n\n// Initialize COM library\nhResult = CoInitializeEx(0, COINIT_MULTITHREADED);\nif (SUCCEEDED(hResult))\n{\n // Initialize security\n hResult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,\n RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);\n if (SUCCEEDED(hResult))\n {\n // Create only one object on the local system\n hResult = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,\n IID_IWbemLocator, (LPVOID*)&amp;pLoc);\n\n if (SUCCEEDED(hResult))\n {\n // Connect to specific host system namespace\n hResult = pLoc-&gt;ConnectServer(TEXT(NETWORK_RESOURCE), NULL, NULL,\n 0, NULL, 0, 0, &amp;pSvc);\n if (SUCCEEDED(hResult))\n {\n /* Set the IWbemServices proxy\n * So the impersonation of the user will be occurred */\n hResult = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,\n NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,\n NULL, EOAC_NONE);\n if (SUCCEEDED(hResult))\n {\n /* Use the IWbemServices pointer to make requests of WMI\n * For example, query for user account */\n hResult = pSvc-&gt;ExecQuery(TEXT(WQL_LANGUAGE), TEXT(WQL_WIN32_USERACCOUNT_QUERY),\n WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &amp;pEnumerator);\n if (SUCCEEDED(hResult))\n {\n // Go to get the next object from IEnumWbemClassObject\n pEnumerator-&gt;Next(WBEM_INFINITE, 1, &amp;pClsObject, &amp;uReturn);\n if (uReturn != 0)\n {\n // Get the value of the \"sid, ...\" property\n pClsObject-&gt;Get(TEXT(WQL_SID), 0, &amp;vtSID, 0, 0);\n VariantClear(&amp;vtSID);\n\n // Print SID\n wcout &lt;&lt; vtSID.bstrVal;\n\n pClsObject-&gt;Release();\n pClsObject = NULL;\n }\n }\n }\n }\n }\n }\n\n // Cleanup\n pSvc-&gt;Release();\n pLoc-&gt;Release();\n pEnumerator-&gt;Release();\n // Uninitialize COM library\n CoUninitialize();\n</code></pre>\n\n<p>This example does works properly!</p>\n" }, { "answer_id": 58853677, "author": "Martin Schmitz", "author_id": 8937534, "author_profile": "https://Stackoverflow.com/users/8937534", "pm_score": 0, "selected": false, "text": "<p>in cmd.exe</p>\n\n<blockquote>\n <p>whoami /user</p>\n</blockquote>\n\n<p>if you need it programatically, please ask more specified</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17028/" ]
I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don't want to go that route. Apologies to everybody that answered in C# for not specifying it's C++. :-)
In Win32, call [GetTokenInformation](http://msdn.microsoft.com/en-us/library/aa446671.aspx), passing a token handle and the `TokenUser` constant. It will fill in a [TOKEN\_USER](http://msdn.microsoft.com/en-us/library/aa379634.aspx) structure for you. One of the elements in there is the user's SID. It's a BLOB (binary), but you can turn it into a string by using [ConvertSidToStringSid](http://msdn.microsoft.com/en-us/library/aa376399.aspx). To get hold of the current token handle, use [OpenThreadToken](http://msdn.microsoft.com/en-us/library/aa379296(VS.85).aspx) or [OpenProcessToken](http://msdn.microsoft.com/en-us/library/aa379295(VS.85).aspx). If you prefer ATL, it has the [CAccessToken](https://learn.microsoft.com/en-za/cpp/atl/reference/caccesstoken-class?view=msvc-160) class, which has all sorts of interesting things in it. .NET has the [Thread.CurrentPrinciple](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx) property, which returns an IPrincipal reference. You can get the SID: ``` IPrincipal principal = Thread.CurrentPrincipal; WindowsIdentity identity = principal.Identity as WindowsIdentity; if (identity != null) Console.WriteLine(identity.User); ``` Also in .NET, you can use WindowsIdentity.GetCurrent(), which returns the current user ID: ``` WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (identity != null) Console.WriteLine(identity.User); ```
251,271
<p>Sometimes you need to upgrade the database with many rows that you have in a datatable or you have an array full of data, instead of putting all this data together in a string and then splitting in SQL SERVER, or instead of iterating the datatable in the code row by row and updating database, is there any other way? Is there other type of variables besides the traditional ones in SQL SERVER 2005?</p>
[ { "answer_id": 251285, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": true, "text": "<p>There's a few ways to do this.</p>\n\n<p>If you're simply inserting rows, then I would create a DataTable object with the information in it, then use the SqlBulkCopy object:</p>\n\n<pre><code>SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);\ncopier.BatchSize = 500; //# of rows to insert at a time\ncopier.DestinationTableName = \"dbo.MyTable\";\ncopier.WriteToServer(myDataTable);\n</code></pre>\n\n<p>Another option is to wrap your data in xml (however you want to do that), and send it to your stored procedure (which does whatever you need it to do) using the sql 2005 'xml' data type</p>\n" }, { "answer_id": 251545, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>I agree with John that <code>SqlBulkCopy</code> or sqlxml are the best options in SQL Server 2005; note that in SQL Server 2008 you also have <a href=\"http://msdn.microsoft.com/en-us/library/bb675163.aspx\" rel=\"noreferrer\">table valued parameters</a>, which would be worth consideration; especially when mixed with the new <a href=\"http://msdn.microsoft.com/en-us/library/ms141775.aspx\" rel=\"noreferrer\">merge join</a>.</p>\n\n<p>Note that if you use <code>SqlBulkCopy</code>, I strongly recommend bulk inserting only to a staging table - i.e. a separate table just for the import; then run a stored procedure to move the data to the live table. That way you get proper logging, and you can have a tightly scoped transaction just at the database while you run the SP (i.e. you don't need a transaction spanning all that network IO).</p>\n\n<p>One other point; if you are dealing with large volumes of data, you might not want to have to load a <code>DataTable</code> (since that forces you to buffer all the data in memory first); as an alternative, it is also possible to write your own <code>IDataReader</code> that pulls data from a stream (such as a file etc); see <code>SimpleDataReader</code> <a href=\"http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/84d08dd9778efd77/91c7a20056ffe8e1\" rel=\"noreferrer\">here</a>. <code>SqlBulkCopy</code> will accept data from an <code>IDataReader</code> very happily.</p>\n" }, { "answer_id": 251574, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>John mentioned using XML... and that's the approach I would use for your situation (SQL Server 2005, and making a sproc that handles the SQL for you).</p>\n\n<p>Here's an example of how to get started (this is just a select statement, but you can make it an update if you want):</p>\n\n<pre><code>CREATE PROCEDURE MySproc ( @Accounts XML )\nAS\n\nSELECT\n Accounts.AccountID.query('.')\nFROM\n @Accounts.nodes('//ID/text()') AS Accounts(AccountID)\n\nGO\nEXEC MySproc '&lt;Accounts&gt;&lt;ID&gt;123&lt;/ID&gt;&lt;ID&gt;456&lt;/ID&gt;&lt;/Accounts&gt;'\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
Sometimes you need to upgrade the database with many rows that you have in a datatable or you have an array full of data, instead of putting all this data together in a string and then splitting in SQL SERVER, or instead of iterating the datatable in the code row by row and updating database, is there any other way? Is there other type of variables besides the traditional ones in SQL SERVER 2005?
There's a few ways to do this. If you're simply inserting rows, then I would create a DataTable object with the information in it, then use the SqlBulkCopy object: ``` SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default); copier.BatchSize = 500; //# of rows to insert at a time copier.DestinationTableName = "dbo.MyTable"; copier.WriteToServer(myDataTable); ``` Another option is to wrap your data in xml (however you want to do that), and send it to your stored procedure (which does whatever you need it to do) using the sql 2005 'xml' data type
251,275
<p>I have a User object that has a Country object on it. I map this with a many-to-one tag in the User mapping file:</p> <pre><code>&lt;many-to-one name="Country" column="CountryID" cascade="none"/&gt; </code></pre> <p>How do I update a User's country?</p> <p>At the moment my UI has a dropdown of countries and the ID of the new country is passed to the controller. The controller then sets the ID of the User's country from that value. So:</p> <pre><code>var user = session.Get&lt;User&gt;(userID); user.Country.ID = Convert.ToInt32(Request.Form["Country_ID"]); </code></pre> <p>But when I call:</p> <pre><code>session.SaveOrUpdate(user); </code></pre> <p>I get an error saying that "identifier of an instance of Country was altered from 7 to 8". Presumably this is because the Country object is marked as dirty by NHibernate? I don't want to update the country object though, just the ID reference in the User. Is it possible to do it this way?</p> <p>Thanks, Jon</p>
[ { "answer_id": 251324, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 0, "selected": false, "text": "<pre><code>var user = session.Get&lt;User&gt;(userID);\nuser.Country = session.Get&lt;Country&gt;(Convert.ToInt32(Request.Form[\"Country_ID\"]));\n</code></pre>\n\n<p>You must retrieve the country from the database and then set it to the user</p>\n" }, { "answer_id": 251963, "author": "JontyMC", "author_id": 32855, "author_profile": "https://Stackoverflow.com/users/32855", "pm_score": 0, "selected": false, "text": "<p>Thanks Anders. Why do we need the extra overhead of first getting the object back when all we are doing is updating a reference to that object?</p>\n\n<p>In reality our controller is automatically deserializing the request to the object. Is there no way we can tell NHibernate to ignore the updating of the country object and just update the user? I would have thought cascade=\"none\" would have done that.</p>\n\n<p>What happens if you have several many-to-one objects on a object that need to be updated? That is a lot of overhead to get them all back before saving.</p>\n" }, { "answer_id": 253010, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 1, "selected": false, "text": "<p>You can always get hold of the underlying connection and do the update manually.</p>\n\n<p><a href=\"http://www.darkside.co.za/archive/2008/03/03/castle-activerecord-get-the-underlying-database-connection.aspx\" rel=\"nofollow noreferrer\">http://www.darkside.co.za/archive/2008/03/03/castle-activerecord-get-the-underlying-database-connection.aspx</a></p>\n" }, { "answer_id": 253209, "author": "JontyMC", "author_id": 32855, "author_profile": "https://Stackoverflow.com/users/32855", "pm_score": 0, "selected": false, "text": "<p>That would really negate the whole purpose of using an ORM in the first place, wouldn't it? What is the normal pattern for updating child objects like this? Surely it is a very common scenario. Is it to load every single one up:</p>\n\n<pre><code>var user = session.Get&lt;User&gt;(userID);\nuser.Country = session.Get&lt;Country&gt;(Convert.ToInt32(Request.Form[\"Country_ID\"]));\nuser.Manager = session.Get&lt;User&gt;(Convert.ToInt32(Request.Form[\"Manager_ID\"]));\nuser.State = session.Get&lt;State&gt;(Convert.ToInt32(Request.Form[\"State _ID\"]));\nuser.Region = session.Get&lt;Region&gt;(Convert.ToInt32(Request.Form[\"State _ID\"]));\n</code></pre>\n\n<p>Do we really need to make an extra database call for every child object (event though those objects aren't being updated)?</p>\n\n<p>At the moment we have:</p>\n\n<pre><code>var ds = new NameValueDeserializer();\nvar entity = session.Get&lt;TEntity&gt;(entityID);\nds.Deserialize(entity, form);\nsession.Update(entity);\n</code></pre>\n\n<p>So this works generically for all entities. Having to specifically load up child objects to save the entity would be an unnecessary coding overhead (as well as making extra database calls).</p>\n\n<p>Is there no way round this in configuration, mappings, interceptors, etc? Does anyone know why Hibernate has taken this design decision?</p>\n" }, { "answer_id": 253304, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 1, "selected": true, "text": "<p>You should probably take this discussion to the NHibernate users group.</p>\n\n<p><a href=\"http://groups.google.com/group/nhusers\" rel=\"nofollow noreferrer\">http://groups.google.com/group/nhusers</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32855/" ]
I have a User object that has a Country object on it. I map this with a many-to-one tag in the User mapping file: ``` <many-to-one name="Country" column="CountryID" cascade="none"/> ``` How do I update a User's country? At the moment my UI has a dropdown of countries and the ID of the new country is passed to the controller. The controller then sets the ID of the User's country from that value. So: ``` var user = session.Get<User>(userID); user.Country.ID = Convert.ToInt32(Request.Form["Country_ID"]); ``` But when I call: ``` session.SaveOrUpdate(user); ``` I get an error saying that "identifier of an instance of Country was altered from 7 to 8". Presumably this is because the Country object is marked as dirty by NHibernate? I don't want to update the country object though, just the ID reference in the User. Is it possible to do it this way? Thanks, Jon
You should probably take this discussion to the NHibernate users group. <http://groups.google.com/group/nhusers>
251,276
<p>I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything:</p> <p><code>SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')</code></p> <p>Can parameters be used like this? or are they only valid in an instance such as:</p> <p><code>SELECT * FROM compliance_corner WHERE body LIKE '%&lt;string&gt;%'</code> (where <code>&lt;string&gt;</code> is the search object).</p> <p>EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed?</p> <p>Also, I ran this statement in SQL Server: <code>SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE</code>%max%')` and that returns results.</p>
[ { "answer_id": 251280, "author": "Will Wagner", "author_id": 25468, "author_profile": "https://Stackoverflow.com/users/25468", "pm_score": 2, "selected": false, "text": "<p>You may have to concatenate the % signs with your parameter, e.g.:</p>\n\n<p>LIKE '%' || @query || '%'</p>\n\n<p>Edit:\nActually, that may not make any sense at all. I think I may have misunderstood your problem.</p>\n" }, { "answer_id": 251288, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 5, "selected": false, "text": "<p>you have to do:</p>\n\n<p><code>LIKE '%' + @param + '%'</code></p>\n" }, { "answer_id": 251311, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 7, "selected": true, "text": "<p>Your visual basic code would look something like this:</p>\n\n<pre><code>Dim cmd as New SqlCommand(\"SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')\")\n\ncmd.Parameters.Add(\"@query\", searchString)\n</code></pre>\n" }, { "answer_id": 251380, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 7, "selected": false, "text": "<p>Well, I'd go with:</p>\n\n<pre><code> Dim cmd as New SqlCommand(\n \"SELECT * FROM compliance_corner\"_\n + \" WHERE (body LIKE @query )\"_ \n + \" OR (title LIKE @query)\")\n\n cmd.Parameters.Add(\"@query\", \"%\" +searchString +\"%\")\n</code></pre>\n" }, { "answer_id": 4433177, "author": "Lalie", "author_id": 541042, "author_profile": "https://Stackoverflow.com/users/541042", "pm_score": 1, "selected": false, "text": "<p>Sometimes the symbol used as a placeholder <code>%</code> is not the same if you execute a query from VB as when you execute it from MS SQL / Access. Try changing your placeholder symbol from <code>%</code> to <code>*</code>. That might work.<br>\nHowever, if you debug and want to copy your SQL string directly in MS SQL or Access to test it, you may have to change the symbol back to <code>%</code> in MS SQL or Access in order to actually return values.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 45429309, "author": "Ramgy Borja", "author_id": 7978302, "author_profile": "https://Stackoverflow.com/users/7978302", "pm_score": 1, "selected": false, "text": "<p>try also this way</p>\n\n<pre><code>Dim cmd as New SqlCommand(\"SELECT * FROM compliance_corner WHERE (body LIKE CONCAT('%',@query,'%') OR title LIKE CONCAT('%',@query,'%') )\")\ncmd.Parameters.Add(\"@query\", searchString)\ncmd.ExecuteNonQuery()\n</code></pre>\n\n<p>Used <strong>Concat</strong> instead of <strong>+</strong></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything: `SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')` Can parameters be used like this? or are they only valid in an instance such as: `SELECT * FROM compliance_corner WHERE body LIKE '%<string>%'` (where `<string>` is the search object). EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed? Also, I ran this statement in SQL Server: `SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE`%max%')` and that returns results.
Your visual basic code would look something like this: ``` Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')") cmd.Parameters.Add("@query", searchString) ```
251,277
<p>Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that).</p> <p>The specific example I have is a <a href="http://www.php.net/directoryiterator" rel="noreferrer">DirectoryIterator</a> but it would be nice to have a solution general to any iterator.</p> <pre><code>$dir = new DirectoryIterator('.'); foreach ($dir as $file) echo $file-&gt;getFilename(); </code></pre> <p>I'd like to be able to sort these by various criteria (filename, size, etc)</p>
[ { "answer_id": 251320, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 4, "selected": true, "text": "<p>There is no way to do that. An iterator should \"iterate\" through the list. You have to sort the underlying list to achieve the needed behavior.</p>\n\n<p>By the way, the more complete reference to the SPL is here:\n<a href=\"http://www.php.net/~helly/php/ext/spl/\" rel=\"noreferrer\">http://www.php.net/~helly/php/ext/spl/</a></p>\n" }, { "answer_id": 3832409, "author": "bishop", "author_id": 463000, "author_profile": "https://Stackoverflow.com/users/463000", "pm_score": 3, "selected": false, "text": "<p>You'll have to reduce using iterator_to_array() then uasort(). And, in my performance testing, sufficiently fast.</p>\n\n<p>To your specific example, the most compact way I know using iterators is below:</p>\n\n<pre><code>// get (recursively) files matching a pattern, each file as SplFileInfo object\n$matches = new RegexIterator(\n new RecursiveIteratorIterator(\n new RecursiveDirectoryIterator('/path/to/files/')\n ),\n '/(\\.php|\\.ini|\\.xml)$/i'\n );\n $files = iterator_to_array($matches);\n\n// sort them by name\nuasort($files, create_function('$a,$b', 'return strnatcasecmp($a-&gt;getFilename(), $b-&gt;getFilename());'));\n</code></pre>\n" }, { "answer_id": 26845098, "author": "Luís Lopes", "author_id": 1866773, "author_profile": "https://Stackoverflow.com/users/1866773", "pm_score": 3, "selected": false, "text": "<p>For the ones that end up here 5 years later:</p>\n\n<p>If you make the Iterator an extension of ArrayIterator you can use</p>\n\n<p>ArrayIterator::uasort (to sort by value) and ArrayIterator::uksort (to sort by key)</p>\n\n<p><a href=\"http://php.net/manual/en/arrayiterator.uasort.php\" rel=\"noreferrer\">http://php.net/manual/en/arrayiterator.uasort.php</a></p>\n\n<p><a href=\"http://php.net/manual/en/arrayiterator.uksort.php\" rel=\"noreferrer\">http://php.net/manual/en/arrayiterator.uksort.php</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24181/" ]
Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that). The specific example I have is a [DirectoryIterator](http://www.php.net/directoryiterator) but it would be nice to have a solution general to any iterator. ``` $dir = new DirectoryIterator('.'); foreach ($dir as $file) echo $file->getFilename(); ``` I'd like to be able to sort these by various criteria (filename, size, etc)
There is no way to do that. An iterator should "iterate" through the list. You have to sort the underlying list to achieve the needed behavior. By the way, the more complete reference to the SPL is here: <http://www.php.net/~helly/php/ext/spl/>
251,278
<p>Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator)</p> <p>Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example:</p> <pre><code>**Table** Value A, Value L, Value P Value A, Value Q, Value Z </code></pre> <p>I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of).</p> <p>Here's what I've got so far, although it doesn't work obviously:</p> <pre><code>SELECT value, attribute_definition_id, value_rk FROM attribute_values WHERE value IN ( SELECT value, max(value_rk) FROM attribute_values ) ORDER BY attribute_definition_id </code></pre> <p>I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value_rk is my big problem since every value is unique but I only need one.</p> <p>NOTE: value_rk is not a number, hence this DOES NOT WORK</p> <p>UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value_rk for the value that matches. Like so:</p> <pre><code>&lt;cfquery name="queryBaseValues" datasource="XXX" timeout="999"&gt; SELECT DISTINCT value, attribute_definition_id FROM attribute_values ORDER BY attribute_definition_id &lt;/cfquery&gt; &lt;cfoutput query="queryBaseValues"&gt; &lt;cfquery name="queryRKValue" datasource="XXX"&gt; SELECT TOP 1 value_rk FROM attribute_values WHERE value = '#queryBaseValues.value#' &lt;/cfquery&gt; &lt;cfset resourceKey = queryRKValue.value_rk&gt; ... </code></pre> <p>So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)</p>
[ { "answer_id": 251290, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT value, attribute_definition_id, value_rk\nFROM attribute_values\nWHERE value, value_rk IN (\n SELECT value, max(value_rk)\n FROM attribute_values\n GROUP BY value\n)\nORDER BY attribute_definition_id\n</code></pre>\n\n<p>NOT TESTED!</p>\n" }, { "answer_id": 251293, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 2, "selected": false, "text": "<p>Is this what you're looking for?</p>\n\n<pre><code>SELECT value, attribute_definition_id, value_rk\nFROM attribute_values av1\nWHERE value_rk IN (\n SELECT max(value_rk)\n FROM attribute_values av2\n WHERE av2.value = av1.value\n)\nORDER BY attribute_definition_id\n</code></pre>\n\n<p>If value_rk is unique, this should work.</p>\n" }, { "answer_id": 251301, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT a1.value, a1.attribute_definition_id, a1.value_rk\nFROM attribute_values AS a1\n LEFT OUTER JOIN attribute_values AS a2\n ON (a1.value = a2.value AND a1.value_rk &lt; a2.value_rk)\nWHERE a2.value IS NULL\nORDER BY a1.attribute_definition_id;\n</code></pre>\n\n<p>In other words, find the row <code>a1</code> for which no row <code>a2</code> exists with the same <code>value</code> and a greater <code>value_rk</code>.</p>\n" }, { "answer_id": 251316, "author": "Adam", "author_id": 30084, "author_profile": "https://Stackoverflow.com/users/30084", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if I entirely understand your set-up, but would something like this work:</p>\n\n<pre><code>SELECT value, attribute_definition_id, value_rk\nFROM attribute_values\nGROUP BY value\nORDER BY attribute_definition_id;\n</code></pre>\n\n<p>Again, I'm not real sure which column it is you're trying to limit, or how you're wanting to limit it.</p>\n" }, { "answer_id": 251319, "author": "Patryk Kordylewski", "author_id": 30927, "author_profile": "https://Stackoverflow.com/users/30927", "pm_score": 3, "selected": false, "text": "<p>This should work for PostgreSQL, i don't know which dbms you use.</p>\n\n<pre><code>SELECT DISTINCT ON (value)\n value, \n attribute_definition_id, \n value_rk\nFROM \n attribute_values\nORDER BY\n value, \n attribute_definition_id\n</code></pre>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/interactive/sql-select.html#SQL-DISTINCT\" rel=\"nofollow noreferrer\">PostgreSQL Docs</a></p>\n" }, { "answer_id": 251370, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 2, "selected": false, "text": "<p>Okay, here's my assumptions:</p>\n\n<p>Standard SQL Server</p>\n\n<p>value_rk is not a numeric value, but value and attribute_definition_id <em>are</em> numeric.</p>\n\n<pre><code>SELECT value_rk, MIN(value) as value, MIN(attribute_definition_id) as attribute_definition_id\nFROM attribute_values\nGROUP BY value_rk\nORDER BY MIN(attribute_definition_id)\n</code></pre>\n\n<p>If one of those fields isn't numeric, then it'll require more thought - please let us know.</p>\n" }, { "answer_id": 251562, "author": "matt.mercieca", "author_id": 30407, "author_profile": "https://Stackoverflow.com/users/30407", "pm_score": 0, "selected": false, "text": "<p>Less elegant than I would like---- it's essentially what you're doing, just in pure SQL--- but it works and can all be done in SQL.</p>\n\n<pre>\nDECLARE @mytable TABLE(mykey NVARCHAR(512), myVal NVARCHAR(512))\n\nDECLARE @keyVal NVARCHAR(512)\nDECLARE @depVal NVARCHAR(512)\nDECLARE myCursor CURSOR for\n SELECT DISTINCT(value) FROM attribute_values\nOPEN myCursor\nFETCH NEXT FROM myCursor INTO @keyVal\nWHILE @@FETCH_STATUS=0\n BEGIN\n SET @depVal = (SELECT TOP 1 attribute_definition_id FROM attribute_values WHERE VALUE=@keyVal ORDER BY attribute_definition_id)\n INSERT INTO @mytable (mykey, myVal) VALUES (@keyVal, @depVal)\n FETCH NEXT FROM myCursor INTO @keyVal\n END\nDEALLOCATE myCursor\n\nSELECT * FROM @mytable\n</pre>\n\n<p>You can add a depVal2 and others using this method. </p>\n" }, { "answer_id": 251856, "author": "walming", "author_id": 24595, "author_profile": "https://Stackoverflow.com/users/24595", "pm_score": 5, "selected": true, "text": "<p>this might work:</p>\n\n<pre><code>SELECT DISTINCT a.value, a.attribute_definition_id, \n (SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk\nFROM attribute_values as a\nORDER BY attribute_definition_id\n</code></pre>\n\n<p>.. not tested.</p>\n" }, { "answer_id": 266933, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 2, "selected": false, "text": "<p>If you are open to using table variables, you could keep it all within a single database call like this:</p>\n\n<pre><code>DECLARE @attribute_values TABLE (value int, attribute_definition_id int, value_rk uniqueidentifier)\n\nINSERT INTO @attribute_values (value)\nSELECT DISTINCT value FROM attribute_values\n\nUPDATE @attribute_values\nSET attribute_definition_id = av2.attribute_definition_id,\n value_rk = av2.value_rk\nFROM @attribute_values av1\nINNER JOIN attribute_values av2 ON av1.value = av2.value\n\nSELECT value, attribute_definition_id, value_rk FROM @attribute_values\n</code></pre>\n\n<p>Essentially you are creating a limited recordset with the table filled with unique values of 'value', and letting SQL Server fill in the gaps using just one of the matches from the main table.</p>\n\n<p>Edited to add: This syntax works within cfquery just fine.</p>\n" }, { "answer_id": 8756710, "author": "user1133937", "author_id": 1133937, "author_profile": "https://Stackoverflow.com/users/1133937", "pm_score": 0, "selected": false, "text": "<p>i think</p>\n\n<pre><code>SELECT DISTINCT a.value, a.attribute_definition_id, \n(SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk\nFROM attribute_values as a\nORDER BY attribute_definition_id\n</code></pre>\n\n<p>worked</p>\n" }, { "answer_id": 12221134, "author": "Corwin Joy", "author_id": 150709, "author_profile": "https://Stackoverflow.com/users/150709", "pm_score": 0, "selected": false, "text": "<p>As noted by John Fiala, the canonical answer in SQL server is to use a group by clause when you want to perform a \"distinct\" operation over a subset of columns. Why is this the correct canonical answer? Well, you want to pull in columns that are not part of your \"distinct\" group. Exactly what rows do you want to pull in for these subsidiary columns? Using a group by clause and defining aggregate functions for these subsidiary columns makes your query well-behaved in the sense that you now know how these subsidiary columns are obtained. This article gives more details:</p>\n\n<p><a href=\"http://weblogs.sqlteam.com/jeffs/archive/2007/10/12/sql-distinct-group-by.aspx\" rel=\"nofollow\">http://weblogs.sqlteam.com/jeffs/archive/2007/10/12/sql-distinct-group-by.aspx</a></p>\n\n<pre><code>SELECT value_rk, MIN(value) as value, \nMIN(attribute_definition_id) as attribute_definition_id\nFROM attribute_values\nGROUP BY value_rk\n</code></pre>\n\n<p>Also, it's worth noting that MIN and MAX work on text and several other data types that are not numeric values.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value\_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator) Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example: ``` **Table** Value A, Value L, Value P Value A, Value Q, Value Z ``` I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of). Here's what I've got so far, although it doesn't work obviously: ``` SELECT value, attribute_definition_id, value_rk FROM attribute_values WHERE value IN ( SELECT value, max(value_rk) FROM attribute_values ) ORDER BY attribute_definition_id ``` I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value\_rk is my big problem since every value is unique but I only need one. NOTE: value\_rk is not a number, hence this DOES NOT WORK UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value\_rk for the value that matches. Like so: ``` <cfquery name="queryBaseValues" datasource="XXX" timeout="999"> SELECT DISTINCT value, attribute_definition_id FROM attribute_values ORDER BY attribute_definition_id </cfquery> <cfoutput query="queryBaseValues"> <cfquery name="queryRKValue" datasource="XXX"> SELECT TOP 1 value_rk FROM attribute_values WHERE value = '#queryBaseValues.value#' </cfquery> <cfset resourceKey = queryRKValue.value_rk> ... ``` So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)
this might work: ``` SELECT DISTINCT a.value, a.attribute_definition_id, (SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk FROM attribute_values as a ORDER BY attribute_definition_id ``` .. not tested.
251,298
<p>I noticed the specificaition for Collections.sort:</p> <pre><code>public static &lt;T&gt; void sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c) </code></pre> <p>Why is the "<code>? super</code>" necessary here? If <code>ClassB</code> extends <code>ClassA</code>, then wouldn't we have a guarantee that a <code>Comparator&lt;ClassA&gt;</code> would be able to compare two <code>ClassB</code> objects anyway, without the "<code>? super</code>" part?</p> <p>In other words, given this code:</p> <pre><code>List&lt;ClassB&gt; list = . . . ; Comparator&lt;ClassA&gt; comp = . . . ; Collections.sort(list, comp); </code></pre> <p>why isn't the compiler smart enough to know that this is OK even without specifying "<code>? super</code>" for the declaration of Collections.sort()?</p>
[ { "answer_id": 251328, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "<p>Josh Bloch had a talk at Google I/O this year, called <a href=\"http://sites.google.com/site/io/effective-java-reloaded\" rel=\"nofollow noreferrer\">Effective Java Reloaded</a>, which you may find interesting. It talks about a mnemonic called \"Pecs\" (producer <code>extends</code>, consumer <code>super</code>), which explains why you use <code>? extends T</code> and <code>? super T</code> in your input parameters (only; never for return types), and when to use which.</p>\n" }, { "answer_id": 251342, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>It's obvious to you that, in the case of <code>Comparator</code>, any ancestor of <code>T</code> would work. But the compiler doesn't know that class <code>Comparator</code> functions like that - it just needs to be told whether it should allow <code>&lt;T&gt;</code> or <code>&lt;? super T&gt;</code>.</p>\n\n<p>Viewed another way, yes it's true that any <code>Comparator</code> of an ancestor would work in this case - and the way the library developer says that is to use <code>&lt;? super T&gt;</code>.</p>\n" }, { "answer_id": 251355, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>This is similar to C#, I just learned about it a couple days ago as to why (the hard way, and then the PDC informative way).</p>\n\n<p>Assume <code>Dog extends Animal</code></p>\n\n<p><code>Blah&lt;Dog&gt;</code> is <strong>not</strong> the same as <code>Blah&lt;Animal&gt;</code> they have completely different type signatures even though <code>Dog</code> extends <code>Animal</code>.</p>\n\n<p>For example assume a method on <code>Blah&lt;T&gt;</code>:</p>\n\n<pre><code>T Clone(); \n</code></pre>\n\n<p>In <code>Blah&lt;Dog&gt;</code> this is <code>Dog Clone();</code> while in <code>Blah&lt;Animal&gt;</code> this is <code>Animal Clone();</code>.</p>\n\n<p>You need a way to distinguish that the compiler can say that <code>Blah&lt;Dog&gt;</code> has the same public interface of <code>Blah&lt;Animal&gt;</code> and that's what <code>&lt;? super T&gt;</code> indicates - any class used as T can be reduced to its super class in terms of <code>Blah&lt;? super T&gt;</code>.</p>\n\n<p>(In C# 4.0 this would be <code>Blah&lt;out T&gt;</code> I believe.)</p>\n" }, { "answer_id": 251357, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>There's a really nice (but twisty) explanation of this in <a href=\"http://java.sun.com/docs/books/tutorial/extra/generics/morefun.html\" rel=\"nofollow noreferrer\">More Fun with Wildcards</a>.</p>\n" }, { "answer_id": 251714, "author": "Kris Nuttycombe", "author_id": 390636, "author_profile": "https://Stackoverflow.com/users/390636", "pm_score": 0, "selected": false, "text": "<p>The simple answer to your question is that the library designer wanted to give the maximum flexibility to the user of the library; this method signature for example allows you to do something like this:</p>\n\n<pre><code>List&lt;Integer&gt; ints = Arrays.asList(1,2,3);\nComparator&lt;Number&gt; numberComparator = ...;\n\nCollections.sort(ints, numberComparator);\n</code></pre>\n\n<p>Using the wildcard prevents you from being forced to use a <code>Comparator&lt;Integer&gt;</code>; the fact that the language requires a wildcard to be specified by the library designer enables him or her to either permit or restrict such use.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
I noticed the specificaition for Collections.sort: ``` public static <T> void sort(List<T> list, Comparator<? super T> c) ``` Why is the "`? super`" necessary here? If `ClassB` extends `ClassA`, then wouldn't we have a guarantee that a `Comparator<ClassA>` would be able to compare two `ClassB` objects anyway, without the "`? super`" part? In other words, given this code: ``` List<ClassB> list = . . . ; Comparator<ClassA> comp = . . . ; Collections.sort(list, comp); ``` why isn't the compiler smart enough to know that this is OK even without specifying "`? super`" for the declaration of Collections.sort()?
Josh Bloch had a talk at Google I/O this year, called [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded), which you may find interesting. It talks about a mnemonic called "Pecs" (producer `extends`, consumer `super`), which explains why you use `? extends T` and `? super T` in your input parameters (only; never for return types), and when to use which.
251,307
<p>I have a resource handler that is Response.WriteFile(fileName) based on a parameter passed through the querystring. I am handling the mimetype correctly, but the issue is in some browsers, the filename comes up as Res.ashx (The name of the handler) instead of MyPdf.pdf (the file I am outputting). Can someone inform me how to change the name of the file when it is sent back to the server? Here is my code:</p> <pre><code>// Get the name of the application string application = context.Request.QueryString["a"]; string resource = context.Request.QueryString["r"]; // Parse the file extension string[] extensionArray = resource.Split(".".ToCharArray()); // Set the content type if (extensionArray.Length &gt; 0) context.Response.ContentType = MimeHandler.GetContentType( extensionArray[extensionArray.Length - 1].ToLower()); // clean the information application = (string.IsNullOrEmpty(application)) ? "../App_Data/" : application.Replace("..", ""); // clean the resource resource = (string.IsNullOrEmpty(resource)) ? "" : resource.Replace("..", ""); string url = "./App_Data/" + application + "/" + resource; context.Response.WriteFile(url); </code></pre>
[ { "answer_id": 251323, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>This Scott Hanselman post should be helpful:<br>\n<a href=\"http://www.hanselman.com/blog/CommentView.aspx?guid=360\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/CommentView.aspx?guid=360</a></p>\n" }, { "answer_id": 251364, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": true, "text": "<p>Extending from Joel's comment, your actual code would look something like this:</p>\n\n<pre><code>context.Response.AddHeader(\"content-disposition\", \"attachment; filename=\" + resource);\n</code></pre>\n" }, { "answer_id": 251388, "author": "Matthew Kruskamp", "author_id": 22521, "author_profile": "https://Stackoverflow.com/users/22521", "pm_score": 0, "selected": false, "text": "<p>Thank you guys for your answer. The final code works and checks for pdf.</p>\n\n<pre><code>if (extensionArray[extensionArray.Length - 1].ToLower() == \"pdf\")\n context.Response.AddHeader(\"content-disposition\", \n \"Attachment; filename=\" + resource);\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22521/" ]
I have a resource handler that is Response.WriteFile(fileName) based on a parameter passed through the querystring. I am handling the mimetype correctly, but the issue is in some browsers, the filename comes up as Res.ashx (The name of the handler) instead of MyPdf.pdf (the file I am outputting). Can someone inform me how to change the name of the file when it is sent back to the server? Here is my code: ``` // Get the name of the application string application = context.Request.QueryString["a"]; string resource = context.Request.QueryString["r"]; // Parse the file extension string[] extensionArray = resource.Split(".".ToCharArray()); // Set the content type if (extensionArray.Length > 0) context.Response.ContentType = MimeHandler.GetContentType( extensionArray[extensionArray.Length - 1].ToLower()); // clean the information application = (string.IsNullOrEmpty(application)) ? "../App_Data/" : application.Replace("..", ""); // clean the resource resource = (string.IsNullOrEmpty(resource)) ? "" : resource.Replace("..", ""); string url = "./App_Data/" + application + "/" + resource; context.Response.WriteFile(url); ```
Extending from Joel's comment, your actual code would look something like this: ``` context.Response.AddHeader("content-disposition", "attachment; filename=" + resource); ```
251,313
<p>Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?</p> <pre><code>function getSomethingAsync(someState, callback) { var req = abc.createRequestObject(someParams); req.invoke(makeCallback(someState, callback)); } function makeCallback(someState, callback) { return function getSomethingCallback(data) { var result = processDataUsingState(data, someState); callback(result); // alternately/optionally pass someState along to result } } </code></pre> <p>If not, is there a better or more idiomatic way?</p>
[ { "answer_id": 251347, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>its better (nicer) to use anonymous functions:</p>\n\n<pre><code>function getSomethingAsync (someState, callback) {\n req.invoke (function (data) {\n var result = processDataUsingState (data, someState);\n callback (result);\n });\n}\n</code></pre>\n" }, { "answer_id": 251363, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<p>I don't see any immediate problems with this - closures are powerful for numerous reasons, one of which is removing the need to use global variables for state maintenance.</p>\n\n<p>That said, the only thing you need to be wary of with regards to closures is memory leaks that typically occur in IE, but those are usually, IIRC, related to DOM elements and event handlers attached thereto.</p>\n\n<p>Proceed!</p>\n" }, { "answer_id": 8930571, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 1, "selected": false, "text": "<p>The more idiomatic way is to use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind</code></a>, then you don't need to duplicate the code to create the closure. I'll use a simple example (that doesn't have your custom code) to explain</p>\n<pre><code>/**\n * Retrieves the content of a url asyunchronously\n * The callback will be called with one parameter: the html retrieved\n */\nfunction getUrl(url, callback) {\n $.ajax({url: url, success: function(data) {\n callback(data);\n }}) \n}\n\n// Now lets' call getUrl twice, specifying the same \n// callback but a different id will be passed to each\nfunction updateHtml(id, html) {\n $('#' + id).html(html);\n}\n\n\n// By calling bind on the callback, updateHTML will be called with \n// the parameters you passed to it, plus the parameters that are used\n// when the callback is actually called (inside )\n// The first parameter is the context (this) to use, since we don't care,\n// I'm passing in window since it's the default context\ngetUrl('/get/something.html', updateHTML.bind(window, 'node1'));\n// results in updateHTML('node1', 'response HTML here') being called\ngetUrl('/get/something-else.html', updateHTML.bind(window, 'node2'));\n// results in updateHTML('node2', 'response HTML here') being called\n</code></pre>\n<p><code>Function.bind</code> is new so if you need backwards support, look at the Compatibility section of <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind</code></a></p>\n<p>Lastly, I know the question wasn't tagged as jQuery. This was just the quickest way to show an asynchronous function without dealing with cross browser issues</p>\n" }, { "answer_id": 8965087, "author": "pete otaqui", "author_id": 484190, "author_profile": "https://Stackoverflow.com/users/484190", "pm_score": 0, "selected": false, "text": "<p>You can also manipulate the value of \"this\" in a function with call() / apply().</p>\n\n<p>For example, specify that a further argument to your async method is an object to use as \"this\" in the callback. This is how jQuery sets the dom node to be \"this\" in event callbacks.</p>\n\n<pre><code>function getSomethingAsync(callback, scope) {\n var req = abc.createRequestObject(someParams);\n req.invoke(function(rsp) {\n callback.apply(scope, [rsp]);\n });\n}\n\n// usage:\ngetSomethingAsync(function() {console.log(this.someState)}, {someState:'value'});\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript? ``` function getSomethingAsync(someState, callback) { var req = abc.createRequestObject(someParams); req.invoke(makeCallback(someState, callback)); } function makeCallback(someState, callback) { return function getSomethingCallback(data) { var result = processDataUsingState(data, someState); callback(result); // alternately/optionally pass someState along to result } } ``` If not, is there a better or more idiomatic way?
I don't see any immediate problems with this - closures are powerful for numerous reasons, one of which is removing the need to use global variables for state maintenance. That said, the only thing you need to be wary of with regards to closures is memory leaks that typically occur in IE, but those are usually, IIRC, related to DOM elements and event handlers attached thereto. Proceed!
251,317
<p>When I try to use <code>curl</code> or <code>file_get_contents</code> to read something like <a href="http://example.com/python/json/" rel="nofollow noreferrer">http://example.com/python/json/</a> from <a href="http://example.com/" rel="nofollow noreferrer">http://example.com/</a> I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well.</p> <pre><code>echo file_get_contents('http://example.com/python/json/'); =&gt; 404 echo file_get_contents('http://google.com'); =&gt; OK </code></pre> <p>The same script works on my laptop, but I can't figure out what the difference is.</p>
[ { "answer_id": 251327, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": true, "text": "<p>It looks like example.com is not the default domain for the IP address and that file_get_contents uses HTTP/1.0 instead of HTTP/1.1 and/or does not send a Host: header. Try the curl support in PHP instead:</p>\n\n<pre><code>$curl = curl_init();\ncurl_setopt($curl, CURLOPT_URL, 'http://example.com/');\ncurl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);\n$result = curl_exec($curl);\ncurl_close($curl);\n</code></pre>\n\n<p>Alternatively the /etc/hosts file sets the wrong IP address for example.com.</p>\n" }, { "answer_id": 251329, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<p>Something to do with the domain, maybe? Of course, you don't want to reveal it here, so you might have a bit to do, but I guess the sanity check would be that you can access that URL via a web browser (or command line tool such as GET if you're command-line only).</p>\n\n<p>You could also just ping and/or traceroute to the domain - the results may well be illuminating.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ]
When I try to use `curl` or `file_get_contents` to read something like <http://example.com/python/json/> from <http://example.com/> I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well. ``` echo file_get_contents('http://example.com/python/json/'); => 404 echo file_get_contents('http://google.com'); => OK ``` The same script works on my laptop, but I can't figure out what the difference is.
It looks like example.com is not the default domain for the IP address and that file\_get\_contents uses HTTP/1.0 instead of HTTP/1.1 and/or does not send a Host: header. Try the curl support in PHP instead: ``` $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://example.com/'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); ``` Alternatively the /etc/hosts file sets the wrong IP address for example.com.
251,325
<p>So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here.</p> <pre><code>sieve(BST&lt;T&gt;* t, int n); </code></pre> <p>this function is called like this: sieve(t,n) the object is called BST t; </p> <p>I'm going to be using the class remove function within the sieve function to remove specific objects. I'm not sure what my prototype for this basic function should look like? Doing this:</p> <pre><code>sieve(BST&lt;int&gt; t, int n) </code></pre> <p>What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function.</p> <p>If I call the remove function (t.remove(value)) in my main function where the original object was created it removes everything properly. Once I start doing it through my sieve function I see no change when I re print it out from my main function. So my main function looks something like this:</p> <pre><code>int main () { int n, i, len; BST&lt;int&gt; t; cin &gt;&gt; n; vector&lt;int&gt; v(n); srand(1); for (i = 0; i &lt; n; i++) v[i] = rand() % n; for (i = 0; i &lt; n; i++) t.insert(v[i]); print_stat(t); t.inOrder(print_data); sieve(v,t,n); print_stat(t); t.inOrder(print_data); return 0; } </code></pre> <p>So my results end up being the same, even though my debug statements within the functions show it's actually deleting something. I'm guessing where I'm going wrong is how I am passing the t object onto the function.</p>
[ { "answer_id": 251335, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "<pre><code>sieve(BST&lt;int&gt;&amp; t, int n)\n</code></pre>\n\n<p>The <code>&amp;</code> specifies passing by <em>reference</em> rather than value. :-)</p>\n" }, { "answer_id": 251350, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>The signature:</p>\n\n<pre><code>/* missing return type */ sieve&lt;BST&lt;int&gt; t, int n);\n</code></pre>\n\n<p>will, in fact, make a copy of the <code>BST&lt;int&gt;</code> passed in to <code>sieve()</code>. So any changes you make to it will be thrown away (unless you return a copy of it).</p>\n\n<p>You probably want something like:</p>\n\n<pre><code>void sieve&lt;BST&lt;int&gt; &amp; t, int n);\n</code></pre>\n\n<p>which passes in a reference, so any modifications you make to <code>t</code> inside the method are made to the object that you passed in (not a copy).</p>\n\n<p>Once you get that down and understand it, you'll probably want to make the <code>sieve()</code> function a \"function template\" so that it can take a <code>BST&lt;&gt;</code> containing any type.</p>\n" }, { "answer_id": 251352, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "<p>If I understand correctly your issue, you should use</p>\n\n<pre><code>BST t; \nsieve(BST&lt;T&gt; *t, int n);\n</code></pre>\n\n<p>and invoke it as:</p>\n\n<pre><code>sieve(&amp;t,n)\n</code></pre>\n\n<p>passing the pointer to the <code>t</code> object</p>\n\n<p>OR</p>\n\n<pre><code>BST t; \nsieve(BST&lt;T&gt; &amp;t, int n);\n</code></pre>\n\n<p>and invoke it as:</p>\n\n<pre><code>sieve(t,n)\n</code></pre>\n\n<p>passing the reference to the <code>t</code> object</p>\n" }, { "answer_id": 251362, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function.</p>\n</blockquote>\n\n<p>Correct. That is exactly what happens, because in C++ parameters are passed to funcitons by value. Passing a reference or a pointer will fix your problem. Using a reference is cleaner.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here. ``` sieve(BST<T>* t, int n); ``` this function is called like this: sieve(t,n) the object is called BST t; I'm going to be using the class remove function within the sieve function to remove specific objects. I'm not sure what my prototype for this basic function should look like? Doing this: ``` sieve(BST<int> t, int n) ``` What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function. If I call the remove function (t.remove(value)) in my main function where the original object was created it removes everything properly. Once I start doing it through my sieve function I see no change when I re print it out from my main function. So my main function looks something like this: ``` int main () { int n, i, len; BST<int> t; cin >> n; vector<int> v(n); srand(1); for (i = 0; i < n; i++) v[i] = rand() % n; for (i = 0; i < n; i++) t.insert(v[i]); print_stat(t); t.inOrder(print_data); sieve(v,t,n); print_stat(t); t.inOrder(print_data); return 0; } ``` So my results end up being the same, even though my debug statements within the functions show it's actually deleting something. I'm guessing where I'm going wrong is how I am passing the t object onto the function.
``` sieve(BST<int>& t, int n) ``` The `&` specifies passing by *reference* rather than value. :-)
251,336
<p>How do I discover classes at runtime in the classpath which implements a defined interface?</p> <p>ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.</p>
[ { "answer_id": 251670, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 0, "selected": false, "text": "<p>There is no reliable way to know what classes are in the classpath. According to its <a href=\"http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html\" rel=\"nofollow noreferrer\">documentation</a>, ServiceLoader relies on external files to tell it what classes to load; you might want to do the same. The basic idea is to have a file with the name of the class(es) to load, and then use reflection to instantiate it/them.</p>\n" }, { "answer_id": 251691, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "<p>There's nothing built into Java 1.5 for this. I implemented it myself; it's not too complicated. However, when we upgrade to Java 6, I will have to replace calls to my implementation with calls to <code>ServiceLoader</code>. I could have defined a little bridge between the app and the loader, but I only use it in a few places, and the wrapper itself would be a good candidate for a ServiceLoader.</p>\n\n<p>This is the core idea:</p>\n\n<pre><code>public &lt;S&gt; Iterable&lt;S&gt; load(Class&lt;S&gt; ifc) throws Exception {\n ClassLoader ldr = Thread.currentThread().getContextClassLoader();\n Enumeration&lt;URL&gt; e = ldr.getResources(\"META-INF/services/\" + ifc.getName());\n Collection&lt;S&gt; services = new ArrayList&lt;S&gt;();\n while (e.hasMoreElements()) {\n URL url = e.nextElement();\n InputStream is = url.openStream();\n try {\n BufferedReader r = new BufferedReader(new InputStreamReader(is, \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null)\n break;\n int comment = line.indexOf('#');\n if (comment &gt;= 0)\n line = line.substring(0, comment);\n String name = line.trim();\n if (name.length() == 0)\n continue;\n Class&lt;?&gt; clz = Class.forName(name, true, ldr);\n Class&lt;? extends S&gt; impl = clz.asSubclass(ifc);\n Constructor&lt;? extends S&gt; ctor = impl.getConstructor();\n S svc = ctor.newInstance();\n services.add(svc);\n }\n }\n finally {\n is.close();\n }\n }\n return services;\n}\n</code></pre>\n\n<p>Better exception handling is left as an exercise for the reader. Also, the method could be parameterized to accept a ClassLoader of the caller's choosing.</p>\n" }, { "answer_id": 251826, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>ServiceLoader is quite basic, and has been in use (informally) within the JDK since 1.3. ServiceLoader just finally made it a first class citizen. It simply looks for a resource file named for your interface, which is basically bundled in the META-INF directory of a library jar.</p>\n\n<p>That file contains the name of the class to load.</p>\n\n<p>So, you'd have a file named:</p>\n\n<p>META-INF/services/com.example.your.interface</p>\n\n<p>and inside it is a single line: com.you.your.interfaceImpl.</p>\n\n<p>In lieu of ServiceLoader, I like Netbeans Lookup. It works with 1.5 (and maybe 1.4).</p>\n\n<p>Out of the box, it does the exact same thing as ServiceLoader, and it's trivial to use. But it offers a lot more flexibility.</p>\n\n<p>Here's a link: <a href=\"http://openide.netbeans.org/lookup/\" rel=\"nofollow noreferrer\">http://openide.netbeans.org/lookup/</a></p>\n\n<p>Here's a article about ServiceLoader, but it mentions Netbeans Lookup at the bottom:\n<a href=\"http://weblogs.java.net/blog/timboudreau/archive/2008/08/simple_dependen.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/timboudreau/archive/2008/08/simple_dependen.html</a></p>\n" }, { "answer_id": 5246753, "author": "Marco Hunsicker", "author_id": 651652, "author_profile": "https://Stackoverflow.com/users/651652", "pm_score": 3, "selected": false, "text": "<p><code>javax.imageio.spi.ServiceRegistry</code> is the equivalent with prior Java versions. It's available since Java 1.4.</p>\n\n<p>It does not look like a general utility class, but it is. It's even a bit more powerful than <code>ServiceLoader</code>, as it allows some control over the order of the returned providers and direct access to the registry.</p>\n\n<p>See <a href=\"http://docs.oracle.com/javase/7/docs/api/index.html?javax/imageio/spi/ServiceRegistry.html\" rel=\"nofollow\">http://docs.oracle.com/javase/7/docs/api/index.html?javax/imageio/spi/ServiceRegistry.html</a></p>\n" }, { "answer_id": 6534230, "author": "Petrychenko", "author_id": 730929, "author_profile": "https://Stackoverflow.com/users/730929", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, </p>\n\n<blockquote>\n <p>There's nothing built into Java 1.5 for this ...</p>\n</blockquote>\n\n<p>is only a part of truth. </p>\n\n<p>There is non-standard <code>sun.misc.Service</code> around.</p>\n\n<p><a href=\"http://www.docjar.com/docs/api/sun/misc/Service.html\" rel=\"nofollow\">http://www.docjar.com/docs/api/sun/misc/Service.html</a></p>\n\n<p>Beware, it is not a part of standard J2SE API! \nIt is non-standard part of Sun JDK. \nSo you can not rely on it if you use, say, <code>JRockit</code>.</p>\n" }, { "answer_id": 7422757, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 1, "selected": false, "text": "<p>This is an old question but the other option is to use <strong>Package Level Annotations</strong>.\nSee my answer for: <a href=\"https://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface/5831808#5831808\">Find Java classes implementing an interface</a></p>\n\n<p>Package level annotations are annotations that are in package-info.java classes.</p>\n\n<p>JAXB uses this instead of Service Loaders. I also think its more flexible than the service loader.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
How do I discover classes at runtime in the classpath which implements a defined interface? ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.
There's nothing built into Java 1.5 for this. I implemented it myself; it's not too complicated. However, when we upgrade to Java 6, I will have to replace calls to my implementation with calls to `ServiceLoader`. I could have defined a little bridge between the app and the loader, but I only use it in a few places, and the wrapper itself would be a good candidate for a ServiceLoader. This is the core idea: ``` public <S> Iterable<S> load(Class<S> ifc) throws Exception { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + ifc.getName()); Collection<S> services = new ArrayList<S>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); Class<? extends S> impl = clz.asSubclass(ifc); Constructor<? extends S> ctor = impl.getConstructor(); S svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; } ``` Better exception handling is left as an exercise for the reader. Also, the method could be parameterized to accept a ClassLoader of the caller's choosing.
251,338
<p>I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows.</p> <p>I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.</p> <p>I can get the free space available by doing:</p> <blockquote> <p>cmd.exe /c Z:\ /-c</p> <p>or</p> <p>cmd.exe /c \\server\share /-c</p> </blockquote> <p>and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size.</p> <p>Any suggestions?</p>
[ { "answer_id": 251447, "author": "DMKing", "author_id": 10887, "author_profile": "https://Stackoverflow.com/users/10887", "pm_score": 3, "selected": true, "text": "<p>One way to do it would be to use fsutil on the command line. It returns something like this:</p>\n\n<pre><code>D:\\&gt;fsutil fsinfo ntfsinfo c:\nNTFS Volume Serial Number : 0xd49cf9cf9cf9ac5c\nVersion : 3.1\nNumber Sectors : 0x0000000004a813ff\nTotal Clusters : 0x000000000095027f\nFree Clusters : 0x00000000002392f5\nTotal Reserved : 0x0000000000000490\nBytes Per Sector : 512\nBytes Per Cluster : 4096\nBytes Per FileRecord Segment : 1024\nClusters Per FileRecord Segment : 0\nMft Valid Data Length : 0x000000000e70c000\nMft Start Lcn : 0x00000000000c0000\nMft2 Start Lcn : 0x0000000000000010\nMft Zone Start : 0x0000000000624ea0\nMft Zone End : 0x0000000000643da0\n</code></pre>\n\n<p>Multipy your number of sectors times the bytes per sector to get your size.</p>\n" }, { "answer_id": 256448, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 1, "selected": false, "text": "<p>You could do this pretty easily using a JNI call if you are comfortable with that...</p>\n\n<p>If you want a pre-packaged library that you can use with JDK1.5, take a look at the <a href=\"http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/FileSystemUtils.html\" rel=\"nofollow noreferrer\">Apache FileSystemUtils</a></p>\n\n<p>This just wraps the system call that you describe, but at least it's a standard library that you can use until you are able to use 1.6.</p>\n" }, { "answer_id": 365019, "author": "zehrer", "author_id": 45419, "author_profile": "https://Stackoverflow.com/users/45419", "pm_score": 0, "selected": false, "text": "<p>You could use the <a href=\"http://support.hyperic.com/display/SIGAR/Home\" rel=\"nofollow noreferrer\">SIGAR</a> library, which gives you native access on many platforms.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14007/" ]
I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows. I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5. I can get the free space available by doing: > > cmd.exe /c Z:\ /-c > > > or > > > cmd.exe /c \\server\share /-c > > > and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size. Any suggestions?
One way to do it would be to use fsutil on the command line. It returns something like this: ``` D:\>fsutil fsinfo ntfsinfo c: NTFS Volume Serial Number : 0xd49cf9cf9cf9ac5c Version : 3.1 Number Sectors : 0x0000000004a813ff Total Clusters : 0x000000000095027f Free Clusters : 0x00000000002392f5 Total Reserved : 0x0000000000000490 Bytes Per Sector : 512 Bytes Per Cluster : 4096 Bytes Per FileRecord Segment : 1024 Clusters Per FileRecord Segment : 0 Mft Valid Data Length : 0x000000000e70c000 Mft Start Lcn : 0x00000000000c0000 Mft2 Start Lcn : 0x0000000000000010 Mft Zone Start : 0x0000000000624ea0 Mft Zone End : 0x0000000000643da0 ``` Multipy your number of sectors times the bytes per sector to get your size.
251,345
<p>Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.</p> <p>Is there a 'proper' Rails way?</p>
[ { "answer_id": 251518, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 7, "selected": false, "text": "<p>If you're looking to do the search in the database then you'll need to use SQL.</p>\n\n<p>And, of course, you'll need to do the search in the database otherwise you need to load <em>all</em> the objects into Ruby (which isn't a good thing).</p>\n\n<p>So, you will need something like</p>\n\n<pre><code>MyModel.find(:all, :conditions =&gt; [\"field LIKE ?\", \"#{prefix}%\"])\n</code></pre>\n\n<p>where <code>prefix</code> is a variable with the string you're looking for.</p>\n\n<p>In Rails 3.0+ this becomes:</p>\n\n<pre><code>MyModel.where(\"field LIKE :prefix\", prefix: \"#{prefix}%\")\n</code></pre>\n" }, { "answer_id": 251556, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 4, "selected": true, "text": "<p>I would highly recommend the <a href=\"http://rdoc.info/projects/binarylogic/searchlogic\" rel=\"nofollow noreferrer\">Searchlogic</a> plugin.</p>\n\n<p>Then it's as easy as:</p>\n\n<pre><code>@search = Model.new_search(params[:search])\[email protected]_starts_with = \"prefix\"\n@models = @search.all\n</code></pre>\n\n<p>Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the <code>starts_with</code> condition. It will also handle all pagination.</p>\n\n<p>This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL!</p>\n\n<p>Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.</p>\n" }, { "answer_id": 898345, "author": "narsk", "author_id": 110123, "author_profile": "https://Stackoverflow.com/users/110123", "pm_score": 3, "selected": false, "text": "<p>Very much like the above answer, but if you're using ActiveRecord...2.1 or greater, you could use a named scope which would allow you to use this \"finder\" on records retrieved thru associations:</p>\n\n<pre><code>class User\n named_scope :with_name_like, lambda {|str|\n :conditions =&gt; ['lower(name) like ?', %(%#{str.downcase}%)]\n }\nend\n</code></pre>\n\n<p>Used like:</p>\n\n<pre><code>User.with_name_like(\"Samson\")\n</code></pre>\n\n<p>(returns all users in your database with a name like \"Samson\".</p>\n\n<p>Or:</p>\n\n<pre><code>some_association.users.with_name_like(\"Samson\")\n</code></pre>\n\n<p>Users off that association only with a name like \"Samson\".</p>\n" }, { "answer_id": 6959671, "author": "Larry", "author_id": 838196, "author_profile": "https://Stackoverflow.com/users/838196", "pm_score": 3, "selected": false, "text": "<p>Disclaimer: I am new to Ruby and Rails, and I am still trying to learn the Ruby Way to do things, but I have been coding for more than half of my life, and professionally for a decade. DRY is a concept with which I am very familiar. Here is how I implemented it. It is very similar to narsk's answer, which I think is also good. </p>\n\n<pre><code># name_searchable.rb\n# mix this into your class using\n# extend NameSearchable\nmodule NameSearchable\n def search_by_prefix (prefix)\n self.where(\"lower(name) LIKE '#{prefix.downcase}%'\")\n end\nend\n</code></pre>\n\n<p>And then in your model:</p>\n\n<pre><code>class User &lt; ActiveRecord::Base\n extend NameSearchable\n ...\nend\n</code></pre>\n\n<p>And then when you want to use it:</p>\n\n<pre><code>User.search_by_prefix('John') #or\nUser.search_by_prefix(\"#{name_str}\")\n</code></pre>\n\n<p>One thing to call out:</p>\n\n<p>Traditional relational databases aren't extremely good at satisfying these kinds of queries. If you are looking for a highly responsive implementation that will not kill your databases under load, you should probably use a solution that is tailored to the purpose instead. Popular examples include Solr or Sphinx, and there are many others as well. With this implementation, since you DRY, you could substitute the implementation with a separate indexer in just one place and you would be ready to rock. </p>\n" }, { "answer_id": 12223406, "author": "Dave Sag", "author_id": 917187, "author_profile": "https://Stackoverflow.com/users/917187", "pm_score": 2, "selected": false, "text": "<p>Now it's 2012 I thought I'd throw in this update to narsk's answer.</p>\n\n<p><code>named_scope</code> became simply <code>scope</code> a while ago so the example becomes</p>\n\n<pre><code>class User\n scope :name_starts_with, lambda {|str|\n :conditions =&gt; ['lower(name) like ?', \"#{str.downcase}%\"]\n }\nend\n</code></pre>\n\n<p>Note I removed the first <code>%</code> from narsk's solution as the OP is asking for a 'starts_with' not a 'contains' match.</p>\n\n<p>Now you can do things like</p>\n\n<pre><code>User.name_starts_with(\"b\").each do {|bs| puts bs.inspect}\nbob = User.name_starts_with(\"bob\").first\n\n… etc\n</code></pre>\n\n<p>Note that scopes <em>always return collections</em>, never individual results. That threw me when I was first starting out with AR and I still manage to forget that every now and again.</p>\n" }, { "answer_id": 14882525, "author": "Oriettaxx", "author_id": 1761229, "author_profile": "https://Stackoverflow.com/users/1761229", "pm_score": 1, "selected": false, "text": "<p>Dave Sag, I guess the first part of your code should be</p>\n\n<pre><code>class User\n scope :name_starts_with, (lambda do |str|\n {:conditions =&gt; ['lower(name) like ?', \"#{str.downcase}%\"]}\n end )\nend\n</code></pre>\n" }, { "answer_id": 24322687, "author": "bert bruynooghe", "author_id": 306730, "author_profile": "https://Stackoverflow.com/users/306730", "pm_score": 1, "selected": false, "text": "<p>Very terse syntax for the same thing might be: </p>\n\n<pre><code>Model.where(field: ('prefix'...'prefiy'))\n</code></pre>\n\n<p>This renders:</p>\n\n<pre><code>WHERE ( field &gt;= 'prefix' AND field &lt; 'prefiy')\n</code></pre>\n\n<p>This does the job as <em>'prefiy'</em> is the first string alphabetically not matching the <em>'prefix'</em> prefix.</p>\n\n<p>I would not use it normally (I would go for squeel or ransack instead), but it can save your day if for some reason you have to stick to hash syntax for the queries...</p>\n" }, { "answer_id": 26679117, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 3, "selected": false, "text": "<p>I don't want to write a scope every time I want to see if a specific column starts_with a prefix.</p>\n\n<pre><code># initializers/active_record_initializers.rb\nclass ActiveRecord::Base\n # do not accept a column_name from the outside without sanitizing it\n # as this can be prone to sql injection\n def self.starts_with(column_name, prefix)\n where(\"lower(#{column_name}) like ?\", \"#{prefix.downcase}%\")\n end\nend\n</code></pre>\n\n<p>Call it like this:</p>\n\n<pre><code>User.starts_with('name', 'ab').limit(1)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it. Is there a 'proper' Rails way?
I would highly recommend the [Searchlogic](http://rdoc.info/projects/binarylogic/searchlogic) plugin. Then it's as easy as: ``` @search = Model.new_search(params[:search]) @search.condition.field_starts_with = "prefix" @models = @search.all ``` Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the `starts_with` condition. It will also handle all pagination. This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL! Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.
251,351
<p>Is there a way of ordering a list of objects by a count of a property which is a collection? </p> <p>For arguments sake let's say I have a question object with a question name property, a property that is a collection of answer objects and another property that is a collection of user objects. The users join the question table via foreign key on question table and answers are joined with middle joining table. </p> <p>If I want nhibernate to get a list of "question" objects could I order it by Question.Answers.Count?</p> <p>i've tried the documentation's example using HQL:</p> <pre><code> List&lt;Question&gt; list = nhelper.NHibernateSession .CreateQuery("Select q from Question q left join q.Answers a group by q,a order by count(a)") .List&lt;Question&gt;(); </code></pre> <p>but i get </p> <pre><code>"column Question.Name is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" </code></pre> <p>I've tried adding all the properties to the group by list but it doesn't work. What happens then is that foreign key userId causes the same error as above but i can't include it in the group by as nhibernate lists it as </p> <pre><code>Question.Users.UserId </code></pre> <p>which doesn't solve it if included. </p> <p>any ideas?</p>
[ { "answer_id": 251361, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p>There is no one single optimum hashing algorithm. If you have a known input domain you can use a perfect-hashing generator such as <a href=\"http://www.gnu.org/software/gperf/\" rel=\"noreferrer\">gperf</a> to generate a hashing algorithm that will get a 100% rate on that particular input set. Otherwise, there is no 'right' answer to this question.</p>\n" }, { "answer_id": 251374, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "<p>You can get both using the Knuth hash function <a href=\"http://www.concentric.net/~Ttwang/tech/inthash.htm\" rel=\"nofollow noreferrer\">described here</a>.</p>\n\n<p>It's extremely fast assuming a power-of-2 hash table size -- just one multiply, one shift, and one bit-and. More importantly (for you) it's great at minimizing collisions (see <a href=\"http://blog.clawpaws.net/post/2007/04/22/Good-Hash-Functions\" rel=\"nofollow noreferrer\">this analysis</a>).</p>\n\n<p>Some other good algorithms are described <a href=\"http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200101/homework10/hashfuncs.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 251394, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": "<p>The simple hashCode used by Java's String class might show a suitable algorithm. </p>\n\n<p>Below is the \"GNU Classpath\" implementation. (License: GPL)</p>\n\n<pre><code> /**\n * Computes the hashcode for this String. This is done with int arithmetic,\n * where ** represents exponentiation, by this formula:&lt;br&gt;\n * &lt;code&gt;s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]&lt;/code&gt;.\n *\n * @return hashcode value of this String\n */\n public int hashCode()\n {\n if (cachedHashCode != 0)\n return cachedHashCode;\n\n // Compute the hash code using a local variable to be reentrant.\n int hashCode = 0;\n int limit = count + offset;\n for (int i = offset; i &lt; limit; i++)\n hashCode = hashCode * 31 + value[i];\n return cachedHashCode = hashCode;\n }\n</code></pre>\n" }, { "answer_id": 251404, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/251346/best-hashing-algorithm-in-terms-of-hash-collisions-and-performance#251361\">Nigel Campbell</a> indicated, there's no such thing as the 'best' hash function, as it depends on the data characteristics of what you're hashing as well as whether or not you need cryptographic quality hashes.</p>\n\n<p>That said, here are some pointers:</p>\n\n<ul>\n<li><p>Since the items you're using as input to the hash are just a set of strings, you could simply combine the hashcodes for each of those individual strings. I've seen the following pseudo-code suggested to do this, but I don't know of any particular analysis of it:</p>\n\n<pre><code>int hashCode = 0;\n\nforeach (string s in propertiesToHash) {\n hashCode = 31*hashCode + s.GetHashCode();\n}\n</code></pre>\n\n<p>According to <a href=\"http://www.themissingdocs.net/wordpress/?m=200607\" rel=\"nofollow noreferrer\">this article</a>, System.Web has an internal method that combines hashcodes using </p>\n\n<pre><code>combinedHash = ((combinedHash &lt;&lt; 5) + combinedHash) ^ nextObj.GetHashCode();\n</code></pre>\n\n<p>I've also seen code that simply xor's the hashcodes together, but that seems like a bad idea to me (though I again have no analysis to back this up). If nothing else, you end up with a collision if the same strings are hashed in a different order.</p></li>\n<li><p>I've used FNV to good effect: <a href=\"http://www.isthe.com/chongo/tech/comp/fnv/\" rel=\"nofollow noreferrer\">http://www.isthe.com/chongo/tech/comp/fnv/</a></p></li>\n<li><p>Paul Hsieh has a decent article: <a href=\"http://www.azillionmonkeys.com/qed/hash.html\" rel=\"nofollow noreferrer\">http://www.azillionmonkeys.com/qed/hash.html</a></p></li>\n<li><p>Another nice article by Bob Jenkins that was originally published in 1997 in Doctor Dobb's Journal (the linked article has updates): <a href=\"http://burtleburtle.net/bob/hash/doobs.html\" rel=\"nofollow noreferrer\">http://burtleburtle.net/bob/hash/doobs.html</a> </p></li>\n</ul>\n" }, { "answer_id": 251578, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 1, "selected": false, "text": "<p>Here is the <a href=\"http://en.wikipedia.org/wiki/Cuckoo_hashing\" rel=\"nofollow noreferrer\">Cuckoo Hash</a>.</p>\n<blockquote>\n<p>Lookup requires inspection of just two\nlocations in the hash table, which\ntakes constant time in the worst case\n(see Big O notation). This is in\ncontrast to many other hash table\nalgorithms, which may not have a\nconstant worst-case bound on the time\nto do a lookup.</p>\n</blockquote>\n<p>I think that fits into your criteria of collisions and performance. It appears that the tradeoff is that this type of hash table can only get 49% full.</p>\n" }, { "answer_id": 252293, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 3, "selected": false, "text": "<p>I am going to be lame here and give a more theoretical response rather a pin-pointing answer but please take the value in it.</p>\n\n<p>First there are two distinct problems : </p>\n\n<p>a. Collision probability\nb. Performance of hashing (i.e.: time, cpu-cycles etc.)</p>\n\n<p>The two problems are mildly corellated. They are not perfectly correlated.</p>\n\n<p>Problem a deals with the difference between the hashee and the resulted hash spaces. When you hash a 1KB file (1024 bytes) file and the hash has 32 bytes there will be :</p>\n\n<p>1,0907481356194159294629842447338e+2466 (i.e. a number with 2466 zeros) possible combinations of input files</p>\n\n<p>and the hash space will have </p>\n\n<p>1,1579208923731619542357098500869e+77 (i.e. a number with 77 zeros)</p>\n\n<p>The difference IS HUGE. there are 2389 zeros difference between them. THERE WILL BE COLLISIONS (a collision is a special case when two DIFFERENT input files will have the exact same hash) since we are reducing 10^2466 cases to 10^77 cases.</p>\n\n<p>The only way to minimize collison risk is to enlarge the hash space and therefore to make the hahs longer. Ideally the hash will have the file length but this is somehow moronic.</p>\n\n<hr>\n\n<p>The second problem is performance. This only deals with the algorithm of the hash. Ofcourse that a longer hash will most probably require more cpu cycles but a smarter algorithm might not. I have no clear case answer for this question. It's just too tough.</p>\n\n<p>However you can benchmark/measure different hashing implementations and draw pre-conclusions from this.</p>\n\n<p>Good luck ;)</p>\n" }, { "answer_id": 259998, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 6, "selected": true, "text": "<p>Forget about the term \"best\". No matter which hash algorithm anyone might come up with, unless you have a very limited set of data that needs to be hashed, every algorithm that performs very well on average can become completely useless if only being fed with the right (or from your perspective \"wrong\") data.</p>\n\n<p>Instead of wasting too much time thinking about how to get the hash more collision-free without using too much CPU time, I'd rather start thinking about \"How to make collisions less problematic\". E.g. if every hash bucket is in fact a table and all strings in this table (that had a collision) are sorted alphabetically, you can search within a bucket table using binary search (which is only O(log n)) and that means, even when every second hash bucket has 4 collisions, your code will still have decent performance (it will be a bit slower compared to a collision free table, but not that much). One big advantage here is that if your table is big enough and your hash is not too simple, two strings resulting in the same hash value will usually look completely different (hence the binary search can stop comparing strings after maybe one or two characters on average; making every compare very fast).</p>\n\n<p>Actually I had a situation myself before where searching directly within a sorted table using binary search turned out to be faster than hashing! Even though my hash algorithm was simple, it took quite some time to hash the values. Performance testing showed that only if I get more than about 700-800 entries, hashing is indeed faster than binary search. However, as the table could never grow larger than 256 entries anyway and as the average table was below 10 entries, benchmarking clearly showed that on every system, every CPU, the binary search was faster. Here, the fact that usually already comparing the first byte of the data was enough to lead to the next bsearch iteration (as the data used to be very different in the first one to two byte already) turned out as a big advantage.</p>\n\n<p>So to summarize: I'd take a decent hash algorithm, that doesn't cause too many collisions on average and is rather fast (I'd even accept some more collisions, if it's just very fast!) and rather optimize my code how to get the smallest performance penalty once collisions do occur (and they will! They will unless your hash space is at least equal or bigger than your data space and you can map a unique hash value to every possible set of data).</p>\n" }, { "answer_id": 29689759, "author": "Abhishek Jain", "author_id": 1416923, "author_profile": "https://Stackoverflow.com/users/1416923", "pm_score": 1, "selected": false, "text": "<p>Here is a straightforward way of implementing it yourself: <a href=\"http://www.devcodenote.com/2015/04/collision-free-string-hashing.html\" rel=\"nofollow\">http://www.devcodenote.com/2015/04/collision-free-string-hashing.html</a></p>\n\n<p>Here is a snippet from the post:</p>\n\n<p>if say we have a character set of capital English letters, then the length of the character set is 26 where A could be represented by the number 0, B by the number 1, C by the number 2 and so on till Z by the number 25. Now, whenever we want to map a string of this character set to a unique number , we perform the same conversion as we did in case of the binary format</p>\n" }, { "answer_id": 49182299, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 1, "selected": false, "text": "<p>\"Murmurhash\" is pretty good on both performance and collisions.</p>\n\n<p>The mentioned thread at \"softwareengineering.stackexchange\" has some tests and Murmur wins.</p>\n\n<p>I wrote my own C# port of MurmurHash 2 to .NET and tested it on a list of 466k English words, got 22 collisions.</p>\n\n<p>The results and implementation are here: <a href=\"https://github.com/jitbit/MurmurHash.net\" rel=\"nofollow noreferrer\">https://github.com/jitbit/MurmurHash.net</a> (disclaimer, I'm involved with this open source project!)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32835/" ]
Is there a way of ordering a list of objects by a count of a property which is a collection? For arguments sake let's say I have a question object with a question name property, a property that is a collection of answer objects and another property that is a collection of user objects. The users join the question table via foreign key on question table and answers are joined with middle joining table. If I want nhibernate to get a list of "question" objects could I order it by Question.Answers.Count? i've tried the documentation's example using HQL: ``` List<Question> list = nhelper.NHibernateSession .CreateQuery("Select q from Question q left join q.Answers a group by q,a order by count(a)") .List<Question>(); ``` but i get ``` "column Question.Name is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" ``` I've tried adding all the properties to the group by list but it doesn't work. What happens then is that foreign key userId causes the same error as above but i can't include it in the group by as nhibernate lists it as ``` Question.Users.UserId ``` which doesn't solve it if included. any ideas?
Forget about the term "best". No matter which hash algorithm anyone might come up with, unless you have a very limited set of data that needs to be hashed, every algorithm that performs very well on average can become completely useless if only being fed with the right (or from your perspective "wrong") data. Instead of wasting too much time thinking about how to get the hash more collision-free without using too much CPU time, I'd rather start thinking about "How to make collisions less problematic". E.g. if every hash bucket is in fact a table and all strings in this table (that had a collision) are sorted alphabetically, you can search within a bucket table using binary search (which is only O(log n)) and that means, even when every second hash bucket has 4 collisions, your code will still have decent performance (it will be a bit slower compared to a collision free table, but not that much). One big advantage here is that if your table is big enough and your hash is not too simple, two strings resulting in the same hash value will usually look completely different (hence the binary search can stop comparing strings after maybe one or two characters on average; making every compare very fast). Actually I had a situation myself before where searching directly within a sorted table using binary search turned out to be faster than hashing! Even though my hash algorithm was simple, it took quite some time to hash the values. Performance testing showed that only if I get more than about 700-800 entries, hashing is indeed faster than binary search. However, as the table could never grow larger than 256 entries anyway and as the average table was below 10 entries, benchmarking clearly showed that on every system, every CPU, the binary search was faster. Here, the fact that usually already comparing the first byte of the data was enough to lead to the next bsearch iteration (as the data used to be very different in the first one to two byte already) turned out as a big advantage. So to summarize: I'd take a decent hash algorithm, that doesn't cause too many collisions on average and is rather fast (I'd even accept some more collisions, if it's just very fast!) and rather optimize my code how to get the smallest performance penalty once collisions do occur (and they will! They will unless your hash space is at least equal or bigger than your data space and you can map a unique hash value to every possible set of data).
251,379
<p>I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this:</p> <p>What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data?</p> <p>I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me.</p> <p>Note: We are using .NET 2.0</p>
[ { "answer_id": 251452, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": true, "text": "<p>I personally find that using the </p>\n\n<pre><code>control.DataSource = YourSource;\ncontrol.DataBind();\n</code></pre>\n\n<p>process is much easier, you don't have to do the iteration, and overall reduces LOC.</p>\n\n<p>If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.</p>\n" }, { "answer_id": 251475, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 1, "selected": false, "text": "<p>Data binding is much easier to set up, less error prone overall, reduces LOC significantly (as Mitchel Sellers said), and, a few minor glitches aside, works fairly reliably.</p>\n\n<p>In my experience, you only actually need full manual control if you need to specify the exact update order or timing for data bound controls.</p>\n" }, { "answer_id": 251589, "author": "MarcE", "author_id": 7262, "author_profile": "https://Stackoverflow.com/users/7262", "pm_score": 0, "selected": false, "text": "<p>It can be useful to manually bind if you've got a complex input scenario. With databound input controls you can find that you only know you've got bad data when it hits the DB and throws an exception (badly formatted date/time, integer out of correct range etc). </p>\n\n<p>You can obviously handle this with the various validation / pre-commit events on the data controls but it can be easier (and more obviously readable) to just manually validate your input and post it when you know it's correct.</p>\n\n<p>That's the only reason I can think of and it's only applicable for input. If you're in a read-only scenario then databinding is a no-brainer.</p>\n" }, { "answer_id": 2391948, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 0, "selected": false, "text": "<p>My experiences were quite the opposite to my previous posters here. <a href=\"http://aaronfeng.blogspot.com/2006/05/databinding-is-evil.html\" rel=\"nofollow noreferrer\">This blog entry</a> (dated 2006) summarizes my feelings about databinding.</p>\n" }, { "answer_id": 9407970, "author": "plc training in chennai", "author_id": 1227586, "author_profile": "https://Stackoverflow.com/users/1227586", "pm_score": 1, "selected": false, "text": "<p>Information joining is much simpler to set up, less problem subject overall, lowers LOC considerably, and, a few modest mistakes aside, will work pretty easily. In my experience, you only actually need full guide control if you need to specify the actual up-date order or time for details certain handles.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this: What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data? I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me. Note: We are using .NET 2.0
I personally find that using the ``` control.DataSource = YourSource; control.DataBind(); ``` process is much easier, you don't have to do the iteration, and overall reduces LOC. If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.
251,389
<p>How do you display a Silverlight 2.0 application in a Vista Sidebar gadget? Whenever I load a gadget with the standard Silverlight 2 object tag, I get the no-silverlight default content instead of the app. So, what's the trick to allowing it to run?</p> <p>This is how I am currently trying to pull it off:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Unicode" /&gt; &lt;title&gt;Silverlight Test&lt;/title&gt; &lt;style type="text/css"&gt; body { margin: 0; width: 130px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%"&gt; &lt;param name="source" value="GTest.xap"/&gt; &lt;param name="background" value="transparent" /&gt; &lt;param name="minRuntimeVersion" value="2.0.31005.0" /&gt; &lt;param name="autoUpgrade" value="true" /&gt; &lt;param name="windowless" value="true" /&gt; Get Silverlight &lt;/object&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is there a setting I can use in IE that affects the sidebar so it will allow Silverlight to execute?</p> <p>Even if I can get it working just on my computer, that would be a good start.</p>
[ { "answer_id": 253910, "author": "Gordon Mackie JoanMiro", "author_id": 15778, "author_profile": "https://Stackoverflow.com/users/15778", "pm_score": 4, "selected": true, "text": "<p>It seems with the release version of Silverlight 2 the source parameter changed and has to be a URI - see this thread from the Silverlight forums: <a href=\"http://silverlight.net/forums/p/30968/99824.aspx\" rel=\"nofollow noreferrer\">http://silverlight.net/forums/p/30968/99824.aspx</a></p>\n" }, { "answer_id": 254280, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 3, "selected": false, "text": "<p>Just to clarify for future generations:</p>\n\n<p>Changing the source value to \"x-gadget://ClientBin/GTest.xap\" did the trick.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ]
How do you display a Silverlight 2.0 application in a Vista Sidebar gadget? Whenever I load a gadget with the standard Silverlight 2 object tag, I get the no-silverlight default content instead of the app. So, what's the trick to allowing it to run? This is how I am currently trying to pull it off: ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=Unicode" /> <title>Silverlight Test</title> <style type="text/css"> body { margin: 0; width: 130px; } </style> </head> <body> <object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="GTest.xap"/> <param name="background" value="transparent" /> <param name="minRuntimeVersion" value="2.0.31005.0" /> <param name="autoUpgrade" value="true" /> <param name="windowless" value="true" /> Get Silverlight </object> </body> </html> ``` Is there a setting I can use in IE that affects the sidebar so it will allow Silverlight to execute? Even if I can get it working just on my computer, that would be a good start.
It seems with the release version of Silverlight 2 the source parameter changed and has to be a URI - see this thread from the Silverlight forums: <http://silverlight.net/forums/p/30968/99824.aspx>
251,391
<p>The <a href="https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/c5kehkcz(v=vs.110)" rel="noreferrer">MSDN documentation</a> says that</p> <pre><code>public class SomeObject { public void SomeOperation() { lock(this) { //Access instance variables } } } </code></pre> <p>is &quot;a problem if the instance can be accessed publicly&quot;. I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?</p>
[ { "answer_id": 251399, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": false, "text": "<p>Because if people can get at your object instance (ie: your <code>this</code>) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on <code>this</code> internally, so this may cause problems (possibly a deadlock)</p>\n\n<p>In addition to this, it's also bad practice, because it's locking \"too much\"</p>\n\n<p>For example, you might have a member variable of <code>List&lt;int&gt;</code>, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.</p>\n" }, { "answer_id": 251412, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 5, "selected": false, "text": "<p>...and the exact same arguments apply to this construct as well:</p>\n\n<pre><code>lock(typeof(SomeObject))\n</code></pre>\n" }, { "answer_id": 251416, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 5, "selected": false, "text": "<p>Take a look at the MSDN Topic <a href=\"http://msdn.microsoft.com/en-us/library/ms173179.aspx\" rel=\"noreferrer\">Thread Synchronization (C# Programming Guide)</a></p>\n\n<blockquote>\n <p>Generally, it is best to avoid locking\n on a public type, or on object\n instances beyond the control of your\n application. For example, lock(this)\n can be problematic if the instance can\n be accessed publicly, because code\n beyond your control may lock on the\n object as well. <b>This could create\n deadlock situations where two or more\n threads wait for the release of the\n same object</b>. Locking on a public\n data type, as opposed to an object,\n can cause problems for the same\n reason. Locking on literal strings is\n especially risky because literal\n strings are interned by the common\n language runtime (CLR). This means\n that there is one instance of any\n given string literal for the entire\n program, the exact same object\n represents the literal in all running\n application domains, on all threads.\n As a result, a lock placed on a string\n with the same contents anywhere in the\n application process locks all\n instances of that string in the\n application. As a result, it is best\n to lock a private or protected member\n that is not interned. Some classes\n provide members specifically for\n locking. The Array type, for example,\n provides SyncRoot. Many collection\n types provide a SyncRoot member as\n well.</p>\n</blockquote>\n" }, { "answer_id": 251431, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 1, "selected": false, "text": "<p>Because any chunk of code that can see the instance of your class can also lock on that reference. You want to hide (encapsulate) your locking object so that only code that needs to reference it can reference it. The keyword this refers to the current class instance, so any number of things could have reference to it and could use it to do thread synchronization.</p>\n\n<p>To be clear, this is bad because some other chunk of code could use the class instance to lock, and might prevent your code from obtaining a timely lock or could create other thread sync problems. Best case: nothing else uses a reference to your class to lock. Middle case: something uses a reference to your class to do locks and it causes performance problems. Worst case: something uses a reference of your class to do locks and it causes really bad, really subtle, really hard-to-debug problems.</p>\n" }, { "answer_id": 251539, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "<p>There's also some good discussion about this here: <a href=\"https://stackoverflow.com/questions/46909/is-this-the-proper-use-of-a-mutex\">Is this the proper use of a mutex?</a> </p>\n" }, { "answer_id": 251668, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 10, "selected": true, "text": "<p>It is bad form to use <code>this</code> in lock statements because it is generally out of your control who else might be locking on that object.</p>\n\n<p>In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.</p>\n\n<p>A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using <code>this</code> violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on <code>this</code> unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.</p>\n\n<p>Finally, there is the common misconception that <code>lock(this)</code> actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is <strong>false</strong>. The object passed as a parameter to <code>lock</code> merely serves as a <strong>key</strong>. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.</p>\n\n<p>This is why it's bad to use strings as the keys in <code>lock</code> statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an <code>Object</code> instance will do nicely.</p>\n\n<p>Run the following C# code as an example.</p>\n\n<pre><code>public class Person\n{\n public int Age { get; set; }\n public string Name { get; set; }\n\n public void LockThis()\n {\n lock (this)\n {\n System.Threading.Thread.Sleep(10000);\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var nancy = new Person {Name = \"Nancy Drew\", Age = 15};\n var a = new Thread(nancy.LockThis);\n a.Start();\n var b = new Thread(Timewarp);\n b.Start(nancy);\n Thread.Sleep(10);\n var anotherNancy = new Person { Name = \"Nancy Drew\", Age = 50 };\n var c = new Thread(NameChange);\n c.Start(anotherNancy);\n a.Join();\n Console.ReadLine();\n }\n\n static void Timewarp(object subject)\n {\n var person = subject as Person;\n if (person == null) throw new ArgumentNullException(\"subject\");\n // A lock does not make the object read-only.\n lock (person.Name)\n {\n while (person.Age &lt;= 23)\n {\n // There will be a lock on 'person' due to the LockThis method running in another thread\n if (Monitor.TryEnter(person, 10) == false)\n {\n Console.WriteLine(\"'this' person is locked!\");\n }\n else Monitor.Exit(person);\n person.Age++;\n if(person.Age == 18)\n {\n // Changing the 'person.Name' value doesn't change the lock...\n person.Name = \"Nancy Smith\";\n }\n Console.WriteLine(\"{0} is {1} years old.\", person.Name, person.Age);\n }\n }\n }\n\n static void NameChange(object subject)\n {\n var person = subject as Person;\n if (person == null) throw new ArgumentNullException(\"subject\");\n // You should avoid locking on strings, since they are immutable.\n if (Monitor.TryEnter(person.Name, 30) == false)\n {\n Console.WriteLine(\"Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \\\"Nancy Drew\\\".\");\n }\n else Monitor.Exit(person.Name);\n\n if (Monitor.TryEnter(\"Nancy Drew\", 30) == false)\n {\n Console.WriteLine(\"Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!\");\n }\n else Monitor.Exit(\"Nancy Drew\");\n if (Monitor.TryEnter(person.Name, 10000))\n {\n string oldName = person.Name;\n person.Name = \"Nancy Callahan\";\n Console.WriteLine(\"Name changed from '{0}' to '{1}'.\", oldName, person.Name);\n }\n else Monitor.Exit(person.Name);\n }\n}\n</code></pre>\n\n<p>Console output</p>\n\n<pre><code>'this' person is locked!\nNancy Drew is 16 years old.\n'this' person is locked!\nNancy Drew is 17 years old.\nFailed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".\n'this' person is locked!\nNancy Smith is 18 years old.\n'this' person is locked!\nNancy Smith is 19 years old.\n'this' person is locked!\nNancy Smith is 20 years old.\nFailed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!\n'this' person is locked!\nNancy Smith is 21 years old.\n'this' person is locked!\nNancy Smith is 22 years old.\n'this' person is locked!\nNancy Smith is 23 years old.\n'this' person is locked!\nNancy Smith is 24 years old.\nName changed from 'Nancy Drew' to 'Nancy Callahan'.\n</code></pre>\n" }, { "answer_id": 9870883, "author": "SOReader", "author_id": 190281, "author_profile": "https://Stackoverflow.com/users/190281", "pm_score": 0, "selected": false, "text": "<p>Sorry guys but I can't agree with the argument that locking this might cause deadlock. You are confusing two things: deadlocking and starving.</p>\n\n<ul>\n<li>You cannot cancel deadlock without interrupting one of the threads so after you get into a deadlock you cannot get out</li>\n<li>Starving will end automatically after one of the threads finishes its job</li>\n</ul>\n\n<p><a href=\"http://imageshack.us/photo/my-images/403/threading.png/\" rel=\"nofollow\">Here</a> is a picture which illustrates the difference.</p>\n\n<p><strong>Conclusion</strong><br>\nYou can still safely use <code>lock(this)</code> if thread starvation is not an issue for you. You still have to keep in mind that when the thread, which is starving thread using <code>lock(this)</code> ends in a lock having your object locked, it will finally end in eternal starvation ;)</p>\n" }, { "answer_id": 10510647, "author": "Craig Tullis", "author_id": 618649, "author_profile": "https://Stackoverflow.com/users/618649", "pm_score": 5, "selected": false, "text": "<p>I know this is an old thread, but because people can still look this up and rely on it, it seems important to point out that <code>lock(typeof(SomeObject))</code> is significantly worse than <code>lock(this)</code>. Having said that; sincere kudos to Alan for pointing out that <code>lock(typeof(SomeObject))</code> is bad practice.</p>\n<p>An instance of <code>System.Type</code> is one of the most generic, coarse-grained objects there is. At the very least, an instance of System.Type is global to an AppDomain, and .NET can run multiple programs in an AppDomain. This means that two entirely different applications could potentially cause interference in one another even to the extent of creating a deadlock if they both try to get a synchronization lock on the same global instance of System.Type.</p>\n<p>So <code>lock(this)</code> isn't particularly robust form, can cause problems and should always raise eyebrows for all the reasons cited. Yet there is widely used, relatively well-respected and apparently stable code like log4net that uses the lock(this) pattern extensively, even though I would personally prefer to see that pattern change.</p>\n<p>But <code>lock(typeof(SomeObject))</code> opens up a whole new and enhanced can of worms.</p>\n<p>For what it's worth.</p>\n" }, { "answer_id": 13168091, "author": "William", "author_id": 1417910, "author_profile": "https://Stackoverflow.com/users/1417910", "pm_score": -1, "selected": false, "text": "<p>There will be a problem if the instance can be accessed publicly because there could be other requests that might be using the same object instance. It's better to use private/static variable.</p>\n" }, { "answer_id": 17031960, "author": "Raj Rao", "author_id": 44815, "author_profile": "https://Stackoverflow.com/users/44815", "pm_score": 1, "selected": false, "text": "<p>Here is some sample code that is simpler to follow (IMO): (Will work in <strong>LinqPad</strong>, reference following namespaces: System.Net and System.Threading.Tasks)</p>\n\n<p>Something to remember is that lock(x) basically is syntactic sugar and what it does is to use Monitor.Enter and then uses a try, catch, finally block to call Monitor.Exit. See: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.enter\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.enter</a> (remarks section)</p>\n\n<blockquote>\n <p>or use the C# lock statement (SyncLock statement in Visual Basic),\n which wraps the Enter and Exit methods in a try…finally block.</p>\n</blockquote>\n\n<pre><code>void Main()\n{\n //demonstrates why locking on THIS is BADD! (you should never lock on something that is publicly accessible)\n ClassTest test = new ClassTest();\n lock(test) //locking on the instance of ClassTest\n {\n Console.WriteLine($\"CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Parallel.Invoke(new Action[]\n {\n () =&gt; {\n //this is there to just use up the current main thread. \n Console.WriteLine($\"CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n },\n //none of these will enter the lock section.\n () =&gt; test.DoWorkUsingThisLock(1),//this will dead lock as lock(x) uses Monitor.Enter\n () =&gt; test.DoWorkUsingMonitor(2), //this will not dead lock as it uses Montory.TryEnter\n });\n }\n}\n\npublic class ClassTest\n{\n public void DoWorkUsingThisLock(int i)\n {\n Console.WriteLine($\"Start ClassTest.DoWorkUsingThisLock {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n lock(this) //this can be bad if someone has locked on this already, as it will cause it to be deadlocked!\n {\n Console.WriteLine($\"Running: ClassTest.DoWorkUsingThisLock {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Thread.Sleep(1000);\n }\n Console.WriteLine($\"End ClassTest.DoWorkUsingThisLock Done {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n }\n\n public void DoWorkUsingMonitor(int i)\n {\n Console.WriteLine($\"Start ClassTest.DoWorkUsingMonitor {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n if (Monitor.TryEnter(this))\n {\n Console.WriteLine($\"Running: ClassTest.DoWorkUsingMonitor {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Thread.Sleep(1000);\n Monitor.Exit(this);\n }\n else\n {\n Console.WriteLine($\"Skipped lock section! {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n }\n\n Console.WriteLine($\"End ClassTest.DoWorkUsingMonitor Done {i} CurrentThread {Thread.CurrentThread.ManagedThreadId}\");\n Console.WriteLine();\n }\n}\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>CurrentThread 15\nCurrentThread 15\nStart ClassTest.DoWorkUsingMonitor 2 CurrentThread 13\nStart ClassTest.DoWorkUsingThisLock 1 CurrentThread 12\nSkipped lock section! 2 CurrentThread 13\nEnd ClassTest.DoWorkUsingMonitor Done 2 CurrentThread 13\n</code></pre>\n\n<p>Notice that Thread#12 never ends as its dead locked.</p>\n" }, { "answer_id": 17062160, "author": "atlaste", "author_id": 1031591, "author_profile": "https://Stackoverflow.com/users/1031591", "pm_score": 3, "selected": false, "text": "<p>Imagine that you have a skilled secretary at your office that's a shared resource in the department. Once in a while, you rush towards them because you have a task, only to hope that another one of your co-workers has not already claimed them. Usually you only have to wait for a brief period of time. </p>\n\n<p>Because caring is sharing, your manager decides that customers can use the secretary directly as well. But this has a side effect: A customer might even claim them while you're working for this customer and you also need them to execute part of the tasks. A deadlock occurs, because claiming is no longer a hierarchy. This could have been avoided all together by not allowing customers to claim them in the first place. </p>\n\n<p><code>lock(this)</code> is bad as we've seen. An outside object might lock on the object and since you don't control who's using the class, anyone can lock on it... Which is the exact example as described above. Again, the solution is to limit exposure of the object. However, if you have a <code>private</code>, <code>protected</code> or <code>internal</code> class you <em>could already control who is locking on your object</em>, because you're sure that you've written your code yourself. So the message here is: don't expose it as <code>public</code>. Also, ensuring that a lock is used in similar scenario's avoids deadlocks.</p>\n\n<p>The complete opposite of this is to lock on resources that are shared throughout the app domain -- the worst case scenario. It's like putting your secretary outside and allowing everyone out there to claim them. The result is utter chaos - or in terms of source code: it was a bad idea; throw it away and start over. So how do we do that?</p>\n\n<p>Types are shared in the app domain as most people here point out. But there are even better things we can use: strings. The reason is that strings <em>are pooled</em>. In other words: if you have two strings that have the same contents in an app domain, there's a chance that they have the exact same pointer. Since the pointer is used as the lock key, what you basically get is a synonym for \"prepare for undefined behavior\".</p>\n\n<p>Similarly, you shouldn't lock on WCF objects, HttpContext.Current, Thread.Current, Singletons (in general), etc. The easiest way to avoid all of this? <code>private [static] object myLock = new object();</code></p>\n" }, { "answer_id": 22585601, "author": "ItsAllABadJoke", "author_id": 1070409, "author_profile": "https://Stackoverflow.com/users/1070409", "pm_score": 2, "selected": false, "text": "<p>Locking on the <em>this</em> pointer can be <em>bad</em> if you are locking over a <em>shared resource</em>. A shared resource can be a static variable or a file on your computer - i.e. something that is shared between all users of the class. The reason is that the this pointer will contain a different reference to a location in memory each time your class is instantiated. So, locking over <em>this</em> in once instance of a class is different than locking over <em>this</em> in another instance of a class.</p>\n\n<p>Check out this code to see what I mean. Add the following code to your main program in a Console application:</p>\n\n<pre><code> static void Main(string[] args)\n {\n TestThreading();\n Console.ReadLine();\n }\n\n public static void TestThreading()\n {\n Random rand = new Random();\n Thread[] threads = new Thread[10];\n TestLock.balance = 100000;\n for (int i = 0; i &lt; 10; i++)\n {\n TestLock tl = new TestLock();\n Thread t = new Thread(new ThreadStart(tl.WithdrawAmount));\n threads[i] = t;\n }\n for (int i = 0; i &lt; 10; i++)\n {\n threads[i].Start();\n }\n Console.Read();\n }\n</code></pre>\n\n<p>Create a new class like the below.</p>\n\n<pre><code> class TestLock\n{\n public static int balance { get; set; }\n public static readonly Object myLock = new Object();\n\n public void Withdraw(int amount)\n {\n // Try both locks to see what I mean\n // lock (this)\n lock (myLock)\n {\n Random rand = new Random();\n if (balance &gt;= amount)\n {\n Console.WriteLine(\"Balance before Withdrawal : \" + balance);\n Console.WriteLine(\"Withdraw : -\" + amount);\n balance = balance - amount;\n Console.WriteLine(\"Balance after Withdrawal : \" + balance);\n }\n else\n {\n Console.WriteLine(\"Can't process your transaction, current balance is : \" + balance + \" and you tried to withdraw \" + amount);\n }\n }\n\n }\n public void WithdrawAmount()\n {\n Random rand = new Random();\n Withdraw(rand.Next(1, 100) * 100);\n }\n}\n</code></pre>\n\n<p>Here is a run of the program locking on <em>this</em>.</p>\n\n<pre><code> Balance before Withdrawal : 100000\n Withdraw : -5600\n Balance after Withdrawal : 94400\n Balance before Withdrawal : 100000\n Balance before Withdrawal : 100000\n Withdraw : -5600\n Balance after Withdrawal : 88800\n Withdraw : -5600\n Balance after Withdrawal : 83200\n Balance before Withdrawal : 83200\n Withdraw : -9100\n Balance after Withdrawal : 74100\n Balance before Withdrawal : 74100\n Withdraw : -9100\n Balance before Withdrawal : 74100\n Withdraw : -9100\n Balance after Withdrawal : 55900\n Balance after Withdrawal : 65000\n Balance before Withdrawal : 55900\n Withdraw : -9100\n Balance after Withdrawal : 46800\n Balance before Withdrawal : 46800\n Withdraw : -2800\n Balance after Withdrawal : 44000\n Balance before Withdrawal : 44000\n Withdraw : -2800\n Balance after Withdrawal : 41200\n Balance before Withdrawal : 44000\n Withdraw : -2800\n Balance after Withdrawal : 38400\n</code></pre>\n\n<p>Here is a run of the program locking on <em>myLock</em>.</p>\n\n<pre><code>Balance before Withdrawal : 100000\nWithdraw : -6600\nBalance after Withdrawal : 93400\nBalance before Withdrawal : 93400\nWithdraw : -6600\nBalance after Withdrawal : 86800\nBalance before Withdrawal : 86800\nWithdraw : -200\nBalance after Withdrawal : 86600\nBalance before Withdrawal : 86600\nWithdraw : -8500\nBalance after Withdrawal : 78100\nBalance before Withdrawal : 78100\nWithdraw : -8500\nBalance after Withdrawal : 69600\nBalance before Withdrawal : 69600\nWithdraw : -8500\nBalance after Withdrawal : 61100\nBalance before Withdrawal : 61100\nWithdraw : -2200\nBalance after Withdrawal : 58900\nBalance before Withdrawal : 58900\nWithdraw : -2200\nBalance after Withdrawal : 56700\nBalance before Withdrawal : 56700\nWithdraw : -2200\nBalance after Withdrawal : 54500\nBalance before Withdrawal : 54500\nWithdraw : -500\nBalance after Withdrawal : 54000\n</code></pre>\n" }, { "answer_id": 25319099, "author": "Vikrant", "author_id": 1302617, "author_profile": "https://Stackoverflow.com/users/1302617", "pm_score": 2, "selected": false, "text": "<p>There is very good article about it <a href=\"http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects\" rel=\"nofollow noreferrer\">http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects</a> by Rico Mariani, performance architect for the Microsoft® .NET runtime</p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n <p>The basic problem here is that you don't own the type object, and you\n don't know who else could access it. In general, it's a very bad idea\n to rely on locking an object you didn't create and don't know who else\n might be accessing. Doing so invites deadlock. The safest way is to\n only lock private objects.</p>\n</blockquote>\n" }, { "answer_id": 27279352, "author": "Dhruv Rangunwala", "author_id": 2174507, "author_profile": "https://Stackoverflow.com/users/2174507", "pm_score": 1, "selected": false, "text": "<p>Please refer to the following link which explains why lock (this) is not a good idea.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices</a></p>\n\n<p>So the solution is to add a private object, for example, lockObject to the class and place the code region inside the lock statement as shown below:</p>\n\n<pre><code>lock (lockObject)\n{\n...\n}\n</code></pre>\n" }, { "answer_id": 51567344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here's a much simpler illustration (taken from <a href=\"https://gridwizard.wordpress.com/2014/06/17/technical-interviews-net-developers\" rel=\"nofollow noreferrer\">Question 34 here</a>) why lock(this) is bad and may result in deadlocks when consumer of your class also try to lock on the object.\nBelow, only one of three thread can proceed, the other two are deadlocked.</p>\n\n<blockquote>\n<pre><code>class SomeClass\n{\n public void SomeMethod(int id)\n {\n **lock(this)**\n {\n while(true)\n {\n Console.WriteLine(\"SomeClass.SomeMethod #\" + id);\n }\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n SomeClass o = new SomeClass();\n\n lock(o)\n {\n for (int threadId = 0; threadId &lt; 3; threadId++)\n {\n Thread t = new Thread(() =&gt; {\n o.SomeMethod(threadId);\n });\n t.Start();\n }\n\n Console.WriteLine();\n }\n</code></pre>\n</blockquote>\n\n<p>To work around, this guy used Thread.TryMonitor (with timeout) instead of lock:</p>\n\n<blockquote>\n<pre><code> Monitor.TryEnter(temp, millisecondsTimeout, ref lockWasTaken);\n if (lockWasTaken)\n {\n doAction();\n }\n else\n {\n throw new Exception(\"Could not get lock\");\n }\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://blogs.appbeat.io/post/c-how-to-lock-without-deadlocks\" rel=\"nofollow noreferrer\">https://blogs.appbeat.io/post/c-how-to-lock-without-deadlocks</a></p>\n" }, { "answer_id": 54585517, "author": "zumalifeguard", "author_id": 75129, "author_profile": "https://Stackoverflow.com/users/75129", "pm_score": 1, "selected": false, "text": "<p>You can establish a rule that says that a class can have code that locks on 'this' or any object that the code in the class instantiates. So it's only a problem if the pattern is not followed.</p>\n\n<p>If you want to protect yourself from code that won't follow this pattern, then the accepted answer is correct. But if the pattern is followed, it's not a problem.</p>\n\n<p>The advantage of lock(this) is efficiency. What if you have a simple \"value object\" that holds a single value. It's just a wrapper, and it gets instantiated millions of times. By requiring the creation of a private sync object just for locking, you've basically doubled the size of the object and doubled the number of allocations. When performance matters, this is an advantage.</p>\n\n<p>When you don't care about number of allocations or memory footprint, avoiding lock(this) is preferable for the reasons indicated in other answers.</p>\n" }, { "answer_id": 71479913, "author": "Rzassar", "author_id": 862795, "author_profile": "https://Stackoverflow.com/users/862795", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices#general-recommendations\" rel=\"nofollow noreferrer\">Here</a> is why it is not recommended.</p>\n<p><strong>Short version:</strong><br />\nConsider the following code snippet:</p>\n<pre><code>object foo = new Object(); \nobject bar = foo; \n\nlock(foo)\n{\n lock(bar){}\n} \n</code></pre>\n<p>Here, foo and bar are referring to a same instance of object causing deadlock. That is the simplified version of what may happens in reality.</p>\n<p><strong>Longer version:</strong><br />\nTo explain it more according to the following code snippet, consider you wrote a class (<code>SomeClass</code> in this example) and consumer of your class (a coder named &quot;John&quot;) wants to acquire a lock over an instance of your class (<code>someObject</code> in this example). He encounters a deadlock because he gets a lock over instance <code>someObject</code> and inside this lock he calls a method of that instance (<code>SomeMethod()</code>) which internally acquires a lock over the exact same instance.</p>\n<ul>\n<li><p>I could have written the following example with or without Task/Thread and the gist of deadlock still remains the same.</p>\n</li>\n<li><p>To prevent bizarre situation where the main Thread finishes while its children are still running, I used <code>.Wait()</code>. However, in long-running-tasks or situation where a code-snippet executes more frequently, you would definitely see the same behavior.</p>\n</li>\n<li><p>Although John applied a bad practice of using an instance of a class as a lock-object, but we (as the developer of a classlibrary <code>SomeClass</code>) should deter such situation simple by not using <code>this</code> as a lock-object in our class.</p>\n</li>\n<li><p>Instead, we should declare a simple private field and use that as our lock-object.</p>\n<pre><code> using System;\n using System.Threading;\n using System.Threading.Tasks;\n\n class SomeClass\n {\n public void SomeMethod()\n {\n //NOTE: Locks over an object that is already locked by the caller.\n // Hence, the following code-block never executes.\n lock (this)\n {\n Console.WriteLine(&quot;Hi&quot;);\n }\n }\n }\n\n public class Program\n {\n public static void Main()\n {\n SomeClass o = new SomeClass();\n\n lock (o)\n {\n Task.Run(() =&gt; o.SomeMethod()).Wait();\n }\n\n Console.WriteLine(&quot;Finish&quot;);\n }\n }\n</code></pre>\n</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341413/" ]
The [MSDN documentation](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/c5kehkcz(v=vs.110)) says that ``` public class SomeObject { public void SomeOperation() { lock(this) { //Access instance variables } } } ``` is "a problem if the instance can be accessed publicly". I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?
It is bad form to use `this` in lock statements because it is generally out of your control who else might be locking on that object. In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness. A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using `this` violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on `this` unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal. Finally, there is the common misconception that `lock(this)` actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is **false**. The object passed as a parameter to `lock` merely serves as a **key**. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed. This is why it's bad to use strings as the keys in `lock` statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an `Object` instance will do nicely. Run the following C# code as an example. ``` public class Person { public int Age { get; set; } public string Name { get; set; } public void LockThis() { lock (this) { System.Threading.Thread.Sleep(10000); } } } class Program { static void Main(string[] args) { var nancy = new Person {Name = "Nancy Drew", Age = 15}; var a = new Thread(nancy.LockThis); a.Start(); var b = new Thread(Timewarp); b.Start(nancy); Thread.Sleep(10); var anotherNancy = new Person { Name = "Nancy Drew", Age = 50 }; var c = new Thread(NameChange); c.Start(anotherNancy); a.Join(); Console.ReadLine(); } static void Timewarp(object subject) { var person = subject as Person; if (person == null) throw new ArgumentNullException("subject"); // A lock does not make the object read-only. lock (person.Name) { while (person.Age <= 23) { // There will be a lock on 'person' due to the LockThis method running in another thread if (Monitor.TryEnter(person, 10) == false) { Console.WriteLine("'this' person is locked!"); } else Monitor.Exit(person); person.Age++; if(person.Age == 18) { // Changing the 'person.Name' value doesn't change the lock... person.Name = "Nancy Smith"; } Console.WriteLine("{0} is {1} years old.", person.Name, person.Age); } } } static void NameChange(object subject) { var person = subject as Person; if (person == null) throw new ArgumentNullException("subject"); // You should avoid locking on strings, since they are immutable. if (Monitor.TryEnter(person.Name, 30) == false) { Console.WriteLine("Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\"."); } else Monitor.Exit(person.Name); if (Monitor.TryEnter("Nancy Drew", 30) == false) { Console.WriteLine("Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!"); } else Monitor.Exit("Nancy Drew"); if (Monitor.TryEnter(person.Name, 10000)) { string oldName = person.Name; person.Name = "Nancy Callahan"; Console.WriteLine("Name changed from '{0}' to '{1}'.", oldName, person.Name); } else Monitor.Exit(person.Name); } } ``` Console output ``` 'this' person is locked! Nancy Drew is 16 years old. 'this' person is locked! Nancy Drew is 17 years old. Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string "Nancy Drew". 'this' person is locked! Nancy Smith is 18 years old. 'this' person is locked! Nancy Smith is 19 years old. 'this' person is locked! Nancy Smith is 20 years old. Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining! 'this' person is locked! Nancy Smith is 21 years old. 'this' person is locked! Nancy Smith is 22 years old. 'this' person is locked! Nancy Smith is 23 years old. 'this' person is locked! Nancy Smith is 24 years old. Name changed from 'Nancy Drew' to 'Nancy Callahan'. ```
251,395
<p>Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?</p> <p>Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc</p> <p>Thanks</p>
[ { "answer_id": 251410, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 4, "selected": true, "text": "<p>Don't know about a library, but you can use to check if the querystring exists:</p>\n\n<pre><code>if (!String.IsNullOrEmpty(Request.Querystring[\"foo\"]))\n{\n // check further\n}\nelse\n{\n // not there, do something else\n}\n</code></pre>\n\n<p>If you want to use Reglar Expressions to further validate, you can create a class that accepts the string and return a boolean.</p>\n\n<pre><code>public static Boolean IsValid(String s)\n{\n const String sRegEx = @\"regex here\";\n\n Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n MatchCollection oMatches = oRegEx.Matches(s);\n\n return (oMatches.Count &gt; 0) ? true : false;\n}\n</code></pre>\n\n<p>This is a good free program to help you build the regluar expressions: <a href=\"http://www.ultrapico.com/expresso.htm\" rel=\"nofollow noreferrer\">Expresso</a></p>\n" }, { "answer_id": 251426, "author": "Josh Hinman", "author_id": 2527, "author_profile": "https://Stackoverflow.com/users/2527", "pm_score": 1, "selected": false, "text": "<p>Do you mean to ask about breaking the query string into its parts? ASP.Net already does that for you. You can access the individual paramaters via the Request.QueryString collection.</p>\n\n<p>For the query string: ?fruit=apple&amp;socks=white</p>\n\n<p>Request.QueryString[\"fruit\"] will give you \"apple\", and Request.QueryString[\"socks\"] will give you \"white\".</p>\n" }, { "answer_id": 251465, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 1, "selected": false, "text": "<p>If you're talking about validating the query string for requests as they come in, the .NET Framework already does this. Page has a property called ValidateRequest that's true by default, and anything invalid in the query string will cause an error (the first time the query string is accessed in your code behind) without your having to do anything.</p>\n\n<p>If you're talking about validating query strings you have as data or something, then <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163462.aspx\" rel=\"nofollow noreferrer\">this MSDN Mag article</a> may help you.</p>\n\n<p>EDIT: I see you're asking more about data validation. You should find some good stuff in the MSDN article I linked above.</p>\n" }, { "answer_id": 251575, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 2, "selected": false, "text": "<p>The best approach for this sort of thing would probably be to use regular expressions to check whatever condition you are looking for.</p>\n\n<p>It would be good in an actual scenario to separate the validation from the presentation but just for the sake of an example: </p>\n\n<pre><code> if (!string.IsNullOrEmpty(Request.QueryString[\"Variable\"]))\n {\n string s = Request.QueryString[\"Variable\"];\n\n Regex regularExpression = new Regex(\"Put your regex here\");\n\n if (regularExpression.IsMatch(s))\n {\n // Do what you want.\n }\n }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings? Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc Thanks
Don't know about a library, but you can use to check if the querystring exists: ``` if (!String.IsNullOrEmpty(Request.Querystring["foo"])) { // check further } else { // not there, do something else } ``` If you want to use Reglar Expressions to further validate, you can create a class that accepts the string and return a boolean. ``` public static Boolean IsValid(String s) { const String sRegEx = @"regex here"; Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); MatchCollection oMatches = oRegEx.Matches(s); return (oMatches.Count > 0) ? true : false; } ``` This is a good free program to help you build the regluar expressions: [Expresso](http://www.ultrapico.com/expresso.htm)
251,396
<p>I am currently developing a Java app which handles a SOAP webservice. </p> <p>The problem lies after I parse the WSDL [the <strong>Parser</strong> object from Apache Axis does it for me], and I create the call. </p> <p>When I try to invoke it, I have to pass a Object[] to assign the parameters [taken from the Action of the WSDL]. A normal action is easy, but when I have custom datatypes, I can't get it to fill it out for me. I try to pass Object[]{ new Object { }}, but it assigns the first field instead. I can't pass it already processed, because it changes the '&lt; >' to '--lt --gt', and the server doesn't recognize it'.</p> <p>This is a fragment of the WSDL.</p> <blockquote> <pre><code> &lt;s:element name="FERecuperaQTYRequest"&gt; &lt;s:complexType&gt; &lt;s:sequence&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="argAuth" type="tns:FEAuthRequest" /&gt; &lt;/s:sequence&gt; &lt;/s:complexType&gt; &lt;/s:element&gt; &lt;s:complexType name="FEAuthRequest"&gt; &lt;s:sequence&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="Token" type="s:string" /&gt; &lt;s:element minOccurs="0" maxOccurs="1" name="Sign" type="s:string" /&gt; &lt;s:element minOccurs="1" maxOccurs="1" name="cuit" type="s:long" /&gt; &lt;/s:sequence&gt; &lt;/s:complexType&gt; </code></pre> </blockquote> <p>And this is the troublesome Java Fragment</p> <pre><code> QTY = (String) call.invoke ( new Object[]{ new Object[]{ tokenConexion.getToken (), tokenConexion.getSign (), tokenConexion.getCUIT () } }); </code></pre>
[ { "answer_id": 251443, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<p>Have you looked into using something like Spring's proxy functionality? You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side!</p>\n\n<p>Example Spring config:</p>\n\n<pre><code>&lt;bean id=\"myService\" class=\"org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean\"&gt;\n &lt;property name=\"serviceFactoryClass\" value=\"org.apache.axis.client.ServiceFactory\"/&gt;\n &lt;property name=\"wsdlDocumentUrl\" value=\"classpath://META-INF/myService.wsdl\"/&gt;\n &lt;property name=\"namespaceUri\" value=\"http://com/myService\"/&gt;\n &lt;property name=\"endpointAddress\" value=\"http://server/MyService\"/&gt;\n &lt;property name=\"serviceName\" value=\"MyService\"/&gt;\n &lt;property name=\"portName\" value=\"MyService\"/&gt;\n &lt;property name=\"serviceInterface\" value=\"com.IMyService\"/&gt;\n &lt;property name=\"lookupServiceOnStartup\" value=\"false\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"myClient\" class=\"com.MyServiceClient\"&gt;\n &lt;property name=\"myService\" ref=\"myService\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>Java:</p>\n\n<pre><code>public interface IMyService {\n Foo getFoo();\n}\n\npublic class MyServiceClient {\n private IMyService myService;\n public void setMyService(IMyService myService) {\n this.myService = myService;\n }\n\n public void DoStuff() {\n Foo foo = myService.getFoo();\n ...\n }\n}\n</code></pre>\n\n<p>For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean:</p>\n\n<pre><code>public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {\nprotected void postProcessJaxRpcService(Service service) {\n TypeMappingRegistry registry = service.getTypeMappingRegistry();\n TypeMapping mapping = registry.createTypeMapping();\n QName qName = new QName(\"http://com/myService\", \"Foo\");\n mapping.register(Foo.class, qName,\n new BeanSerializerFactory(Foo.class, qName),\n new BeanDeserializerFactory(Foo.class, qName));\n }\n}\n</code></pre>\n\n<p>What I love about this is that code that <em>shouldn't</em> care about the implementation of the service <em>doesn't</em>. Testing becomes a breeze, and the cohesion of your classes is <em>much</em> better.</p>\n" }, { "answer_id": 251982, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>We tried to use complex objects and Axis. Don't! We had a bunch of problems with Dotnet being able to create a correct object from the WSDL. We ended up just using primitives, strings, and arrays. If someone has a good method of using complex object I would love to hear it.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4749/" ]
I am currently developing a Java app which handles a SOAP webservice. The problem lies after I parse the WSDL [the **Parser** object from Apache Axis does it for me], and I create the call. When I try to invoke it, I have to pass a Object[] to assign the parameters [taken from the Action of the WSDL]. A normal action is easy, but when I have custom datatypes, I can't get it to fill it out for me. I try to pass Object[]{ new Object { }}, but it assigns the first field instead. I can't pass it already processed, because it changes the '< >' to '--lt --gt', and the server doesn't recognize it'. This is a fragment of the WSDL. > > > ``` > <s:element name="FERecuperaQTYRequest"> > <s:complexType> > <s:sequence> > <s:element minOccurs="0" maxOccurs="1" name="argAuth" type="tns:FEAuthRequest" /> > </s:sequence> > </s:complexType> > </s:element> > <s:complexType name="FEAuthRequest"> > <s:sequence> > <s:element minOccurs="0" maxOccurs="1" name="Token" type="s:string" /> > <s:element minOccurs="0" maxOccurs="1" name="Sign" type="s:string" /> > <s:element minOccurs="1" maxOccurs="1" name="cuit" type="s:long" /> > </s:sequence> > </s:complexType> > > ``` > > And this is the troublesome Java Fragment ``` QTY = (String) call.invoke ( new Object[]{ new Object[]{ tokenConexion.getToken (), tokenConexion.getSign (), tokenConexion.getCUIT () } }); ```
Have you looked into using something like Spring's proxy functionality? You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side! Example Spring config: ``` <bean id="myService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean"> <property name="serviceFactoryClass" value="org.apache.axis.client.ServiceFactory"/> <property name="wsdlDocumentUrl" value="classpath://META-INF/myService.wsdl"/> <property name="namespaceUri" value="http://com/myService"/> <property name="endpointAddress" value="http://server/MyService"/> <property name="serviceName" value="MyService"/> <property name="portName" value="MyService"/> <property name="serviceInterface" value="com.IMyService"/> <property name="lookupServiceOnStartup" value="false"/> </bean> <bean id="myClient" class="com.MyServiceClient"> <property name="myService" ref="myService"/> </bean> ``` Java: ``` public interface IMyService { Foo getFoo(); } public class MyServiceClient { private IMyService myService; public void setMyService(IMyService myService) { this.myService = myService; } public void DoStuff() { Foo foo = myService.getFoo(); ... } } ``` For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean: ``` public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean { protected void postProcessJaxRpcService(Service service) { TypeMappingRegistry registry = service.getTypeMappingRegistry(); TypeMapping mapping = registry.createTypeMapping(); QName qName = new QName("http://com/myService", "Foo"); mapping.register(Foo.class, qName, new BeanSerializerFactory(Foo.class, qName), new BeanDeserializerFactory(Foo.class, qName)); } } ``` What I love about this is that code that *shouldn't* care about the implementation of the service *doesn't*. Testing becomes a breeze, and the cohesion of your classes is *much* better.
251,401
<p>Does anyone know of any DLLs (preferably .net) that encapsulate the lua 5.1 compiler? I'm working on a .net project where part of it needs to compile lua scripts, and i would rather have a DLL that i could send script code to instead of sending the script to a temporary file and running luac.exe.</p> <p>Edit: I'd need a .NET library that implements luac in such a way that it outputs standard lua bytecode (not a lua library that compiles to the CLR). Compiling the lua c source code didn't work, as when i went to include a reference to the dll in a c# project, visual studio complained that it wasnt a valid assembly. My searches so far haven't found anything.</p>
[ { "answer_id": 251443, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<p>Have you looked into using something like Spring's proxy functionality? You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side!</p>\n\n<p>Example Spring config:</p>\n\n<pre><code>&lt;bean id=\"myService\" class=\"org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean\"&gt;\n &lt;property name=\"serviceFactoryClass\" value=\"org.apache.axis.client.ServiceFactory\"/&gt;\n &lt;property name=\"wsdlDocumentUrl\" value=\"classpath://META-INF/myService.wsdl\"/&gt;\n &lt;property name=\"namespaceUri\" value=\"http://com/myService\"/&gt;\n &lt;property name=\"endpointAddress\" value=\"http://server/MyService\"/&gt;\n &lt;property name=\"serviceName\" value=\"MyService\"/&gt;\n &lt;property name=\"portName\" value=\"MyService\"/&gt;\n &lt;property name=\"serviceInterface\" value=\"com.IMyService\"/&gt;\n &lt;property name=\"lookupServiceOnStartup\" value=\"false\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"myClient\" class=\"com.MyServiceClient\"&gt;\n &lt;property name=\"myService\" ref=\"myService\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>Java:</p>\n\n<pre><code>public interface IMyService {\n Foo getFoo();\n}\n\npublic class MyServiceClient {\n private IMyService myService;\n public void setMyService(IMyService myService) {\n this.myService = myService;\n }\n\n public void DoStuff() {\n Foo foo = myService.getFoo();\n ...\n }\n}\n</code></pre>\n\n<p>For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean:</p>\n\n<pre><code>public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {\nprotected void postProcessJaxRpcService(Service service) {\n TypeMappingRegistry registry = service.getTypeMappingRegistry();\n TypeMapping mapping = registry.createTypeMapping();\n QName qName = new QName(\"http://com/myService\", \"Foo\");\n mapping.register(Foo.class, qName,\n new BeanSerializerFactory(Foo.class, qName),\n new BeanDeserializerFactory(Foo.class, qName));\n }\n}\n</code></pre>\n\n<p>What I love about this is that code that <em>shouldn't</em> care about the implementation of the service <em>doesn't</em>. Testing becomes a breeze, and the cohesion of your classes is <em>much</em> better.</p>\n" }, { "answer_id": 251982, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>We tried to use complex objects and Axis. Don't! We had a bunch of problems with Dotnet being able to create a correct object from the WSDL. We ended up just using primitives, strings, and arrays. If someone has a good method of using complex object I would love to hear it.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19252/" ]
Does anyone know of any DLLs (preferably .net) that encapsulate the lua 5.1 compiler? I'm working on a .net project where part of it needs to compile lua scripts, and i would rather have a DLL that i could send script code to instead of sending the script to a temporary file and running luac.exe. Edit: I'd need a .NET library that implements luac in such a way that it outputs standard lua bytecode (not a lua library that compiles to the CLR). Compiling the lua c source code didn't work, as when i went to include a reference to the dll in a c# project, visual studio complained that it wasnt a valid assembly. My searches so far haven't found anything.
Have you looked into using something like Spring's proxy functionality? You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side! Example Spring config: ``` <bean id="myService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean"> <property name="serviceFactoryClass" value="org.apache.axis.client.ServiceFactory"/> <property name="wsdlDocumentUrl" value="classpath://META-INF/myService.wsdl"/> <property name="namespaceUri" value="http://com/myService"/> <property name="endpointAddress" value="http://server/MyService"/> <property name="serviceName" value="MyService"/> <property name="portName" value="MyService"/> <property name="serviceInterface" value="com.IMyService"/> <property name="lookupServiceOnStartup" value="false"/> </bean> <bean id="myClient" class="com.MyServiceClient"> <property name="myService" ref="myService"/> </bean> ``` Java: ``` public interface IMyService { Foo getFoo(); } public class MyServiceClient { private IMyService myService; public void setMyService(IMyService myService) { this.myService = myService; } public void DoStuff() { Foo foo = myService.getFoo(); ... } } ``` For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean: ``` public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean { protected void postProcessJaxRpcService(Service service) { TypeMappingRegistry registry = service.getTypeMappingRegistry(); TypeMapping mapping = registry.createTypeMapping(); QName qName = new QName("http://com/myService", "Foo"); mapping.register(Foo.class, qName, new BeanSerializerFactory(Foo.class, qName), new BeanDeserializerFactory(Foo.class, qName)); } } ``` What I love about this is that code that *shouldn't* care about the implementation of the service *doesn't*. Testing becomes a breeze, and the cohesion of your classes is *much* better.
251,402
<p>There are <strong>two different</strong> ways to create an empty object in JavaScript:</p> <pre><code>var objectA = {} var objectB = new Object() </code></pre> <p>Is there any difference in how the script engine handles them? Is there any reason to use one over the other?</p> <p>Similarly it is also possible to create an empty array using different syntax:</p> <pre><code>var arrayA = [] var arrayB = new Array() </code></pre>
[ { "answer_id": 251405, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>This is essentially the same thing. Use whatever you find more convenient.</p>\n" }, { "answer_id": 251440, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 4, "selected": false, "text": "<p>These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into. </p>\n\n<p>One other thing: you might have subtle errors if you forget to use the <code>new</code> operator. So, using literals will help you avoid that problem.</p>\n\n<p>Ultimately, it will depend on the situation as well as preference.</p>\n" }, { "answer_id": 251497, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 3, "selected": false, "text": "<pre><code>var objectA = {}\n</code></pre>\n\n<p>is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.</p>\n" }, { "answer_id": 251567, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "<p>The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.</p>\n\n<p>My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...</p>\n" }, { "answer_id": 251743, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 3, "selected": false, "text": "<p>I believe <code>{}</code> was recommended in one of the Javascript vids on <a href=\"http://developer.yahoo.com/yui/theater/\" rel=\"noreferrer\">here</a> as a good coding convention. <code>new</code> is necessary for pseudoclassical inheritance. the <code>var obj = {};</code> way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need <code>new</code> is when you are using constructors functions. For example:</p>\n\n<pre><code>var Mammal = function (name) {\n this.name = name;\n};\n\nMammal.prototype.get_name = function () {\n return this.name;\n}\n\nMammal.prototype.says = function() {\n return this.saying || '';\n}\n</code></pre>\n\n<p>Then it is used like so:</p>\n\n<pre><code>var aMammal = new Mammal('Me warm-blooded');\nvar name = aMammal.get_name();\n</code></pre>\n\n<p>Another advantage to using <code>{}</code> as oppose to <code>new Object</code> is you can use it to do JSON-style object literals. </p>\n" }, { "answer_id": 252110, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 10, "selected": true, "text": "<h2>Objects</h2>\n\n<p>There is no benefit to using <code>new Object();</code> - whereas <code>{};</code> can make your code more compact, and more readable.</p>\n\n<p>For defining empty objects they're technically the same. The <code>{}</code> syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:</p>\n\n<pre><code>var myObject = {\n title: 'Frog',\n url: '/img/picture.jpg',\n width: 300,\n height: 200\n };\n</code></pre>\n\n<h2>Arrays</h2>\n\n<p>For arrays, there's similarly almost no benefit to ever using <code>new Array();</code> over <code>[];</code> - with one minor exception:</p>\n\n<pre><code>var emptyArray = new Array(100);\n</code></pre>\n\n<p>creates a 100 item long array with all slots containing <code>undefined</code> - which may be nice/useful in certain situations (such as <code>(new Array(9)).join('Na-Na ') + 'Batman!'</code>).</p>\n\n<h2>My recommendation</h2>\n\n<ol>\n<li>Never use <code>new Object();</code> - it's clunkier than <code>{};</code> and looks silly.</li>\n<li>Always use <code>[];</code> - except when you need to quickly create an \"empty\" array with a predefined length.</li>\n</ol>\n" }, { "answer_id": 5665204, "author": "Guillermo Snipe", "author_id": 708191, "author_profile": "https://Stackoverflow.com/users/708191", "pm_score": 7, "selected": false, "text": "<p>Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.</p>\n\n<pre><code>var objectA = {} //This is an object literal\n\nvar objectB = new Object() //This is the object constructor\n</code></pre>\n\n<p>In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.</p>\n\n<p>For example: <code>new Object(1)</code>, will return a Number. <code>new Object(\"hello\")</code> will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..</p>\n\n<p>Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.</p>\n\n<p>I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.</p>\n" }, { "answer_id": 38799700, "author": "basickarl", "author_id": 1137669, "author_profile": "https://Stackoverflow.com/users/1137669", "pm_score": 3, "selected": false, "text": "<h2>Array instantiation performance</h2>\n\n<p>If you wish to create an array with no length:</p>\n\n<p><strong><code>var arr = [];</code> is faster than <code>var arr = new Array();</code></strong></p>\n\n<p>If you wish to create an empty array with a certain length:</p>\n\n<p><strong><code>var arr = new Array(x);</code> is faster than <code>var arr = []; arr[x-1] = undefined</code>;</strong></p>\n\n<p>For benchmarks click the following: <a href=\"https://jsfiddle.net/basickarl/ktbbry5b/\" rel=\"noreferrer\">https://jsfiddle.net/basickarl/ktbbry5b/</a></p>\n\n<p><em>I do not however know the memory footprint of both, I can imagine that <code>new Array()</code> takes up more space.</em></p>\n" }, { "answer_id": 44992859, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "<p><strong>OK</strong>, there are just 2 different ways to do the same thing! One called <code>object literal</code> and the other one is a function <code>constructor</code>!</p>\n\n<p>But read on, there are couple of things I'd like to share:</p>\n\n<p>Using <code>{}</code> makes your code more readable, while creating instances of <code>Object</code> or other built-in functions not recommended...</p>\n\n<p>Also, Object function gets parameters as it's a function, like <code>Object(params)</code>... but <code>{}</code> is pure way to start an object in JavaScript...</p>\n\n<p>Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...</p>\n\n<p>While Object in Javascript can be almost anything, <code>{}</code> only points to javascript objects, for the test how it works, do below in your javascript code or console:</p>\n\n<pre><code>var n = new Object(1); //Number {[[PrimitiveValue]]: 1}\n</code></pre>\n\n<p>Surprisingly, it's creating a Number!</p>\n\n<pre><code>var a = new Object([1,2,3]); //[1, 2, 3]\n</code></pre>\n\n<p>And this is creating a Array!</p>\n\n<pre><code>var s = new Object('alireza'); //String {0: \"a\", 1: \"l\", 2: \"i\", 3: \"r\", 4: \"e\", 5: \"z\", 6: \"a\", length: 7, [[PrimitiveValue]]: \"alireza\"}\n</code></pre>\n\n<p>and this weird result for <code>String</code>!</p>\n\n<p>So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using <code>{}</code> is better in my experience!</p>\n" }, { "answer_id": 65141555, "author": "Amit Singh", "author_id": 10561570, "author_profile": "https://Stackoverflow.com/users/10561570", "pm_score": 2, "selected": false, "text": "<pre><code>Var Obj = {};\n</code></pre>\n<p>This is the most used and simplest method.</p>\n<p>Using</p>\n<pre><code>var Obj = new Obj() \n</code></pre>\n<p>is not preferred.</p>\n<p>There is no need to use <code>new Object()</code>.</p>\n<p>For simplicity, readability and execution speed, use the first one (the object literal method).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918/" ]
There are **two different** ways to create an empty object in JavaScript: ``` var objectA = {} var objectB = new Object() ``` Is there any difference in how the script engine handles them? Is there any reason to use one over the other? Similarly it is also possible to create an empty array using different syntax: ``` var arrayA = [] var arrayB = new Array() ```
Objects ------- There is no benefit to using `new Object();` - whereas `{};` can make your code more compact, and more readable. For defining empty objects they're technically the same. The `{}` syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so: ``` var myObject = { title: 'Frog', url: '/img/picture.jpg', width: 300, height: 200 }; ``` Arrays ------ For arrays, there's similarly almost no benefit to ever using `new Array();` over `[];` - with one minor exception: ``` var emptyArray = new Array(100); ``` creates a 100 item long array with all slots containing `undefined` - which may be nice/useful in certain situations (such as `(new Array(9)).join('Na-Na ') + 'Batman!'`). My recommendation ----------------- 1. Never use `new Object();` - it's clunkier than `{};` and looks silly. 2. Always use `[];` - except when you need to quickly create an "empty" array with a predefined length.
251,403
<p>I want to have a map that has a homogeneous key type but heterogeneous data types.</p> <p>I want to be able to do something like (pseudo-code):</p> <pre><code>boost::map&lt;std::string, magic_goes_here&gt; m; m.add&lt;int&gt;("a", 2); m.add&lt;std::string&gt;("b", "black sheep"); int i = m.get&lt;int&gt;("a"); int j = m.get&lt;int&gt;("b"); // error! </code></pre> <p>I could have a pointer to a base class as the data type but would rather not.</p> <p>I've never used boost before but have looked at the fusion library but can't figure out what I need to do.</p> <p>Thanks for your help.</p>
[ { "answer_id": 251423, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.parashift.com/c++-faq/heterogeneous-list.html\" rel=\"noreferrer\">How can I build a &lt;favorite container&gt; of objects of different types?</a></p>\n<blockquote>\n<p>You can't, but you can fake it pretty well. In C/C++ all arrays are homogeneous (i.e., the elements are all the same type). However, with an extra layer of indirection you can give the appearance of a heterogeneous container (a heterogeneous container is a container where the contained objects are of different types).</p>\n<p>There are two cases with heterogeneous containers.</p>\n<p>The first case occurs when all objects you want to store in a container are publicly derived from a common base class. [...]</p>\n<p>The second case occurs when the object types are disjoint — they do not share a common base class.<br />\nThe approach here is to use a handle class. The container is a container of handle objects (by value or by pointer, your choice; by value is easier). Each handle object knows how to &quot;hold on to&quot; (i.e., maintain a pointer to) one of the objects you want to put in the container. You can use either a single handle class with several different types of pointers as instance data, or a hierarchy of handle classes that shadow the various types you wish to contain (requires the container be of handle base class pointers). The downside of this approach is that it opens up the handle class(es) to maintenance every time you change the set of types that can be contained. The benefit is that you can use the handle class(es) to encapsulate most of the ugliness of memory management and object lifetime. Thus using handle objects may be beneficial even in the first case.</p>\n</blockquote>\n" }, { "answer_id": 251425, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": false, "text": "<p>Would <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/any/s02.html\" rel=\"noreferrer\">boost::any</a> do the trick for you?</p>\n" }, { "answer_id": 251624, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "<p>If you want a limited set of types to be supported, <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html\" rel=\"noreferrer\">Boost.Variant</a> should do the trick.</p>\n" }, { "answer_id": 252106, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;boost/any.hpp&gt;\n\nint main()\n{\n try\n {\n std::map&lt;std::string, boost::any&gt; m;\n m[\"a\"] = 2;\n m[\"b\"] = static_cast&lt;char const *&gt;(\"black sheep\");\n\n int i = boost::any_cast&lt;int&gt;(m[\"a\"]);\n std::cout &lt;&lt; \"I(\" &lt;&lt; i &lt;&lt; \")\\n\";\n\n int j = boost::any_cast&lt;int&gt;(m[\"b\"]); // throws exception\n std::cout &lt;&lt; \"J(\" &lt;&lt; j &lt;&lt; \")\\n\";\n }\n catch(...)\n {\n std::cout &lt;&lt; \"Exception\\n\";\n }\n\n}\n</code></pre>\n" }, { "answer_id": 252196, "author": "Kurt", "author_id": 32794, "author_profile": "https://Stackoverflow.com/users/32794", "pm_score": 3, "selected": false, "text": "<p>Thank you David, that was what I needed. Here's the working solution.</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing std::cout;\nusing std::endl;\n\n#include &lt;map&gt;\n#include &lt;boost/any.hpp&gt;\n\nusing boost::any_cast;\ntypedef std::map&lt;std::string, boost::any&gt; t_map;\n\n\nint main(int argc, char **argv)\n{\n\n t_map map;\n char *pc = \"boo yeah!\";\n\n map[\"a\"] = 2.1;\n map[\"b\"] = pc;\n\n cout &lt;&lt; \"map contents\" &lt;&lt; endl;\n cout &lt;&lt; any_cast&lt;double&gt;(map[\"a\"]) &lt;&lt; endl;\n cout &lt;&lt; any_cast&lt;char*&gt;(map[\"b\"]) &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 43964752, "author": "FaceBro", "author_id": 1737132, "author_profile": "https://Stackoverflow.com/users/1737132", "pm_score": 0, "selected": false, "text": "<p>boost any surely works, but I think using Int to type Technology as the key type of fusion map is a better solution. No type erasure and possibly faster </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32794/" ]
I want to have a map that has a homogeneous key type but heterogeneous data types. I want to be able to do something like (pseudo-code): ``` boost::map<std::string, magic_goes_here> m; m.add<int>("a", 2); m.add<std::string>("b", "black sheep"); int i = m.get<int>("a"); int j = m.get<int>("b"); // error! ``` I could have a pointer to a base class as the data type but would rather not. I've never used boost before but have looked at the fusion library but can't figure out what I need to do. Thanks for your help.
``` #include <map> #include <string> #include <iostream> #include <boost/any.hpp> int main() { try { std::map<std::string, boost::any> m; m["a"] = 2; m["b"] = static_cast<char const *>("black sheep"); int i = boost::any_cast<int>(m["a"]); std::cout << "I(" << i << ")\n"; int j = boost::any_cast<int>(m["b"]); // throws exception std::cout << "J(" << j << ")\n"; } catch(...) { std::cout << "Exception\n"; } } ```
251,409
<p>In MS SQL 2005 or T-SQL, you can do something like:</p> <pre><code>SELECT T.NAME, T.DATE FROM (SELECT * FROM MyTable WHERE ....) AS T </code></pre> <p>I failed to try the similar SQL on Oracle 9i DB. In MS SQL, the nested SQL is treated as a temporary/dynamic view created on fly and destroyed afterward. How can I do the similar thing in Oracle? I really don't want to create a view to do it.</p>
[ { "answer_id": 251414, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>I believe it chokes on the \"as\".</p>\n\n<pre><code>SELECT T.NAME, T.DATE \n FROM (SELECT * FROM MyTable WHERE ....) T\n</code></pre>\n\n<p>should work.</p>\n" }, { "answer_id": 251419, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>The only thing you need to change is remove the keyword \"AS\". Oracle uses that only for column aliases (e.g. SELECT dummy AS some_name FROM dual), although even then you don't need it.</p>\n" }, { "answer_id": 251843, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>If you really need to create a temporary, physical result set then you would do that with a subquery factoring clause:</p>\n\n<pre><code>with t as\n(SELECT /*+ materliaze */ \n *\n FROM MyTable\n WHERE ....)\nSELECT T.NAME, T.DATE \nFROM T\n/\n</code></pre>\n\n<p>It's generally not worthwhile except for specific situations in which the optimizer's accurate estimation of an intermediate result set in a query is critical to an efficient execution plan, in which case dynamic sampling can be used to see the size of the result set, or where a calculated result set is used multiple times in the rest of the query.</p>\n\n<p>You ought to be able to just drop the AS, and Oracle will logically merge the in-line view into the master query if it is safe to do so.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
In MS SQL 2005 or T-SQL, you can do something like: ``` SELECT T.NAME, T.DATE FROM (SELECT * FROM MyTable WHERE ....) AS T ``` I failed to try the similar SQL on Oracle 9i DB. In MS SQL, the nested SQL is treated as a temporary/dynamic view created on fly and destroyed afterward. How can I do the similar thing in Oracle? I really don't want to create a view to do it.
I believe it chokes on the "as". ``` SELECT T.NAME, T.DATE FROM (SELECT * FROM MyTable WHERE ....) T ``` should work.
251,420
<p>Basically, I have an <code>iframe</code> embedded in a page and the <code>iframe</code> has some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> routines I need to invoke from the parent page.</p> <p>Now the opposite is quite simple as you only need to call <code>parent.functionName()</code>, but unfortunately, I need exactly the opposite of that.</p> <p>Please note that my problem is not changing the source <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URL</a> of the <code>iframe</code>, but invoking a function defined in the <code>iframe</code>.</p>
[ { "answer_id": 251437, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 3, "selected": false, "text": "<p>Quirksmode had a <a href=\"http://web.archive.org/web/20080225210716/http://www.quirksmode.org/js/iframe.html\" rel=\"noreferrer\">post on this</a>.</p>\n\n<p>Since the page is now broken, and only accessible via archive.org, I reproduced it here:</p>\n\n<p><strong>IFrames</strong></p>\n\n<p>On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.</p>\n\n<p>An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.</p>\n\n<p><strong>Frame or object?</strong></p>\n\n<p>The fundamental question is whether the iframe is seen as a frame or as an object.</p>\n\n<ul>\n<li>As explained on the <a href=\"http://web.archive.org/web/20080225210716/http://www.quirksmode.org/js/frameintro.html\" rel=\"noreferrer\">Introduction to frames</a> pages, if you use frames the browser creates a frame hierarchy for you (<code>top.frames[1].frames[2]</code> and such). Does the iframe fit into this frame hierarchy?</li>\n<li>Or does the browser see an iframe as just another object, an object that happens to have a src property? In that case we have to use a standard <a href=\"http://web.archive.org/web/20080225210716/http://www.quirksmode.org/js/dom.html\" rel=\"noreferrer\">DOM call</a> (like <code>document.getElementById('theiframe'))</code> to access it.\nIn general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.</li>\n</ul>\n\n<p><strong>NAME attribute</strong></p>\n\n<p>The most important rule is to give any iframe you create a <code>name</code> attribute, even if you also use an <code>id</code>.</p>\n\n<pre><code>&lt;iframe src=\"iframe_page1.html\"\n id=\"testiframe\"\n name=\"testiframe\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>Most browsers need the <code>name</code> attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the <code>id</code> to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But <code>name</code> is far more important than <code>id</code>.</p>\n\n<p><strong>Access</strong></p>\n\n<p>Either you access the iframe as an object and change its <code>src</code> or you access the iframe as a frame and change its <code>location.href</code>.</p>\n\n<p>document.getElementById('iframe_id').src = 'newpage.html';\nframes['iframe_name'].location.href = 'newpage.html';\nThe frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.</p>\n\n<p><strong>Accessing the iframe</strong></p>\n\n<p>So for a complete cross–browser experience you should give the iframe a name and use the</p>\n\n<pre><code>frames['testiframe'].location.href\n</code></pre>\n\n<p>syntax. As far as I know this always works.</p>\n\n<p><strong>Accessing the document</strong></p>\n\n<p>Accessing the document inside the iframe is quite simple, provided you use the <code>name</code> attribute. To count the number of links in the document in the iframe, do\n<a href=\"http://web.archive.org/web/20080225210716/http://www.quirksmode.org/js/iframe.html#\" rel=\"noreferrer\"><code>frames['testiframe'].document.links.length</code></a>.</p>\n\n<p><strong>Generated iframes</strong></p>\n\n<p>When you generate an iframe through the <a href=\"http://web.archive.org/web/20080225210716/http://www.quirksmode.org/dom/intro.html\" rel=\"noreferrer\">W3C DOM</a> the iframe is not immediately entered into the <code>frames</code> array, though, and the <code>frames['testiframe'].location.href</code> syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.</p>\n\n<p>The <code>document.getElementById('testiframe').src</code> syntax works fine in all circumstances.</p>\n\n<p>The <code>target</code> attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a <code>name</code> and an <code>id</code>.</p>\n\n<p>The lack of <code>target</code> support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.</p>\n\n<p><strong>Text size in iframes</strong></p>\n\n<p>A curious Explorer 6 only bug:</p>\n\n<p>When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.</p>\n" }, { "answer_id": 251453, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 10, "selected": true, "text": "<p>Assume your iFrame's id is \"targetFrame\" and the function you want to call is <code>targetFunction()</code>:</p>\n\n<pre><code>document.getElementById('targetFrame').contentWindow.targetFunction();\n</code></pre>\n\n<p>You can also access the frame using <code>window.frames</code> instead of <code>document.getElementById</code>.</p>\n\n<pre><code>// this option does not work in most of latest versions of chrome and Firefox\nwindow.frames[0].frameElement.contentWindow.targetFunction(); \n</code></pre>\n" }, { "answer_id": 251457, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 3, "selected": false, "text": "<p>The IFRAME should be in the <code>frames[]</code> collection. Use something like</p>\n\n<pre><code>frames['iframeid'].method();\n</code></pre>\n" }, { "answer_id": 251468, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": false, "text": "<p>In the IFRAME, make your function public to the window object:</p>\n\n<pre><code>window.myFunction = function(args) {\n doStuff();\n}\n</code></pre>\n\n<p>For access from the parent page, use this:</p>\n\n<pre><code>var iframe = document.getElementById(\"iframeId\");\niframe.contentWindow.myFunction(args);\n</code></pre>\n" }, { "answer_id": 251645, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 7, "selected": false, "text": "<p>There are some quirks to be aware of here.</p>\n\n<ol>\n<li><p><code>HTMLIFrameElement.contentWindow</code> is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the <code>window</code> object.</p></li>\n<li><p>You can also try <code>HTMLIFrameElement.contentDocument.defaultView</code>, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the <code>window</code> object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.</p></li>\n<li><p><code>window.frames['name']</code> returning the window is the oldest and hence most reliable interface. But you then have to use a <code>name=\"...\"</code> attribute to be able to get a frame by name, which is slightly ugly/<strike>deprecated</strike>/transitional. (<code>id=\"...\"</code> would be better but IE doesn't like that.)</p></li>\n<li><p><code>window.frames[number]</code> is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.</p></li>\n<li><p>It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its <code>window.parent</code> script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.</p></li>\n</ol>\n" }, { "answer_id": 310014, "author": "GeverGever", "author_id": 31460, "author_profile": "https://Stackoverflow.com/users/31460", "pm_score": 2, "selected": false, "text": "<pre><code> $(\"#myframe\").load(function() {\n alert(\"loaded\");\n });\n</code></pre>\n" }, { "answer_id": 1063483, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": false, "text": "<p>Just for the record, I've ran into the same issue today but this time the page was embedded in an object, not an iframe (since it was an XHTML 1.1 document). Here's how it works with objects:</p>\n\n<pre><code>document\n .getElementById('targetFrame')\n .contentDocument\n .defaultView\n .targetFunction();\n</code></pre>\n\n<p>(sorry for the ugly line breaks, didn't fit in a single line)</p>\n" }, { "answer_id": 2663118, "author": "Vivek Singh CHAUHAN", "author_id": 222168, "author_profile": "https://Stackoverflow.com/users/222168", "pm_score": 6, "selected": false, "text": "<p>Calling a parent JS function from <code>iframe</code> is possible, but only when both the parent and the page loaded in the <code>iframe</code> are from same domain i.e. <code>example.com</code>, and both are using same protocol i.e. both are either on <code>http://</code> or <code>https://</code>.</p>\n<p>The call will fail in below mentioned cases:</p>\n<ol>\n<li>Parent page and the iframe page are from different domain.<br/></li>\n<li>They are using different protocols, one is on http:// and other is on https://.<br/></li>\n</ol>\n<p>Any workaround to this restriction would be extremely insecure.</p>\n<p>For instance, imagine I registered the domain <code>superwinningcontest.example</code> and sent out links to people's emails. When they loaded up the main page, I could hide a few <code>iframe</code>s in there and read their Facebook feed, check recent Amazon or PayPal transactions, or--if they used a service that did not implement sufficient security--transfer money out of their accounts. That's why JavaScript is limited to same-domain and same-protocol.</p>\n" }, { "answer_id": 7239578, "author": "sangam", "author_id": 47043, "author_profile": "https://Stackoverflow.com/users/47043", "pm_score": 2, "selected": false, "text": "<p>Same things but a bit easier way will be <a href=\"http://dotnetspidor.blogspot.com/2011/07/refresh-parent-page-partially-from.html\" rel=\"nofollow\">How to refresh parent page from page within iframe</a>.\nJust call the parent page's function to invoke javascript function to reload the page:</p>\n\n<pre><code>window.location.reload();\n</code></pre>\n\n<p>Or do this directly from the page in iframe:</p>\n\n<pre><code>window.parent.location.reload();\n</code></pre>\n\n<p>Both works.</p>\n" }, { "answer_id": 7757848, "author": "Nitin Bansal", "author_id": 967062, "author_profile": "https://Stackoverflow.com/users/967062", "pm_score": 2, "selected": false, "text": "<p>Continuing with <a href=\"https://stackoverflow.com/users/7441/joel-anair\">JoelAnair's</a> answer:</p>\n\n<p>For more robustness, use as follows:</p>\n\n<pre><code>var el = document.getElementById('targetFrame');\n\nif(el.contentWindow)\n{\n el.contentWindow.targetFunction();\n}\nelse if(el.contentDocument)\n{\n el.contentDocument.targetFunction();\n}\n</code></pre>\n\n<p>Workd like charm :)</p>\n" }, { "answer_id": 7938270, "author": "19greg96", "author_id": 1018376, "author_profile": "https://Stackoverflow.com/users/1018376", "pm_score": 5, "selected": false, "text": "<p>If the iFrame's target and the containing document are on a different domain, the methods previously posted might not work, but there is a solution:</p>\n\n<p>For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:</p>\n\n<pre><code>var o = document.getElementsByTagName('iframe')[0];\no.contentWindow.postMessage('Hello world', 'http://b.example.org/');\n</code></pre>\n\n<p>To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:</p>\n\n<pre><code>window.addEventListener('message', receiver, false);\nfunction receiver(e) {\n if (e.origin == 'http://example.com') {\n if (e.data == 'Hello world') {\n e.source.postMessage('Hello', e.origin);\n } else {\n alert(e.data);\n }\n }\n}\n</code></pre>\n\n<p>This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.</p>\n\n<p>via <a href=\"http://dev.w3.org/html5/postmsg/#web-messaging\" rel=\"noreferrer\">http://dev.w3.org/html5/postmsg/#web-messaging</a></p>\n" }, { "answer_id": 8381436, "author": "Santhanakumar", "author_id": 826232, "author_profile": "https://Stackoverflow.com/users/826232", "pm_score": 2, "selected": false, "text": "<p>If you want to invoke the JavaScript function on the Parent from the iframe generated by another function ex shadowbox or lightbox. </p>\n\n<p>You should try to make use of <code>window</code> object and invoke parent function:</p>\n\n<pre><code>window.parent.targetFunction();\n</code></pre>\n" }, { "answer_id": 8503787, "author": "Saeid", "author_id": 884152, "author_profile": "https://Stackoverflow.com/users/884152", "pm_score": 1, "selected": false, "text": "<p>Try just <code>parent.myfunction()</code></p>\n" }, { "answer_id": 11795928, "author": "Dominique Fortin", "author_id": 1571709, "author_profile": "https://Stackoverflow.com/users/1571709", "pm_score": 2, "selected": false, "text": "<p>Folowing Nitin Bansal's answer</p>\n\n<p>and for even more robustness:</p>\n\n<pre><code>function getIframeWindow(iframe_object) {\n var doc;\n\n if (iframe_object.contentWindow) {\n return iframe_object.contentWindow;\n }\n\n if (iframe_object.window) {\n return iframe_object.window;\n } \n\n if (!doc &amp;&amp; iframe_object.contentDocument) {\n doc = iframe_object.contentDocument;\n } \n\n if (!doc &amp;&amp; iframe_object.document) {\n doc = iframe_object.document;\n }\n\n if (doc &amp;&amp; doc.defaultView) {\n return doc.defaultView;\n }\n\n if (doc &amp;&amp; doc.parentWindow) {\n return doc.parentWindow;\n }\n\n return undefined;\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>...\nvar el = document.getElementById('targetFrame');\n\nvar frame_win = getIframeWindow(el);\n\nif (frame_win) {\n frame_win.targetFunction();\n ...\n}\n...\n</code></pre>\n" }, { "answer_id": 21649520, "author": "Julien L", "author_id": 690236, "author_profile": "https://Stackoverflow.com/users/690236", "pm_score": 3, "selected": false, "text": "<p>I found quite an elegant solution.</p>\n\n<p>As you said, it's fairly easy to execute code located on the parent document. And that's the base of my code, do to just the opposite.</p>\n\n<p>When my iframe loads, I call a function located on the parent document, passing as an argument a reference to a local function, located in the iframe's document.\nThe parent document now has a direct access to the iframe's function thru this reference.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>On the parent:</p>\n\n<pre><code>function tunnel(fn) {\n fn();\n}\n</code></pre>\n\n<p>On the iframe:</p>\n\n<pre><code>var myFunction = function() {\n alert(\"This work!\");\n}\n\nparent.tunnel(myFunction);\n</code></pre>\n\n<p>When the iframe loads, it will call parent.tunnel(YourFunctionReference), which will execute the function received in parameter.</p>\n\n<p>That simple, without having to deal with the all the non-standards methods from the various browsers.</p>\n" }, { "answer_id": 25138489, "author": "Sandy", "author_id": 846169, "author_profile": "https://Stackoverflow.com/users/846169", "pm_score": -1, "selected": false, "text": "<p>Use following to call function of a frame in parent page</p>\n\n<pre><code>parent.document.getElementById('frameid').contentWindow.somefunction()\n</code></pre>\n" }, { "answer_id": 46622668, "author": "Cybernetic", "author_id": 1639594, "author_profile": "https://Stackoverflow.com/users/1639594", "pm_score": 4, "selected": false, "text": "<p>Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible. </p>\n\n<p>Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it. </p>\n\n<p>parent_frame.html</p>\n\n<pre><code>&lt;button id='parent_page_button' onclick='call_button_inside_frame()'&gt;&lt;/button&gt;\n\nfunction call_button_inside_frame() {\n document.getElementById('my_iframe').contentWindow.postMessage('foo','*');\n}\n</code></pre>\n\n<p>iframe_page.html</p>\n\n<pre><code>window.addEventListener(\"message\", receiveMessage, false);\n\nfunction receiveMessage(event)\n {\n if(event) {\n click_button_inside_frame();\n }\n}\n\nfunction click_button_inside_frame() {\n document.getElementById('frame_button').click();\n}\n</code></pre>\n\n<p>To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:</p>\n\n<pre><code>document.getElementById('my_iframe').contentWindow.postMessage('foo','*');\n</code></pre>\n\n<p>to this: </p>\n\n<pre><code>window.parent.postMessage('foo','*')\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
Basically, I have an `iframe` embedded in a page and the `iframe` has some [JavaScript](http://en.wikipedia.org/wiki/JavaScript) routines I need to invoke from the parent page. Now the opposite is quite simple as you only need to call `parent.functionName()`, but unfortunately, I need exactly the opposite of that. Please note that my problem is not changing the source [URL](http://en.wikipedia.org/wiki/Uniform_Resource_Locator) of the `iframe`, but invoking a function defined in the `iframe`.
Assume your iFrame's id is "targetFrame" and the function you want to call is `targetFunction()`: ``` document.getElementById('targetFrame').contentWindow.targetFunction(); ``` You can also access the frame using `window.frames` instead of `document.getElementById`. ``` // this option does not work in most of latest versions of chrome and Firefox window.frames[0].frameElement.contentWindow.targetFunction(); ```
251,432
<p>Is it possible to <code>typedef</code> long types that use templates? For example:</p> <pre><code>template &lt;typename myfloat_t&gt; class LongClassName { // ... }; template &lt;typename myfloat_t&gt; typedef std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;myfloat_t&gt; &gt; &gt; LongCollection; LongCollection&lt;float&gt; m_foo; </code></pre> <p>This doesn't work, but is there a way to achieve a similar effect? I just want to avoid having to type and read a type definition that covers almost the full width of my editor window. </p>
[ { "answer_id": 251446, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": true, "text": "<p>No, that isn't possible currently. It will be made possible in C++0X AFAIK.</p>\n\n<p>The best I can think of is </p>\n\n<pre><code>template&lt;typename T&gt; struct LongCollection {\n typedef std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;T&gt; &gt; &gt; type;\n};\n\nLongCollection&lt;float&gt;::type m_foo;\n</code></pre>\n" }, { "answer_id": 251455, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": "<p>If you don't want to go the macro way you have to make individual typedefs for each type:</p>\n\n<pre><code>typedef std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;float&gt; &gt; &gt; FloatCollection;\ntypedef std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;double&gt; &gt; &gt; DoubleCollection;\n</code></pre>\n" }, { "answer_id": 251456, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>No, but you can get close using a 'helper' type, see this <a href=\"http://www.gotw.ca/gotw/079.htm\" rel=\"nofollow noreferrer\">example</a>.</p>\n" }, { "answer_id": 251474, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "<p>Its not exactly what you're asking for, but this might achieve the desired effect depending on your actual situation:</p>\n\n<pre><code>template &lt;typename myfloat_t&gt;\nclass LongClassName\n{\n // ...\n};\n\ntemplate &lt;typename myfloat_t&gt;\nclass LongCollection : public std::vector&lt; boost::shared_ptr&lt; LongClassName&lt;myfloat_t&gt; &gt; &gt; \n{\n};\n</code></pre>\n\n<p>You may need to add some constructors or operators depending on your needs.</p>\n" }, { "answer_id": 251484, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>The solution shown by Leon is canonical. Bit of background knowledge: This is called a “(template) metafunction” because it is basically a “function” that gets evaluated at compile time. Instead of values, it deals with types: There's a list of input types (the type arguments) and there's a “return value”: The typedef that declares the type name “type”.</p>\n\n<p>“Invocation” works analogously to normal function invocation, albeit with a different syntax:</p>\n\n<pre><code>// Normal function\nresult = f(args);\n\n// Metafunction\ntypedef f&lt;args&gt;::type result;\n</code></pre>\n\n<p>This code construct is an often-used idiom in libraries such as the Boost libraries and even in the STL at one place: <code>allocator_type::rebind&lt;U&gt;::other</code> accomplishes the same thing with the only difference that the typedef <code>type</code> is called <code>other</code>.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32515/" ]
Is it possible to `typedef` long types that use templates? For example: ``` template <typename myfloat_t> class LongClassName { // ... }; template <typename myfloat_t> typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection; LongCollection<float> m_foo; ``` This doesn't work, but is there a way to achieve a similar effect? I just want to avoid having to type and read a type definition that covers almost the full width of my editor window.
No, that isn't possible currently. It will be made possible in C++0X AFAIK. The best I can think of is ``` template<typename T> struct LongCollection { typedef std::vector< boost::shared_ptr< LongClassName<T> > > type; }; LongCollection<float>::type m_foo; ```
251,433
<p>Looking up LINQ and Or in google is proving somewhat difficult so here I am.</p> <p>I want to so the following:</p> <pre><code>(from creditCard in AvailableCreditCards where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant()) **or creditCard.CardNumber.().Contains(txtFilter.Text)** orderby creditCard.BillToName select creditCard) </code></pre>
[ { "answer_id": 251449, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "<p>You can use the .Where() function to accomplish this.</p>\n\n<pre><code>var cards = AvailableCreditCards.Where(card=&gt; card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());\n</code></pre>\n" }, { "answer_id": 251450, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<p>C# keywords supporting LINQ are still C#. Consider <code>where</code> as a conditional like <code>if</code>; you perform logical operations in the same way. In this case, a logical-OR, you use <code>||</code></p>\n\n<pre><code>(from creditCard in AvailableCreditCards \n where creditCard.BillToName.ToLowerInvariant().Contains(\n txtFilter.Text.ToLowerInvariant()) \n || creditCard.CardNumber.().Contains(txtFilter.Text) \norderby creditCard.BillToName \nselect creditCard)\n</code></pre>\n" }, { "answer_id": 251451, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>You should use the boolean operator that works in your language. Pipe | works in C#</p>\n\n<p>Here's <a href=\"http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.80).aspx\" rel=\"nofollow noreferrer\">msdn</a> on the single |\nHere's <a href=\"http://msdn.microsoft.com/en-us/library/6373h346(VS.80).aspx\" rel=\"nofollow noreferrer\">msdn</a> on the double pipe ||</p>\n\n<p>The deal with the double pipe is that it short-circuits (does not run the right expression if the left expression is true). Many people just use double pipe only because they never learned single pipe.</p>\n\n<p>Double pipe's short circuiting behavior creates <em>branching code</em>, which could be very bad if a side effect was expected from running the expression on the right.</p>\n\n<p>The reason I prefer single pipes in linq queries is that - if the query is someday used in linq to sql, the underlying translation of both of c#'s OR operators is to sql's OR, which operates like the single pipe.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32772/" ]
Looking up LINQ and Or in google is proving somewhat difficult so here I am. I want to so the following: ``` (from creditCard in AvailableCreditCards where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant()) **or creditCard.CardNumber.().Contains(txtFilter.Text)** orderby creditCard.BillToName select creditCard) ```
C# keywords supporting LINQ are still C#. Consider `where` as a conditional like `if`; you perform logical operations in the same way. In this case, a logical-OR, you use `||` ``` (from creditCard in AvailableCreditCards where creditCard.BillToName.ToLowerInvariant().Contains( txtFilter.Text.ToLowerInvariant()) || creditCard.CardNumber.().Contains(txtFilter.Text) orderby creditCard.BillToName select creditCard) ```
251,439
<p>I want to pass an int list (List) as a declarative property to a web user control like this:</p> <pre><code>&lt;UC:MyControl runat="server" ModuleIds="1,2,3" /&gt; </code></pre> <p>I created a TypeConverter to do this:</p> <pre><code>public class IntListConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom( System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { string[] v = ((string)value).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List&lt;int&gt; list = new List&lt;int&gt;(); foreach (string s in vals) { list.Add(Convert.ToInt32(s)); } return list } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor) &amp;&amp; value is List&lt;int&gt;) { List&lt;int&gt; list = (List&lt;int&gt;)value; ConstructorInfo construcor = typeof(List&lt;int&gt;).GetConstructor(new Type[] { typeof(IEnumerable&lt;int&gt;) }); InstanceDescriptor id = new InstanceDescriptor(construcor, new object[] { list.ToArray() }); return id; } return base.ConvertTo(context, culture, value, destinationType); } } </code></pre> <p>And then added the attribute to my property:</p> <pre><code>[TypeConverter(typeof(IntListConverter))] public List&lt;int&gt; ModuleIds { get { ... }; set { ... }; } </code></pre> <p>But I get this error at runtime:</p> <p><code>Unable to generate code for a value of type 'System.Collections.Generic.List'1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. This error occurred while trying to generate the property value for ModuleIds.</code></p> <p>My question is similar to one found <a href="https://stackoverflow.com/questions/116797/passing-int-array-as-parameter-in-web-user-control">here</a>, but the solution does not solve my problem:</p> <p><strong>Update:</strong> I found a page which solved the first problem. I updated the code above to show my fixes. The added code is the <code>CanConvertTo</code> and <code>ConvertTo</code> methods. Now I get a different error.:</p> <p><code>Object reference not set to an instance of an object.</code></p> <p>This error seems to be indirectly caused by something in the <code>ConvertTo</code> method.</p>
[ { "answer_id": 251600, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<p>pass the list from the code behind...</p>\n\n<p>aspx:</p>\n\n<pre><code>&lt;UC:MyControl id=\"uc\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>code-behind:</p>\n\n<pre><code>List&lt;int&gt; list = new List&lt;int&gt;();\nlist.add(1);\nlist.add(2);\nlist.add(3);\n\nuc.ModuleIds = list;\n</code></pre>\n" }, { "answer_id": 251611, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 0, "selected": false, "text": "<p>The way I normally do this is to make the property wrap the ViewState collection. Your way looks better if it can be made to work, but this will get the job done:</p>\n\n<pre><code>public IList&lt;int&gt; ModuleIds\n{\n get\n {\n string moduleIds = Convert.ToString(ViewState[\"ModuleIds\"])\n\n IList&lt;int&gt; list = new Collection&lt;int&gt;();\n\n foreach(string moduleId in moduleIds.split(\",\"))\n {\n list.Add(Convert.ToInt32(moduleId));\n }\n\n return list;\n }\n}\n</code></pre>\n" }, { "answer_id": 251706, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>I believe the problem is the set{}. The type converter want to change the <code>List&lt;int&gt;</code> back into a string, but <code>CanConvertFrom()</code> fails for <code>List&lt;int&gt;</code>.</p>\n" }, { "answer_id": 251728, "author": "jkind", "author_id": 32893, "author_profile": "https://Stackoverflow.com/users/32893", "pm_score": 0, "selected": false, "text": "<p>You can pass it into a string and split on comma to populate a private variable. Does not have the nicety of attribution, but will work.</p>\n\n<pre><code>private List&lt;int&gt; modules;\npublic string ModuleIds\n{\n set{\n if (!string.IsNullOrEmpty(value))\n {\n if (modules == null) modules = new List&lt;int&gt;();\n var ids = value.Split(new []{','});\n if (ids.Length&gt;0)\n foreach (var id in ids)\n modules.Add((int.Parse(id)));\n }\n}\n</code></pre>\n" }, { "answer_id": 251751, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 1, "selected": false, "text": "<p>WHile I can't say I have any particular experience with this error, other sources indicate that you need to add a conversion to the type InstanceDescriptor. check out:</p>\n\n<p><a href=\"http://weblogs.asp.net/bleroy/archive/2005/04/28/405013.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/bleroy/archive/2005/04/28/405013.aspx</a></p>\n\n<p>Which provides an explanation of the reasons or alternatively:</p>\n\n<p><a href=\"http://forums.asp.net/p/1191839/2052438.aspx#2052438\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1191839/2052438.aspx#2052438</a></p>\n\n<p>Which provides example code similar to yours.</p>\n" }, { "answer_id": 251993, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>I think that you're best option is to make your usercontrol have a DataSource-style property.</p>\n\n<p>You take the property as an object and then do some type checking against IList/ IEnumerable/ etc to make sure that it is correct.</p>\n" }, { "answer_id": 251994, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "<p>After hooking a debugger into Cassini, I see that the null ref is actually coming from System.Web.Compilation.CodeDomUtility.GenerateExpressionForValue, which is basically trying to get an expression for the int[] array you pass into the List constructor. Since there's no type descriptor for the int[] array, it fails (and throws a null ref in the process, instead of the \"can't generate property set exception\" that it should).</p>\n\n<p>I can't figure out a built in way of getting a serializable value into a List&lt;int&gt;, so I just used a static method:</p>\n\n<pre><code>class IntListConverter : TypeConverter {\n public static List&lt;int&gt; FromString(string value) {\n return new List&lt;int&gt;(\n value\n .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(s =&gt; Convert.ToInt32(s))\n );\n }\n\n public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {\n if (destinationType == typeof(InstanceDescriptor)) {\n List&lt;int&gt; list = (List&lt;int&gt;)value;\n return new InstanceDescriptor(this.GetType().GetMethod(\"FromString\"),\n new object[] { string.Join(\",\", list.Select(i =&gt; i.ToString()).ToArray()) }\n );\n }\n return base.ConvertTo(context, culture, value, destinationType);\n }\n}\n</code></pre>\n" }, { "answer_id": 252855, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "<p>I solved something simular by creating 2 properties:</p>\n\n<pre><code>public List&lt;int&gt; ModuleIDs { get .... set ... }\npublic string ModuleIDstring { get ... set ... }\n</code></pre>\n\n<p>The ModuleIDstring converts its value set to a list and sets the ModuleIDs property.</p>\n\n<p>This will also make the ModuleIDs usable from a PropertyGrid etc. </p>\n\n<p>Ok, not the best, typesafe solution, but for me it works.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
I want to pass an int list (List) as a declarative property to a web user control like this: ``` <UC:MyControl runat="server" ModuleIds="1,2,3" /> ``` I created a TypeConverter to do this: ``` public class IntListConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom( System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom( System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { string[] v = ((string)value).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List<int> list = new List<int>(); foreach (string s in vals) { list.Add(Convert.ToInt32(s)); } return list } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor) && value is List<int>) { List<int> list = (List<int>)value; ConstructorInfo construcor = typeof(List<int>).GetConstructor(new Type[] { typeof(IEnumerable<int>) }); InstanceDescriptor id = new InstanceDescriptor(construcor, new object[] { list.ToArray() }); return id; } return base.ConvertTo(context, culture, value, destinationType); } } ``` And then added the attribute to my property: ``` [TypeConverter(typeof(IntListConverter))] public List<int> ModuleIds { get { ... }; set { ... }; } ``` But I get this error at runtime: `Unable to generate code for a value of type 'System.Collections.Generic.List'1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. This error occurred while trying to generate the property value for ModuleIds.` My question is similar to one found [here](https://stackoverflow.com/questions/116797/passing-int-array-as-parameter-in-web-user-control), but the solution does not solve my problem: **Update:** I found a page which solved the first problem. I updated the code above to show my fixes. The added code is the `CanConvertTo` and `ConvertTo` methods. Now I get a different error.: `Object reference not set to an instance of an object.` This error seems to be indirectly caused by something in the `ConvertTo` method.
After hooking a debugger into Cassini, I see that the null ref is actually coming from System.Web.Compilation.CodeDomUtility.GenerateExpressionForValue, which is basically trying to get an expression for the int[] array you pass into the List constructor. Since there's no type descriptor for the int[] array, it fails (and throws a null ref in the process, instead of the "can't generate property set exception" that it should). I can't figure out a built in way of getting a serializable value into a List<int>, so I just used a static method: ``` class IntListConverter : TypeConverter { public static List<int> FromString(string value) { return new List<int>( value .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => Convert.ToInt32(s)) ); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { List<int> list = (List<int>)value; return new InstanceDescriptor(this.GetType().GetMethod("FromString"), new object[] { string.Join(",", list.Select(i => i.ToString()).ToArray()) } ); } return base.ConvertTo(context, culture, value, destinationType); } } ```
251,444
<p>I have a command line Ruby app I'm developing and I want to allow a user of it to provide code that will run as a filter on part of the process. Basically, the application does this:</p> <ol> <li>read in some data</li> <li>If a filter is specified, use it to filter data</li> <li>process the data</li> </ol> <p>I want the filtering process (step 2) to be as flexible as possible.</p> <p>My thinking was that the user could provide a Ruby file that set a known constant to point to an object implementing an interface I define, e.g.:</p> <pre><code># user's filter class MyFilter def do_filter(array_to_filter) filtered_array = Array.new # do my filtering on array_to_filter filtered_array end FILTER = MyFilter.new </code></pre> <p>My app's code would then do something like this:</p> <pre><code>array_that_might_get_filtered = get_my_array() if (options.filter_file) require options.filter_file array_that_might_get_filtered = FILTER.do_filter(array_that_might_get_filtered) end </code></pre> <p>While this would work, it feels cheesy and it seems like there should be a better way to do it. I also considered having the filter be in the form of adding a method of a known name to a known class, but that didn't seem quite right, either.</p> <p>Is there a better idiom in Ruby for this?</p>
[ { "answer_id": 251511, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Looks like a job for a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern</a>, and since ruby has <a href=\"http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html\" rel=\"nofollow noreferrer\">functions as first-class objects</a>, you might pass the filter function to be memorized by the array, in order to invoke that custom filter function on demand.</p>\n" }, { "answer_id": 251608, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "<p>I'd just use a combination of the command line, and convention.</p>\n\n<blockquote>\n <p>If a filter is specified, use it to filter data</p>\n</blockquote>\n\n<p>I'm assuming you'd specify a filter on the command line? So you'd invoke the application like this?</p>\n\n<pre><code>ruby dataprocessor.rb custom_filter\n</code></pre>\n\n<p>If so, you could define an \"api\" wherein a class name would have to match what was passed in - pretty much exactly how you've described in your example.</p>\n\n<p>To take it one step further though, you could have some logic which looked for the <code>CustomFilter</code> class using ruby's <code>defined?</code>, and if it was not found, go looking for <code>custom_filter.rb</code> (or any suitable variations) and attempt to load that file, then retry.</p>\n\n<p>This gives you great extensibility, as you can write as many filter classes as you like, chuck them in their own .rb files, and put them anywhere that ruby can find them. You won't have to have an pre-defined constants either, the only constraints will be</p>\n\n<ol>\n<li>The class name must match (a variant of) the file name - This is convention in ruby so you're probably already doing it anyway.</li>\n<li>it must have some predefined method, such as your <code>do_filter</code> method</li>\n</ol>\n\n<p>Incidentally, this is pretty similar to what rails does for requiring your models, and is why you can just use <code>SomeModel</code> without having to always do <code>require app/models/some_model</code> first :-)`</p>\n" }, { "answer_id": 251650, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 0, "selected": false, "text": "<pre><code># user code\nUSER_FILTER = lambda { |value| value != 0xDEADBEEF }\n\n# script code\nload( user_code );\nFILTER = ( const_defined?(:USER_FILTER) ? USER_FILTER : lambda { true } )\n\noutput_array = input_array.filter(&amp;FILTER)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029/" ]
I have a command line Ruby app I'm developing and I want to allow a user of it to provide code that will run as a filter on part of the process. Basically, the application does this: 1. read in some data 2. If a filter is specified, use it to filter data 3. process the data I want the filtering process (step 2) to be as flexible as possible. My thinking was that the user could provide a Ruby file that set a known constant to point to an object implementing an interface I define, e.g.: ``` # user's filter class MyFilter def do_filter(array_to_filter) filtered_array = Array.new # do my filtering on array_to_filter filtered_array end FILTER = MyFilter.new ``` My app's code would then do something like this: ``` array_that_might_get_filtered = get_my_array() if (options.filter_file) require options.filter_file array_that_might_get_filtered = FILTER.do_filter(array_that_might_get_filtered) end ``` While this would work, it feels cheesy and it seems like there should be a better way to do it. I also considered having the filter be in the form of adding a method of a known name to a known class, but that didn't seem quite right, either. Is there a better idiom in Ruby for this?
I'd just use a combination of the command line, and convention. > > If a filter is specified, use it to filter data > > > I'm assuming you'd specify a filter on the command line? So you'd invoke the application like this? ``` ruby dataprocessor.rb custom_filter ``` If so, you could define an "api" wherein a class name would have to match what was passed in - pretty much exactly how you've described in your example. To take it one step further though, you could have some logic which looked for the `CustomFilter` class using ruby's `defined?`, and if it was not found, go looking for `custom_filter.rb` (or any suitable variations) and attempt to load that file, then retry. This gives you great extensibility, as you can write as many filter classes as you like, chuck them in their own .rb files, and put them anywhere that ruby can find them. You won't have to have an pre-defined constants either, the only constraints will be 1. The class name must match (a variant of) the file name - This is convention in ruby so you're probably already doing it anyway. 2. it must have some predefined method, such as your `do_filter` method Incidentally, this is pretty similar to what rails does for requiring your models, and is why you can just use `SomeModel` without having to always do `require app/models/some_model` first :-)`
251,464
<p>How do I get a function's name as a string?</p> <pre><code>def foo(): pass &gt;&gt;&gt; name_of(foo) &quot;foo&quot; </code></pre>
[ { "answer_id": 251469, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": false, "text": "<pre><code>my_function.func_name\n</code></pre>\n\n<p>There are also other fun properties of functions. Type <code>dir(func_name)</code> to list them. <code>func_name.func_code.co_code</code> is the compiled function, stored as a string.</p>\n\n<pre><code>import dis\ndis.dis(my_function)\n</code></pre>\n\n<p>will display the code in <em>almost</em> human readable format. :)</p>\n" }, { "answer_id": 255297, "author": "user28409", "author_id": 28409, "author_profile": "https://Stackoverflow.com/users/28409", "pm_score": 11, "selected": true, "text": "<pre><code>my_function.__name__\n</code></pre>\n\n<p>Using <code>__name__</code> is the preferred method as it applies uniformly. Unlike <code>func_name</code>, it works on built-in functions as well:</p>\n\n<pre><code>&gt;&gt;&gt; import time\n&gt;&gt;&gt; time.time.func_name\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in ?\nAttributeError: 'builtin_function_or_method' object has no attribute 'func_name'\n&gt;&gt;&gt; time.time.__name__ \n'time'\n</code></pre>\n\n<p>Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a <code>__name__</code> attribute too, so you only have remember one special name.</p>\n" }, { "answer_id": 13514318, "author": "Albert Vonpupp", "author_id": 1332764, "author_profile": "https://Stackoverflow.com/users/1332764", "pm_score": 9, "selected": false, "text": "<p>To get the current function's or method's name from inside it, consider:</p>\n\n<pre><code>import inspect\n\nthis_function_name = inspect.currentframe().f_code.co_name\n</code></pre>\n\n<p><code>sys._getframe</code> also works instead of <code>inspect.currentframe</code> although the latter avoids accessing a private function.</p>\n\n<p>To get the calling function's name instead, consider <code>f_back</code> as in <code>inspect.currentframe().f_back.f_code.co_name</code>.</p>\n\n<hr>\n\n<p>If also using <code>mypy</code>, it can complain that:</p>\n\n<blockquote>\n <p>error: Item \"None\" of \"Optional[FrameType]\" has no attribute \"f_code\"</p>\n</blockquote>\n\n<p>To suppress the above error, consider:</p>\n\n<pre><code>import inspect\nimport types\nfrom typing import cast\n\nthis_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name\n</code></pre>\n" }, { "answer_id": 18543271, "author": "sandyc", "author_id": 2734604, "author_profile": "https://Stackoverflow.com/users/2734604", "pm_score": 4, "selected": false, "text": "<p><code>sys._getframe()</code> is not guaranteed to be available in all implementations of Python (<a href=\"http://docs.python.org/2/library/sys.html\" rel=\"noreferrer\">see ref</a>) ,you can use the <code>traceback</code> module to do the same thing, eg.</p>\n\n<pre><code>import traceback\ndef who_am_i():\n stack = traceback.extract_stack()\n filename, codeline, funcName, text = stack[-2]\n\n return funcName\n</code></pre>\n\n<p>A call to <code>stack[-1]</code> will return the current process details.</p>\n" }, { "answer_id": 20714270, "author": "Demyn", "author_id": 937597, "author_profile": "https://Stackoverflow.com/users/937597", "pm_score": 5, "selected": false, "text": "<p>This function will return the caller's function name.</p>\n\n<pre><code>def func_name():\n import traceback\n return traceback.extract_stack(None, 2)[0][2]\n</code></pre>\n\n<p>It is like Albert Vonpupp's answer with a friendly wrapper.</p>\n" }, { "answer_id": 36228241, "author": "Jim G.", "author_id": 109941, "author_profile": "https://Stackoverflow.com/users/109941", "pm_score": 4, "selected": false, "text": "<p>As an extension of <a href=\"https://stackoverflow.com/a/20714270/109941\">@Demyn's answer</a>, I created some utility functions which print the current function's name and current function's arguments:</p>\n\n<pre><code>import inspect\nimport logging\nimport traceback\n\ndef get_function_name():\n return traceback.extract_stack(None, 2)[0][2]\n\ndef get_function_parameters_and_values():\n frame = inspect.currentframe().f_back\n args, _, _, values = inspect.getargvalues(frame)\n return ([(i, values[i]) for i in args])\n\ndef my_func(a, b, c=None):\n logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')\n pass\n\nlogger = logging.getLogger()\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n '%(asctime)s [%(levelname)s] -&gt; %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\nmy_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -&gt; Running my_func([('a', 1), ('b', 3), ('c', None)])\n</code></pre>\n" }, { "answer_id": 38453402, "author": "radato", "author_id": 797396, "author_profile": "https://Stackoverflow.com/users/797396", "pm_score": 5, "selected": false, "text": "<p>I like using a function decorator.\nI added a class, which also times the function time. Assume gLog is a standard python logger:</p>\n\n<pre><code>class EnterExitLog():\n def __init__(self, funcName):\n self.funcName = funcName\n\n def __enter__(self):\n gLog.debug('Started: %s' % self.funcName)\n self.init_time = datetime.datetime.now()\n return self\n\n def __exit__(self, type, value, tb):\n gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))\n\ndef func_timer_decorator(func):\n def func_wrapper(*args, **kwargs):\n with EnterExitLog(func.__name__):\n return func(*args, **kwargs)\n\n return func_wrapper\n</code></pre>\n\n<p>so now all you have to do with your function is decorate it and voila</p>\n\n<pre><code>@func_timer_decorator\ndef my_func():\n</code></pre>\n" }, { "answer_id": 47155992, "author": "lapis", "author_id": 675674, "author_profile": "https://Stackoverflow.com/users/675674", "pm_score": 6, "selected": false, "text": "<p>If you're interested in class methods too, Python 3.3+ has <code>__qualname__</code> in addition to <code>__name__</code>.</p>\n\n<pre><code>def my_function():\n pass\n\nclass MyClass(object):\n def method(self):\n pass\n\nprint(my_function.__name__) # gives \"my_function\"\nprint(MyClass.method.__name__) # gives \"method\"\n\nprint(my_function.__qualname__) # gives \"my_function\"\nprint(MyClass.method.__qualname__) # gives \"MyClass.method\"\n</code></pre>\n" }, { "answer_id": 49322993, "author": "Mohsin Ashraf", "author_id": 5566361, "author_profile": "https://Stackoverflow.com/users/5566361", "pm_score": 4, "selected": false, "text": "<p>You just want to get the name of the function here is a simple code for that.\nlet say you have these functions defined</p>\n\n<pre><code>def function1():\n print \"function1\"\n\ndef function2():\n print \"function2\"\n\ndef function3():\n print \"function3\"\nprint function1.__name__\n</code></pre>\n\n<p>the output will be <strong>function1</strong></p>\n\n<p>Now let say you have these functions in a list</p>\n\n<pre><code>a = [function1 , function2 , funciton3]\n</code></pre>\n\n<p>to get the name of the functions</p>\n\n<pre><code>for i in a:\n print i.__name__\n</code></pre>\n\n<p>the output will be</p>\n\n<p><strong>function1</strong><br/>\n<strong>function2</strong><br />\n<strong>function3</strong><br/></p>\n" }, { "answer_id": 55253296, "author": "Ma Guowei", "author_id": 2330690, "author_profile": "https://Stackoverflow.com/users/2330690", "pm_score": 5, "selected": false, "text": "<pre><code>import inspect\n\ndef foo():\n print(inspect.stack()[0][3])\n</code></pre>\n<p>where</p>\n<ul>\n<li><p><code>stack()[0]</code> is the caller</p>\n</li>\n<li><p><code>stack()[3]</code> is the string name of the method</p>\n</li>\n</ul>\n" }, { "answer_id": 58548220, "author": "NL23codes", "author_id": 9431874, "author_profile": "https://Stackoverflow.com/users/9431874", "pm_score": 4, "selected": false, "text": "<p>I've seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here's something I use for logging function names as well as their respective input and output values. I've adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.</p>\n\n<pre><code>def debug(func=None):\n def wrapper(*args, **kwargs):\n try:\n function_name = func.__func__.__qualname__\n except:\n function_name = func.__qualname__\n return func(*args, **kwargs, function_name=function_name)\n return wrapper\n\n@debug\ndef my_function(**kwargs):\n print(kwargs)\n\nmy_function()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>{'function_name': 'my_function'}\n</code></pre>\n" }, { "answer_id": 63857383, "author": "Ahmed Shehab", "author_id": 8404743, "author_profile": "https://Stackoverflow.com/users/8404743", "pm_score": 3, "selected": false, "text": "<p>Try</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nfn_name = sys._getframe().f_code.co_name\n</code></pre>\n<p>further reference\n<a href=\"https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html\" rel=\"noreferrer\">https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html</a></p>\n" }, { "answer_id": 65110612, "author": "Szczerski", "author_id": 10646189, "author_profile": "https://Stackoverflow.com/users/10646189", "pm_score": 3, "selected": false, "text": "<pre><code>import inspect\n\ndef my_first_function():\n func_name = inspect.stack()[0][3]\n print(func_name) # my_first_function\n</code></pre>\n<p>or:</p>\n<pre><code>import sys\n\ndef my_second_function():\n func_name = sys._getframe().f_code.co_name\n print(func_name) # my_second_function\n</code></pre>\n" }, { "answer_id": 71002981, "author": "Gustin", "author_id": 10141500, "author_profile": "https://Stackoverflow.com/users/10141500", "pm_score": 2, "selected": false, "text": "<p>You can get a function's name as a string by using the special <code>__name__</code> variable.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def my_function():\n pass\n\nprint(my_function.__name__) # prints &quot;my_function&quot;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11452/" ]
How do I get a function's name as a string? ``` def foo(): pass >>> name_of(foo) "foo" ```
``` my_function.__name__ ``` Using `__name__` is the preferred method as it applies uniformly. Unlike `func_name`, it works on built-in functions as well: ``` >>> import time >>> time.time.func_name Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' >>> time.time.__name__ 'time' ``` Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a `__name__` attribute too, so you only have remember one special name.
251,466
<p>An easy jQuery question.</p> <p>I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and then the input name. ( the input names are not unique in my page )</p> <p>So for instance: </p> <pre><code>var xAmt = $('#xForm'+num).('#xAmt'); </code></pre> <p>I really want to supply these values to an AJAX POST</p> <pre><code> $.ajax({ url: "X.asp", cache: false, type: "POST", data: "XID=xID&amp;xNumber=xNum&amp;xAmt=xAmt", </code></pre> <p>...</p> <p>If I can get the values in the AJAX call even better.</p>
[ { "answer_id": 251520, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Looks like you want <code>formSerialize()</code> (or even <code>ajaxSubmit()</code>) from the <a href=\"http://docs.jquery.com/Plugins:Forms#formSerialize.28.29\" rel=\"nofollow noreferrer\">jQuery forms plugin</a>. </p>\n" }, { "answer_id": 251591, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 0, "selected": false, "text": "<p><strong>Edited:</strong></p>\n\n<p>You need to start with getting them all selected, then you can work with them.</p>\n\n<p>To access just the xForm# elements, you can do a selector like this (you should check the syntax, I haven't run this, it's just an example):</p>\n\n<pre><code>$('form input[name*='xAmt'] ').each(function(){ alert( $(this).val() ); alert( $(this).parent().attr('name') + $(this).parent().attr('id') ); });\n</code></pre>\n\n<p>The form input[name*='xAmt'] means select any elements inside a form that contain the term xAmt. You can also do starts with, ends with, etc. See the links below.</p>\n\n<p>When in the each loop, you can access each one as $(this). You can access it's parent form as $(this).parent(), so you can tell which form the input is in.</p>\n\n<p>You might build the data in the loop, or do something else with them, and then make the post.</p>\n\n<p>see:</p>\n\n<p><a href=\"http://docs.jquery.com/Selectors/attributeContains#attributevalue\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/attributeContains#attributevalue</a></p>\n\n<p><a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors</a></p>\n\n<p><a href=\"http://docs.jquery.com/Each\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Each</a></p>\n\n<p><a href=\"http://docs.jquery.com/Attributes/attr#name\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Attributes/attr#name</a></p>\n\n<p><a href=\"http://docs.jquery.com/Traversing/parent#expr\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Traversing/parent#expr</a></p>\n" }, { "answer_id": 251627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<pre><code>function queryX( args ) {\n var queryString = [ \"XID=\", args.XID, \"&amp;xNumber=\", args.xNumber, \"&amp;xAmt=\", args.xAmt ].join(\"\");\n $.ajax({\n url: \"X.asp\",\n cache: false,\n type: \"POST\",\n data: queryString,\n success : function( data ) {\n return data;\n }\n });\n}\nvar myReturnData = queryX({\n XID : $(\"input[name='XID']\").val(),\n xNumber : $(\"input[name='xNumber']\").val(),\n xAmt : $(\"input[name='xAmt']\").val()\n});\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>This allows you the most flexibility, and if only the input values will change (but the query string variables won't), then you can pass in whatever you want as the value.</p>\n" }, { "answer_id": 252471, "author": "ack", "author_id": 32840, "author_profile": "https://Stackoverflow.com/users/32840", "pm_score": 1, "selected": false, "text": "<p>The flexible way to do it has already been answered here, but you can also just make it work with your current code. (Forgive me if this was too basic for what you're looking for.)</p>\n\n<p>Drill down from the unique form name by using the CSS descendant selector (a space):</p>\n\n<pre><code>var xAmt = $('#xForm'+num+ ' #xAmt').val();\n</code></pre>\n\n<p>Repeat for each value you need and call $.ajax just like you're doing.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
An easy jQuery question. I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and then the input name. ( the input names are not unique in my page ) So for instance: ``` var xAmt = $('#xForm'+num).('#xAmt'); ``` I really want to supply these values to an AJAX POST ``` $.ajax({ url: "X.asp", cache: false, type: "POST", data: "XID=xID&xNumber=xNum&xAmt=xAmt", ``` ... If I can get the values in the AJAX call even better.
``` function queryX( args ) { var queryString = [ "XID=", args.XID, "&xNumber=", args.xNumber, "&xAmt=", args.xAmt ].join(""); $.ajax({ url: "X.asp", cache: false, type: "POST", data: queryString, success : function( data ) { return data; } }); } var myReturnData = queryX({ XID : $("input[name='XID']").val(), xNumber : $("input[name='xNumber']").val(), xAmt : $("input[name='xAmt']").val() }); ``` **EDIT:** This allows you the most flexibility, and if only the input values will change (but the query string variables won't), then you can pass in whatever you want as the value.
251,467
<p>I have a directory of bitmaps that are all of the same dimension. I would like to convert these bitmaps into a video file. I don't care if the video file (codec) is wmv or avi. My only requirement is that I specify the frame rate. This does not need to be cross platform, Windows (Vista and XP) only. I have read a few things about using the Windows Media SDK or DirectShow, but none of them are that explicit about providing code samples.</p> <p>Could anyone provide some insight, or some valuable resources that might help me to do this in C#?</p>
[ { "answer_id": 251685, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 2, "selected": false, "text": "<p>You can use the AVI* from avifil32 library, there is an example here (not tried):<br>\n<a href=\"http://www.adp-gmbh.ch/csharp/mandelbrot/index.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/csharp/mandelbrot/index.html</a></p>\n\n<p>This might be of interest for you:<br>\n<a href=\"http://bytescout.com/swfslideshowscout_example_c_sharp.html\" rel=\"nofollow noreferrer\">http://bytescout.com/swfslideshowscout_example_c_sharp.html</a><br>\n(make flash slideshow from JPG images using C#)</p>\n" }, { "answer_id": 251853, "author": "crftr", "author_id": 18213, "author_profile": "https://Stackoverflow.com/users/18213", "pm_score": 5, "selected": true, "text": "<p>At the risk of being voted down, I'll offer a possible alternative option-- a buffered Bitmap animation.</p>\n\n<pre><code>double framesPerSecond;\nBitmap[] imagesToDisplay; // add the desired bitmaps to this array\nTimer playbackTimer;\n\nint currentImageIndex;\nPictureBox displayArea;\n\n(...)\n\ncurrentImageIndex = 0;\nplaybackTimer.Interval = 1000 / framesPerSecond;\nplaybackTimer.AutoReset = true;\nplaybackTimer.Elapsed += new ElapsedEventHandler(playbackNextFrame);\nplaybackTimer.Start();\n\n(...)\n\nvoid playbackNextFrame(object sender, ElapsedEventArgs e)\n{\n if (currentImageIndex + 1 &gt;= imagesToDisplay.Length)\n {\n playbackTimer.Stop();\n\n return;\n }\n\n displayArea.Image = imagesToDisplay[currentImageIndex++];\n}\n</code></pre>\n\n<p>An approach such as this works well if the viewing user has access to the images, enough resources to keep the images in memory, doesn't want to wait for a video to encode, and there may exist a need for different playback speeds.</p>\n\n<p>...just throwing it out there.</p>\n" }, { "answer_id": 252914, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "<p>I have not tried it, but <a href=\"http://msdn.microsoft.com/en-us/library/bb469712(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows Movie Maker</a> has an API, and XML file format you can use.</p>\n" }, { "answer_id": 252950, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/93954/how-to-programatically-create-videos#94485\">FFMPEG can easily do this.</a></p>\n" }, { "answer_id": 253307, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 2, "selected": false, "text": "<p>An ideal technology to achieve what you want is <a href=\"http://msdn.microsoft.com/en-us/library/ms783329(VS.85).aspx\" rel=\"nofollow noreferrer\">DirectShow Editing Services</a>. However, if this is a one-off project then I wouldn't bother - the learning curve can be quite steep.</p>\n\n<p>There's not much in the way of DES sample code available, although there's plenty of general DirectShow samples both within and outside MSDN. For your purposes I'd recommend starting <a href=\"http://msdn.microsoft.com/en-us/library/ms787453(VS.85).aspx\" rel=\"nofollow noreferrer\">here</a> for a basic explanation of using still images as a video source.</p>\n" }, { "answer_id": 289913, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://www.codeplex.com/splicer\" rel=\"nofollow noreferrer\">Splicer</a> to do this.</p>\n\n<p>Please see example 3 at <a href=\"http://www.codeplex.com/splicer/Wiki/View.aspx?title=News%20Feeds&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">http://www.codeplex.com/splicer/Wiki/View.aspx?title=News%20Feeds&amp;referringTitle=Home</a></p>\n\n<p>Edit:</p>\n\n<pre><code>using (ITimeline timeline = new DefaultTimeline(25))\n{\n IGroup group = timeline.AddVideoGroup(32, 160, 100);\n\n ITrack videoTrack = group.AddTrack();\n IClip clip1 = videoTrack.AddImage(\"image1.jpg\", 0, 2);\n IClip clip2 = videoTrack.AddImage(\"image2.jpg\", 0, 2);\n IClip clip3 = videoTrack.AddImage(\"image3.jpg\", 0, 2);\n IClip clip4 = videoTrack.AddImage(\"image4.jpg\", 0, 2);\n\n double halfDuration = 0.5;\n\n group.AddTransition(clip2.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip2.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n group.AddTransition(clip3.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip3.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n group.AddTransition(clip4.Offset - halfDuration, halfDuration, StandardTransitions.CreateFade(), true);\n group.AddTransition(clip4.Offset, halfDuration, StandardTransitions.CreateFade(), false);\n\n ITrack audioTrack = timeline.AddAudioGroup().AddTrack();\n\n IClip audio =\n audioTrack.AddAudio(\"soundtrack.wav\", 0, videoTrack.Duration);\n\n audioTrack.AddEffect(0, audio.Duration,\n StandardEffects.CreateAudioEnvelope(1.0, 1.0, 1.0, audio.Duration));\n\n using (\n WindowsMediaRenderer renderer =\n new WindowsMediaRenderer(timeline, \"output.wmv\", WindowsMediaProfiles.HighQualityVideo))\n {\n renderer.Render();\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I have a directory of bitmaps that are all of the same dimension. I would like to convert these bitmaps into a video file. I don't care if the video file (codec) is wmv or avi. My only requirement is that I specify the frame rate. This does not need to be cross platform, Windows (Vista and XP) only. I have read a few things about using the Windows Media SDK or DirectShow, but none of them are that explicit about providing code samples. Could anyone provide some insight, or some valuable resources that might help me to do this in C#?
At the risk of being voted down, I'll offer a possible alternative option-- a buffered Bitmap animation. ``` double framesPerSecond; Bitmap[] imagesToDisplay; // add the desired bitmaps to this array Timer playbackTimer; int currentImageIndex; PictureBox displayArea; (...) currentImageIndex = 0; playbackTimer.Interval = 1000 / framesPerSecond; playbackTimer.AutoReset = true; playbackTimer.Elapsed += new ElapsedEventHandler(playbackNextFrame); playbackTimer.Start(); (...) void playbackNextFrame(object sender, ElapsedEventArgs e) { if (currentImageIndex + 1 >= imagesToDisplay.Length) { playbackTimer.Stop(); return; } displayArea.Image = imagesToDisplay[currentImageIndex++]; } ``` An approach such as this works well if the viewing user has access to the images, enough resources to keep the images in memory, doesn't want to wait for a video to encode, and there may exist a need for different playback speeds. ...just throwing it out there.
251,479
<p>I acquired a database from another developer. He didn't use auto_incrementers on any tables. They all have primary key ID's, but he did all the incrementing manually, in code.</p> <p>Can I turn those into Auto_incrementers now?</p> <hr> <p>Wow, very nice, thanks a ton. It worked without a hitch on one of my tables. But a second table, i'm getting this error...Error on rename of '.\DBNAME#sql-6c8_62259c' to '.\DBNAME\dealer_master_events'</p>
[ { "answer_id": 251526, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": -1, "selected": false, "text": "<p>As long as you have unique integers (or some unique value) in the current PK, you could create a new table, and insert into it with IDENTITY INSERT ON. Then drop the old table, and rename the new table.</p>\n\n<p>Don't forget to recreate any indexes.</p>\n" }, { "answer_id": 251529, "author": "Alex Weinstein", "author_id": 16668, "author_profile": "https://Stackoverflow.com/users/16668", "pm_score": 0, "selected": false, "text": "<p>Yes, easy. Just run a data-definition query to update the tables, adding an AUTO_INCREMENT column. </p>\n\n<p>If you have an existing database, be careful to preserve any foreign-key relationships that might already be there on the \"artificially created\" primary keys.</p>\n" }, { "answer_id": 251576, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 3, "selected": false, "text": "<p>I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?</p>\n\n<p>Something like:</p>\n\n<pre><code>ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT \n</code></pre>\n\n<p>I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.</p>\n\n<pre><code>ALTER TABLE `content` auto_increment = MAX(`id`) + 1\n</code></pre>\n\n<p>Again, untested but I believe it will work.</p>\n" }, { "answer_id": 251630, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 8, "selected": true, "text": "<p>For example, here's a table that has a primary key but is not <code>AUTO_INCREMENT</code>:</p>\n\n<pre><code>mysql&gt; CREATE TABLE foo (\n id INT NOT NULL,\n PRIMARY KEY (id)\n);\nmysql&gt; INSERT INTO foo VALUES (1), (2), (5);\n</code></pre>\n\n<p>You can <code>MODIFY</code> the column to redefine it with the <code>AUTO_INCREMENT</code> option:</p>\n\n<pre><code>mysql&gt; ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;\n</code></pre>\n\n<p>Verify this has taken effect:</p>\n\n<pre><code>mysql&gt; SHOW CREATE TABLE foo;\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>CREATE TABLE foo (\n `id` INT(11) NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1\n</code></pre>\n\n<p>Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The <code>PRIMARY KEY</code> constraint is unaffected, and you don't need to mention in in the <code>ALTER TABLE</code> statement.</p>\n\n<p>Next you can test that an insert generates a new value:</p>\n\n<pre><code>mysql&gt; INSERT INTO foo () VALUES (); -- yes this is legal syntax\nmysql&gt; SELECT * FROM foo;\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>+----+\n| id |\n+----+\n| 1 | \n| 2 | \n| 5 | \n| 6 | \n+----+\n4 rows in set (0.00 sec)\n</code></pre>\n\n<p>I tested this on MySQL 5.0.51 on Mac OS X.</p>\n\n<p>I also tested with <code>ENGINE=InnoDB</code> and a dependent table. Modifying the <code>id</code> column definition does not interrupt referential integrity.</p>\n\n<hr>\n\n<p>To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/160233/what-does-mysql-error-1025-hy000-error-on-rename-of-foo-errorno-150-mean\">What does mysql error 1025 (HY000): Error on rename of &#39;./foo&#39; (errorno: 150) mean?</a></li>\n<li><a href=\"http://www.simplicidade.org/notes/archives/2008/03/mysql_errno_150.html\" rel=\"noreferrer\">http://www.simplicidade.org/notes/archives/2008/03/mysql_errno_150.html</a></li>\n</ul>\n" }, { "answer_id": 2051739, "author": "Michael A. Griffey", "author_id": 249181, "author_profile": "https://Stackoverflow.com/users/249181", "pm_score": 3, "selected": false, "text": "<p>None of the above worked for my table. I have a table with an unsigned integer as the primary key with values ranging from 0 to 31543. Currently there are over 19 thousand records. I had to modify the column to <code>AUTO_INCREMENT</code> (<code>MODIFY COLUMN</code>'id'<code>INTEGER UNSIGNED NOT NULL AUTO_INCREMENT</code>) and set the seed(<code>AUTO_INCREMENT = 31544</code>) in the same statement.</p>\n\n<pre><code>ALTER TABLE `'TableName'` MODIFY COLUMN `'id'` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 31544;\n</code></pre>\n" }, { "answer_id": 21945624, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This worked for me (i wanted to make id primary and set auto increment)</p>\n\n<p>ALTER TABLE <code>table_name</code> CHANGE <code>id</code> <code>id</code> INT PRIMARY KEY AUTO_INCREMENT;</p>\n" }, { "answer_id": 55655455, "author": "Dima Dz", "author_id": 4685379, "author_profile": "https://Stackoverflow.com/users/4685379", "pm_score": 2, "selected": false, "text": "<pre><code>ALTER TABLE `foo` MODIFY COLUMN `bar_id` INT NOT NULL AUTO_INCREMENT;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>ALTER TABLE `foo` CHANGE `bar_id` `bar_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;\n</code></pre>\n\n<p>But none of these will work if your <code>bar_id</code> is a foreign key in another table: you'll be getting </p>\n\n<pre><code>an error 1068: Multiple primary key defined\n</code></pre>\n\n<p>To solve this, temporary disable foreign key constraint checks by</p>\n\n<pre><code>set foreign_key_checks = 0;\n</code></pre>\n\n<p>and after running the statements above, enable them back again. </p>\n\n<pre><code>set foreign_key_checks = 1;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
I acquired a database from another developer. He didn't use auto\_incrementers on any tables. They all have primary key ID's, but he did all the incrementing manually, in code. Can I turn those into Auto\_incrementers now? --- Wow, very nice, thanks a ton. It worked without a hitch on one of my tables. But a second table, i'm getting this error...Error on rename of '.\DBNAME#sql-6c8\_62259c' to '.\DBNAME\dealer\_master\_events'
For example, here's a table that has a primary key but is not `AUTO_INCREMENT`: ``` mysql> CREATE TABLE foo ( id INT NOT NULL, PRIMARY KEY (id) ); mysql> INSERT INTO foo VALUES (1), (2), (5); ``` You can `MODIFY` the column to redefine it with the `AUTO_INCREMENT` option: ``` mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT; ``` Verify this has taken effect: ``` mysql> SHOW CREATE TABLE foo; ``` Outputs: ``` CREATE TABLE foo ( `id` INT(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 ``` Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The `PRIMARY KEY` constraint is unaffected, and you don't need to mention in in the `ALTER TABLE` statement. Next you can test that an insert generates a new value: ``` mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax mysql> SELECT * FROM foo; ``` Outputs: ``` +----+ | id | +----+ | 1 | | 2 | | 5 | | 6 | +----+ 4 rows in set (0.00 sec) ``` I tested this on MySQL 5.0.51 on Mac OS X. I also tested with `ENGINE=InnoDB` and a dependent table. Modifying the `id` column definition does not interrupt referential integrity. --- To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem: * [What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?](https://stackoverflow.com/questions/160233/what-does-mysql-error-1025-hy000-error-on-rename-of-foo-errorno-150-mean) * <http://www.simplicidade.org/notes/archives/2008/03/mysql_errno_150.html>
251,482
<p>I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:</p> <pre><code>myvalue = CType(value, "String, Integer or Boolean") </code></pre> <p>The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.</p> <p>Is this possible?</p>
[ { "answer_id": 251508, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<p>Sure, but <code>myvalue</code> will have to be defined as of type <code>Object</code>, and you don't necessarily want that. Perhaps this is a case better served by generics.</p>\n\n<p>What determines what type will be used?</p>\n" }, { "answer_id": 251517, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>Well, how do you determine which type is required? As Joel said, this is probably a case for generics. The thing is: since you don't know the type at compile time, you can't treat the value returned anyway so casting doesn't really make sense here.</p>\n" }, { "answer_id": 251558, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 2, "selected": false, "text": "<p>Maybe instead of dynamically casting something (which doesn't seem to work) you could use reflection instead. It is easy enough to get and invoke specific methods or properties.</p>\n\n<pre><code>Dim t As Type = testObject.GetType()\nDim prop As PropertyInfo = t.GetProperty(\"propertyName\")\nDim gmi As MethodInfo = prop.GetGetMethod()\ngmi.Invoke(testObject, Nothing)\n</code></pre>\n\n<p>It isn't pretty but you could do some of that in one line instead of so many.</p>\n" }, { "answer_id": 251571, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 3, "selected": false, "text": "<p>This is the shortest way to do it. I've tested it with multiple types.</p>\n\n<pre><code>Sub DoCast(ByVal something As Object)\n\n Dim newSomething = Convert.ChangeType(something, something.GetType())\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 251587, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 3, "selected": false, "text": "<pre><code> Dim bMyValue As Boolean\n Dim iMyValue As Integer\n Dim sMyValue As String \n Dim t As Type = myValue.GetType\n\n\n Select Case t.Name\n Case \"String\"\n sMyValue = ctype(myValue, string)\n Case \"Boolean\"\n bMyValue = ctype(myValue, boolean)\n Case \"Integer\"\n iMyValue = ctype(myValue, Integer)\n End Select\n</code></pre>\n\n<p>It's a bit hacky but it works. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968/" ]
I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this: ``` myvalue = CType(value, "String, Integer or Boolean") ``` The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database. Is this possible?
Sure, but `myvalue` will have to be defined as of type `Object`, and you don't necessarily want that. Perhaps this is a case better served by generics. What determines what type will be used?
251,485
<p>Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:</p> <pre><code>$this-&gt;{$methodName}($arg1, $arg2, $arg3); </code></pre>
[ { "answer_id": 251499, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>Just omit the braces:</p>\n\n<pre><code>$this-&gt;$methodName($arg1, $arg2, $arg3);\n</code></pre>\n" }, { "answer_id": 251512, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 9, "selected": true, "text": "<p>There is more than one way to do that:</p>\n\n<pre><code>$this-&gt;{$methodName}($arg1, $arg2, $arg3);\n$this-&gt;$methodName($arg1, $arg2, $arg3);\ncall_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));\n</code></pre>\n\n<p>You may even use the reflection api <a href=\"http://php.net/manual/en/class.reflection.php\" rel=\"noreferrer\">http://php.net/manual/en/class.reflection.php</a></p>\n" }, { "answer_id": 251514, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<p>You can also use <code>call_user_func()</code> and <code>call_user_func_array()</code></p>\n" }, { "answer_id": 251516, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>If you're working within a class in PHP, then I would recommend using the overloaded __call function in PHP5. You can find the reference <a href=\"http://us.php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Basically __call does for dynamic functions what __set and __get do for variables in OO PHP5.</p>\n" }, { "answer_id": 371090, "author": "user46637", "author_id": 46637, "author_profile": "https://Stackoverflow.com/users/46637", "pm_score": 2, "selected": false, "text": "<p>In my case.</p>\n\n<pre><code>$response = $client-&gt;{$this-&gt;requestFunc}($this-&gt;requestMsg);\n</code></pre>\n\n<p>Using PHP SOAP.</p>\n" }, { "answer_id": 27148640, "author": "David", "author_id": 428640, "author_profile": "https://Stackoverflow.com/users/428640", "pm_score": 2, "selected": false, "text": "<p>You can store a method in a single variable using a closure:</p>\n\n<pre><code>class test{ \n\n function echo_this($text){\n echo $text;\n }\n\n function get_method($method){\n $object = $this;\n return function() use($object, $method){\n $args = func_get_args();\n return call_user_func_array(array($object, $method), $args); \n };\n }\n}\n\n$test = new test();\n$echo = $test-&gt;get_method('echo_this');\n$echo('Hello'); //Output is \"Hello\"\n</code></pre>\n\n<p>EDIT: I've edited the code and now it's compatible with PHP 5.3. Another example <a href=\"https://stackoverflow.com/a/27149017/428640\">here</a></p>\n" }, { "answer_id": 35025197, "author": "Snapey", "author_id": 67167, "author_profile": "https://Stackoverflow.com/users/67167", "pm_score": 1, "selected": false, "text": "<p>Still valid after all these years! Make sure you trim $methodName if it is user defined content. I could not get $this->$methodName to work until I noticed it had a leading space.</p>\n" }, { "answer_id": 41514419, "author": "RodolfoNeto", "author_id": 2938768, "author_profile": "https://Stackoverflow.com/users/2938768", "pm_score": 4, "selected": false, "text": "<p>You can use the Overloading in PHP:\n<a href=\"http://php.net/manual/en/language.oop5.overloading.php\" rel=\"noreferrer\">Overloading</a></p>\n\n<pre><code>class Test {\n\n private $name;\n\n public function __call($name, $arguments) {\n echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);\n //do a get\n if (preg_match('/^get_(.+)/', $name, $matches)) {\n $var_name = $matches[1];\n return $this-&gt;$var_name ? $this-&gt;$var_name : $arguments[0];\n }\n //do a set\n if (preg_match('/^set_(.+)/', $name, $matches)) {\n $var_name = $matches[1];\n $this-&gt;$var_name = $arguments[0];\n }\n }\n}\n\n$obj = new Test();\n$obj-&gt;set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String\necho $obj-&gt;get_name();//Echo:Method Name: get_name Arguments:\n //return: Any String\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this: ``` $this->{$methodName}($arg1, $arg2, $arg3); ```
There is more than one way to do that: ``` $this->{$methodName}($arg1, $arg2, $arg3); $this->$methodName($arg1, $arg2, $arg3); call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3)); ``` You may even use the reflection api <http://php.net/manual/en/class.reflection.php>
251,532
<p>If I have a URL (eg. <a href="http://www.foo.com/alink.pl?page=2" rel="noreferrer">http://www.foo.com/alink.pl?page=2</a>), I want to determine if I am being redirected to another link. I'd also like to know the final URL (eg. <a href="http://www.foo.com/other_link.pl" rel="noreferrer">http://www.foo.com/other_link.pl</a>). Finally, I want to be able to do this in Perl and Groovy.</p>
[ { "answer_id": 251544, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Well, I know nothing about either Perl or groovy, so I'll give you an another from an HTTP point of view, and you'll have to adapt.</p>\n\n<p>Normally, you make an HTTP request, and you get back some HTML text along with a response code. The response code for Success is 200. Any response code in the 300 range is some form of a redirect.</p>\n" }, { "answer_id": 251559, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>In Perl you can use <a href=\"http://search.cpan.org/~gaas/libwww-perl/lib/LWP/UserAgent.pm\" rel=\"nofollow noreferrer\">LWP::Useragent</a> for that. I guess the easiest way is to add a <code>response_redirect</code> handler using <code>add_handler</code>.</p>\n" }, { "answer_id": 251569, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>Referring to James's answer - sample HTTP session:</p>\n\n<pre><code>$ telnet www.google.com 80\nHEAD / HTTP/1.1\nHOST: www.google.com\n\n\nHTTP/1.1 302 Found\nLocation: http://www.google.it/\nCache-Control: private\nContent-Type: text/html; charset=UTF-8\nSet-Cookie: ##############################\nDate: Thu, 30 Oct 2008 20:03:36 GMT\nServer: ####\nContent-Length: 218\n</code></pre>\n\n<p>Using HEAD instead of GET you get only the header. \"302\" means a temporary redirection, \"Location:\" is where you are redirected to.</p>\n" }, { "answer_id": 251676, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 5, "selected": true, "text": "<p>In Perl:</p>\n\n<pre><code>use LWP::UserAgent;\nmy $ua = LWP::UserAgent-&gt;new;\n\nmy $request = HTTP::Request-&gt;new( GET =&gt; 'http://google.com/' );\nmy $response = $ua-&gt;request($request);\nif ( $response-&gt;is_success and $response-&gt;previous ) {\n print $request-&gt;url, ' redirected to ', $response-&gt;request-&gt;uri, \"\\n\";\n}\n</code></pre>\n" }, { "answer_id": 252024, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>A quick &amp; dirty groovy script to show the concepts -- Note, this is using <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/net/HttpURLConnection.html\" rel=\"nofollow noreferrer\">java.net.HttpURLConnection</a></p>\n\n<p>In order to detect the redirect, you have to use <code>setFollowRedirects(false)</code>. Otherwise, you end up on the redirected page anyway with a <code>responseCode</code> of 200. The downside is you then have to navigate the redirect yourself.</p>\n\n<pre><code>URL url = new URL ('http://google.com')\nHttpURLConnection conn = url.openConnection()\nconn.followRedirects = false\nconn.requestMethod = 'HEAD'\nprintln conn.responseCode\n// Not ideal - should check response code too\nif (conn.headerFields.'Location') {\n println conn.headerFields.'Location'\n}\n\n301\n[\"http://www.google.com/\"]\n</code></pre>\n" }, { "answer_id": 6325129, "author": "Rusty Hodge", "author_id": 795147, "author_profile": "https://Stackoverflow.com/users/795147", "pm_score": 1, "selected": false, "text": "<p>I think this will work for 301 redirects.</p>\n\n<pre><code>use LWP::UserAgent;\nmy $ua = LWP::UserAgent-&gt;new;\n\nmy $request = HTTP::Request-&gt;new( GET =&gt; 'http://google.com/' );\nmy $response = $ua-&gt;request($request);\nif ( $response-&gt;is_redirect ) {\n print $request-&gt;url . \" redirected to location \" . $response-&gt;header('Location') . \"\\n\";\n} \n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I have a URL (eg. <http://www.foo.com/alink.pl?page=2>), I want to determine if I am being redirected to another link. I'd also like to know the final URL (eg. <http://www.foo.com/other_link.pl>). Finally, I want to be able to do this in Perl and Groovy.
In Perl: ``` use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $request = HTTP::Request->new( GET => 'http://google.com/' ); my $response = $ua->request($request); if ( $response->is_success and $response->previous ) { print $request->url, ' redirected to ', $response->request->uri, "\n"; } ```
251,535
<p>One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year.</p> <p>as of today 10/30/2008</p> <p>01/01/01 = 01/01/2001</p> <p>01/01/09 = 01/01/1909</p> <p>This is a strange requirement, and I solved the problem, I just don't like my solution. It feels like there is a better way to do this.</p> <p>Thanks for the help.</p> <pre><code>public static String stupidDate(String dateString) { String twoDigitYear = StringUtils.right(dateString, 2); String newDate = StringUtils.left(dateString, dateString.length() - 2); int year = NumberUtils.toInt(twoDigitYear); Calendar c = GregorianCalendar.getInstance(); int centuryInt = c.get(Calendar.YEAR) - year; newDate = newDate + StringUtils.left(Integer.toString(centuryInt), 2) + twoDigitYear; return newDate; } </code></pre>
[ { "answer_id": 251570, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>public static String anEasierStupidDateWithNoStringParsing(String dateString) {\n DateFormat df = new SimpleDateFormat(\"MM/dd/yyyy\");\n\n //handling ParseExceptions is an exercise left to the reader!\n Date date = df.parse(dateString);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n\n Calendar now = Calendar.getInstance();\n if (cal.after(now)) {\n cal.add(Calendar.YEAR, -100);\n }\n\n return cal;\n}\n</code></pre>\n\n<p>In other words, let SimpleDateFormat parse the String and just adjust the year to be the previous century if SimpleDateFormat (<a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\">which has it's own rules for interpreting year strings</a>) returns a date that is after the current date. </p>\n\n<p>This would guarantee that all dates returned are in the past. However, it doesn't account for any dates that might be parsed as <em>before</em> this past century - for example, with the format <code>MM/dd/yyyy</code>, a date string like \"01/11/12\" parses to Jan 11, 12 A.D.</p>\n" }, { "answer_id": 251719, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "<p>If Joda Time is an option:</p>\n\n<pre><code>String inputDate = \"01/01/08\";\n// assuming U.S. style date, since it's not clear from your original question\nDateTimeFormatter parser = DateTimeFormat.forPattern(\"MM/dd/yy\");\nDateTime dateTime = parser.parseDateTime(inputDate);\n// if after current time\nif (dateTime.isAfter(new DateTime())) {\n dateTime = dateTime.minus(Years.ONE);\n}\n\nreturn dateTime.toString(\"MM/dd/yyyy\");\n</code></pre>\n\n<p>I know Joda Time isn't part of Java SE, and as I've said in another thread, I usually do not condone using a third-party library when there's a Java library that does the same thing. However, the person who is developing Joda Time is also leading JSR310 - the Date and Time API that'll make it into Java 7. So I Joda Time is basically going to be in future Java releases.</p>\n" }, { "answer_id": 251720, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "<p>SimpleDateFormat already does two-digit year parsing for you, using the two-letter ‘yy’ format. (It'll still allow four digits, obviously.)</p>\n\n<p>By default it uses now-80→now+20, so it's not exactly the same rule you propose, but it's reasonable and standardised (in the Java world at least), and can be overridden using set2DigitYearStart() if you want.</p>\n\n<pre><code>DateFormat informat= new SimpleDateFormat(\"MM/dd/yy\");\nDateFormat outformat= new SimpleDateFormat(\"MM/dd/yyyy\");\nreturn outformat.format(informat.parse(dateString));\n</code></pre>\n\n<p>In the longer term, try to migrate to ISO8601 date formatting (yyyy-MM-dd), because MM/dd/yy is approximately the worst possible date format and is bound to cause problems eventually.</p>\n" }, { "answer_id": 251836, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 5, "selected": true, "text": "<p>Groovy script (easy enough to throw into java) demonstrating the point @bobince made about SimpleDateFormat.</p>\n\n<pre><code>import java.text.SimpleDateFormat\n\nSimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy')\nSimpleDateFormat fmt = new SimpleDateFormat('yyyy-MM-dd')\n\nCalendar cal = Calendar.getInstance()\ncal.add(Calendar.YEAR, -100)\nsdf.set2DigitYearStart(cal.getTime())\n\ndates = ['01/01/01', '10/30/08','01/01/09']\ndates.each {String d -&gt;\n println fmt.format(sdf.parse(d))\n}\n</code></pre>\n\n<p>Yields</p>\n\n<pre><code>2001-01-01\n2008-10-30\n1909-01-01\n</code></pre>\n" }, { "answer_id": 26647748, "author": "chetan singhal", "author_id": 760935, "author_profile": "https://Stackoverflow.com/users/760935", "pm_score": 0, "selected": false, "text": "<pre><code>Date deliverDate = new SimpleDateFormat(\"MM/dd/yy\").parse(deliverDateString);\nString dateString2 = new SimpleDateFormat(\"yyyy-MM-dd\").format(deliverDate);\n</code></pre>\n\n<p>Working for me.</p>\n" }, { "answer_id": 74511905, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://stackoverflow.com/a/251836/10819573\">accepted answer</a> uses legacy date-time API which was the correct thing to do in 2008 when the question was asked. In March 2014, <code>java.time</code> API supplanted the <a href=\"https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html\" rel=\"nofollow noreferrer\">error-prone legacy date-time API</a>. Since then, it has been strongly recommended to use this modern date-time API.</p>\n<h2>java.time API</h2>\n<ol>\n<li>You can put optional patterns between <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html#optionalStart--\" rel=\"nofollow noreferrer\"><code>DateTimeFormatterBuilder#optionalStart</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html#optionalEnd--\" rel=\"nofollow noreferrer\"><code>DateTimeFormatterBuilder#optionalEnd</code></a> and create a formatter which can parse a date string with either a four-digit year or a two-digit year.</li>\n<li>Using the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html#appendValueReduced-java.time.temporal.TemporalField-int-int-int-\" rel=\"nofollow noreferrer\"><code>DateTimeFormatterBuilder#appendValueReduced</code></a>, you can specify a base value for the year as per your requirement.</li>\n</ol>\n<p><strong>Demo</strong>:</p>\n<pre><code>import java.time.LocalDate;\nimport java.time.Year;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.temporal.ChronoField;\nimport java.util.Locale;\nimport java.util.stream.Stream;\n\npublic class Main {\n public static void main(String[] args) {\n DateTimeFormatter parser = new DateTimeFormatterBuilder()\n .appendPattern(&quot;M/d/&quot;)\n .optionalStart()\n .appendPattern(&quot;uuuu&quot;)\n .optionalEnd()\n .optionalStart()\n .appendValueReduced(ChronoField.YEAR, 2, 2, Year.now().minusYears(100).getValue())\n .optionalEnd()\n .toFormatter(Locale.ENGLISH);\n\n // Test\n Stream.of(\n &quot;1/2/2022&quot;,\n &quot;01/2/2022&quot;,\n &quot;1/02/2022&quot;,\n &quot;01/02/2022&quot;,\n &quot;1/2/22&quot;,\n &quot;1/2/21&quot;,\n &quot;1/2/20&quot;,\n &quot;1/2/23&quot;,\n &quot;1/2/24&quot;\n )\n .map(s -&gt; LocalDate.parse(s, parser))\n .forEach(System.out::println);\n }\n}\n</code></pre>\n<p><strong>Output</strong>:</p>\n<pre><code>2022-01-02\n2022-01-02\n2022-01-02\n2022-01-02\n1922-01-02\n2021-01-02\n2020-01-02\n1923-01-02\n1924-01-02\n</code></pre>\n<p>Note that the dates with a two-digit year greater than the current year are parsed into a <code>LocalDate</code> with the last century.</p>\n<hr />\n<h2>How to switch from the legacy to the modern date-time API?</h2>\n<p>You can switch from the legacy to the modern date-time API using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant--\" rel=\"nofollow noreferrer\"><code>Date#toInstant</code></a> on a java-util-date instance. Once you have an <code>Instant</code>, you can easily obtain other date-time types of <code>java.time</code> API. An <code>Instant</code> represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as <code>Z</code> which stands for Zulu-time and has a <code>ZoneOffset</code> of <code>+00:00</code>).</p>\n<p><strong>Demo</strong>:</p>\n<pre><code>public class Main {\n public static void main(String[] args) {\n Date date = new Date();\n Instant instant = date.toInstant();\n System.out.println(instant);\n\n ZonedDateTime zdt = instant.atZone(ZoneId.of(&quot;Asia/Kolkata&quot;));\n System.out.println(zdt);\n\n OffsetDateTime odt = instant.atOffset(ZoneOffset.of(&quot;+05:30&quot;));\n System.out.println(odt);\n // Alternatively, using time-zone\n odt = instant.atZone(ZoneId.of(&quot;Asia/Kolkata&quot;)).toOffsetDateTime();\n System.out.println(odt);\n\n LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of(&quot;Asia/Kolkata&quot;));\n System.out.println(ldt);\n // Alternatively,\n ldt = instant.atZone(ZoneId.of(&quot;Asia/Kolkata&quot;)).toLocalDateTime();\n System.out.println(ldt);\n }\n}\n</code></pre>\n<p><strong>Output</strong>:</p>\n<pre><code>2022-11-20T20:32:42.823Z\n2022-11-21T02:02:42.823+05:30[Asia/Kolkata]\n2022-11-21T02:02:42.823+05:30\n2022-11-21T02:02:42.823+05:30\n2022-11-21T02:02:42.823\n2022-11-21T02:02:42.823\n</code></pre>\n<p>Learn more about the modern Date-Time API from <strong><a href=\"https://docs.oracle.com/javase/tutorial/datetime/index.html\" rel=\"nofollow noreferrer\">Trail: Date Time</a></strong>.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year. as of today 10/30/2008 01/01/01 = 01/01/2001 01/01/09 = 01/01/1909 This is a strange requirement, and I solved the problem, I just don't like my solution. It feels like there is a better way to do this. Thanks for the help. ``` public static String stupidDate(String dateString) { String twoDigitYear = StringUtils.right(dateString, 2); String newDate = StringUtils.left(dateString, dateString.length() - 2); int year = NumberUtils.toInt(twoDigitYear); Calendar c = GregorianCalendar.getInstance(); int centuryInt = c.get(Calendar.YEAR) - year; newDate = newDate + StringUtils.left(Integer.toString(centuryInt), 2) + twoDigitYear; return newDate; } ```
Groovy script (easy enough to throw into java) demonstrating the point @bobince made about SimpleDateFormat. ``` import java.text.SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy') SimpleDateFormat fmt = new SimpleDateFormat('yyyy-MM-dd') Calendar cal = Calendar.getInstance() cal.add(Calendar.YEAR, -100) sdf.set2DigitYearStart(cal.getTime()) dates = ['01/01/01', '10/30/08','01/01/09'] dates.each {String d -> println fmt.format(sdf.parse(d)) } ``` Yields ``` 2001-01-01 2008-10-30 1909-01-01 ```
251,541
<pre><code>public void Getrecords(ref IList iList,T dataItem) { iList = Populate.GetList&lt;dataItem&gt;() // GetListis defined as GetList&lt;T&gt; } </code></pre> <p>dataItem can be my order object or user object which will be decided at run time.The above does not work as it gives me this error The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type</p>
[ { "answer_id": 251550, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": -1, "selected": false, "text": "<p>You can use Generic with &lt; T > that will accept the type in runtime like you want.</p>\n" }, { "answer_id": 251552, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": -1, "selected": false, "text": "<pre><code>Getrecords&lt;T&gt; ...\n</code></pre>\n\n<p>This should have any more detailed information that you need. \n<a href=\"http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx</a></p>\n" }, { "answer_id": 251555, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<pre><code>public void GetRecords&lt;T&gt;(ref IList&lt;T&gt; iList, T dataitem)\n{\n}\n</code></pre>\n\n<p>What more are you looking for?</p>\n\n<p><strong>To Revised question:</strong></p>\n\n<pre><code> iList = Populate.GetList&lt;dataItem&gt;() \n</code></pre>\n\n<p>\"dataitem\" is a variable. You want to specify a type there:</p>\n\n<pre><code> iList = Populate.GetList&lt;T&gt;() \n</code></pre>\n\n<blockquote>\n <p>The type 'T' must have a public\n parameterless constructor in order to\n use it as parameter 'T' in the generic\n type GetList:new()</p>\n</blockquote>\n\n<p>This is saying that when you defined Populate.GetList(), you declared it like this:</p>\n\n<pre><code>IList&lt;T&gt; GetList&lt;T&gt;() where T: new() \n{...}\n</code></pre>\n\n<p>That tells the compiler that GetList can only use types that have a public parameterless constructor. You use T to create a GetList method in GetRecords (T refers to different types here), you have to put the same limitation on it:</p>\n\n<pre><code>public void GetRecords&lt;T&gt;(ref IList&lt;T&gt; iList, T dataitem) where T: new() \n{\n iList = Populate.GetList&lt;T&gt;();\n}\n</code></pre>\n" }, { "answer_id": 251561, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 2, "selected": false, "text": "<p>Your revised question passes in dataItem as an object of type T and then tries to use it as a type argument to GetList(). Perhaps you pass dataItem in only as a way to specify T? </p>\n\n<p>If so, the you may want something like so:</p>\n\n<pre><code>public IList&lt;T&gt; GetRecords&lt;T&gt;() {\n return Populate.GetList&lt;T&gt;();\n}\n</code></pre>\n\n<p>Then you call that like so:</p>\n\n<pre><code>IList&lt;int&gt; result = GetRecords&lt;int&gt;();\n</code></pre>\n" }, { "answer_id": 251605, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>The issue with demanding a public, parameterless constructor can only be because Populate.GetList demands it - i.e. has the \"T : new()\" constraint. To fix this, simply add the same constraint to your method.</p>\n\n<p>Actually, I doubt that <code>ref</code> is a good strategy here. At a push, <code>out</code> might do (since you don't read the value), but a far simpler (and more expected) option is a return value:</p>\n\n<pre><code>public IList&lt;T&gt; GetRecords&lt;T&gt;(T dataItem) where T : new()\n{ // MG: what does dataItem do here???\n return Populate.GetList&lt;T&gt;();\n}\n</code></pre>\n\n<p>Of course, at that point, the caller might as well just call <code>Populate.GetList</code> directly!</p>\n\n<p>I suspect you can remove dataItem too... but it isn't entirely clear from the question.</p>\n\n<p>If you don't intend it to be generic (and dataItem is the template object), then you can do this via <code>MakeGenericMethod</code>:</p>\n\n<pre><code>public static IList GetRecords(object dataItem) \n{\n Type type = dataItem.GetType();\n return (IList) typeof(Populate).GetMethod(\"GetList\")\n .MakeGenericMethod(type).Invoke(null,null);\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` public void Getrecords(ref IList iList,T dataItem) { iList = Populate.GetList<dataItem>() // GetListis defined as GetList<T> } ``` dataItem can be my order object or user object which will be decided at run time.The above does not work as it gives me this error The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type
``` public void GetRecords<T>(ref IList<T> iList, T dataitem) { } ``` What more are you looking for? **To Revised question:** ``` iList = Populate.GetList<dataItem>() ``` "dataitem" is a variable. You want to specify a type there: ``` iList = Populate.GetList<T>() ``` > > The type 'T' must have a public > parameterless constructor in order to > use it as parameter 'T' in the generic > type GetList:new() > > > This is saying that when you defined Populate.GetList(), you declared it like this: ``` IList<T> GetList<T>() where T: new() {...} ``` That tells the compiler that GetList can only use types that have a public parameterless constructor. You use T to create a GetList method in GetRecords (T refers to different types here), you have to put the same limitation on it: ``` public void GetRecords<T>(ref IList<T> iList, T dataitem) where T: new() { iList = Populate.GetList<T>(); } ```
251,554
<p>Attempting to deploy a MOSS solution to a UAT server from dev server <em>for the first time</em>. On executing this command </p> <pre><code>stsadm -o addsolution -filename xxx </code></pre> <p>I get a "Object reference not set to an instance of an object" Based on these links: (and others):</p> <p>[<a href="http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/63f0f95d-1215-4041-be6d-64ae63bda276/][1]" rel="nofollow noreferrer">http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/63f0f95d-1215-4041-be6d-64ae63bda276/][1]</a></p> <p>[<a href="http://www.telerik.com/community/forums/thread/b311D-bachea.aspx" rel="nofollow noreferrer">http://www.telerik.com/community/forums/thread/b311D-bachea.aspx</a> I made sure of the following:][1]</p> <ol> <li>I am a member of the farm admin group on the MOSS server </li> <li>I am member of the WSS_RESTRICTED_WPG on the server</li> <li>I was already in the WSS_ADMIN_WPG group on the server</li> </ol> <p>I checked the event log and found exceptions saying that the login to my Site Services DB failed. </p> <p>If I attempt to add myself via SQL Server Mgt Studio I do not have access to set access to that DB such as this:</p> <blockquote> <p>Reason: Cannot open database "SharedServices1_DB" requested by the login. The login failed. Login failed for user 'XXXXX\Administrator'.</p> </blockquote> <p>So, what am I missing? Any obvious things I need to do? Any helpful suggestions are welcome. </p> <p>Thanks</p> <p>[1]: <a href="http://MSDN" rel="nofollow noreferrer">http://MSDN</a> forum thread</p> <p>[1]: <a href="http://Telerik" rel="nofollow noreferrer">http://Telerik</a> support thread</p>
[ { "answer_id": 251713, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": -1, "selected": false, "text": "<p>The issue seems to not be with your solution, but with the SSP. Try deleting the UAT SSP and re-creating it and associate with your site(s).</p>\n\n<p>If that works, you will need to find out why the issue occured.</p>\n" }, { "answer_id": 251777, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 3, "selected": true, "text": "<p>I think the obvious thing you are missing is that the user account doesn't have the required permission to use the sharepoint database - just as it says in your post ;)</p>\n" }, { "answer_id": 264516, "author": "Clint Simon", "author_id": 26887, "author_profile": "https://Stackoverflow.com/users/26887", "pm_score": 2, "selected": false, "text": "<p>Adding solutions has nothing to do with the SSP. </p>\n\n<p>Usually this error would be because the user executing the stsadm command does not have access to the farm configuration database. This has to do with the fact that only the \"farm credentials\" account has access to the farm configuration database.</p>\n\n<p>You can try one of two things:</p>\n\n<ol>\n<li>Run the stsadm command as the \"farm credential\" account. Usually this is a service account, by default it is that account that was used to create the farm database during the installation process.</li>\n<li>Change the \"farm credential\" account to your logged in user. You can do this by using stsadm -o updatefarmcredentials</li>\n</ol>\n\n<p>Hope that helps!</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10552/" ]
Attempting to deploy a MOSS solution to a UAT server from dev server *for the first time*. On executing this command ``` stsadm -o addsolution -filename xxx ``` I get a "Object reference not set to an instance of an object" Based on these links: (and others): [<http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/63f0f95d-1215-4041-be6d-64ae63bda276/][1]> [<http://www.telerik.com/community/forums/thread/b311D-bachea.aspx> I made sure of the following:][1] 1. I am a member of the farm admin group on the MOSS server 2. I am member of the WSS\_RESTRICTED\_WPG on the server 3. I was already in the WSS\_ADMIN\_WPG group on the server I checked the event log and found exceptions saying that the login to my Site Services DB failed. If I attempt to add myself via SQL Server Mgt Studio I do not have access to set access to that DB such as this: > > Reason: Cannot open database > "SharedServices1\_DB" requested by the > login. The login failed. Login failed > for user 'XXXXX\Administrator'. > > > So, what am I missing? Any obvious things I need to do? Any helpful suggestions are welcome. Thanks [1]: <http://MSDN> forum thread [1]: <http://Telerik> support thread
I think the obvious thing you are missing is that the user account doesn't have the required permission to use the sharepoint database - just as it says in your post ;)
251,557
<p>I need to echo a string containing angle brackets (&lt; and >) to a file on a Windows machine. Basically what I want to do is the following:<br> <code>echo some string &lt; with angle &gt; brackets &gt;&gt;myfile.txt</code></p> <p>This doesn't work since the command interpreter gets confused with the angle brackets. I could quote the whole string like this:<br> <code>echo "some string &lt; with angle &gt; brackets" &gt;&gt;myfile.txt</code></p> <p>But then I have double quotes in my file that I don't want. </p> <p>Escaping the brackets ala unix doesn't work either:<br> <code>echo some string \&lt; with angle \&gt; brackets &gt;&gt;myfile.txt</code></p> <p>Ideas?</p>
[ { "answer_id": 251573, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 9, "selected": true, "text": "<p>The Windows escape character is ^, for some reason.</p>\n\n<pre><code>echo some string ^&lt; with angle ^&gt; brackets &gt;&gt;myfile.txt\n</code></pre>\n" }, { "answer_id": 251656, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Escaping the brackets ala unix doesn't\n work either: </p>\n \n <p>echo some string \\&lt; with\n angle \\> brackets >>myfile.txt</p>\n</blockquote>\n\n<p>The backslash would be considered the start of a absolute pathname.</p>\n" }, { "answer_id": 5455611, "author": "aalaap", "author_id": 44257, "author_profile": "https://Stackoverflow.com/users/44257", "pm_score": -1, "selected": false, "text": "<p>You can also use double quotes to escape special characters...</p>\n\n<pre><code>echo some string \"&lt;\" with angle \"&gt;\" brackets &gt;&gt;myfile.txt\n</code></pre>\n" }, { "answer_id": 11594161, "author": "sin3.14", "author_id": 1419252, "author_profile": "https://Stackoverflow.com/users/1419252", "pm_score": 5, "selected": false, "text": "<p>True, the official escape character is <code>^</code>, but be careful because sometimes you need <strong>three</strong> <code>^</code> characters. This is just <em>sometimes</em>:</p>\n\n<pre><code>C:\\WINDOWS&gt; echo ^&lt;html^&gt;\n&lt;html&gt;\n\nC:\\WINDOWS&gt; echo ^&lt;html^&gt; | sort\nThe syntax of the command is incorrect.\n\nC:\\WINDOWS&gt; echo ^^^&lt;html^^^&gt; | sort\n&lt;html&gt;\n\nC:\\WINDOWS&gt; echo ^^^&lt;html^^^&gt;\n^&lt;html^&gt;\n</code></pre>\n\n<p>One trick out of this nonsense is to use a command other than <code>echo</code> to do the output and quote with double quotes:</p>\n\n<pre><code>C:\\WINDOWS&gt; set/p _=\"&lt;html&gt;\" &lt;nul\n&lt;html&gt;\nC:\\WINDOWS&gt; set/p _=\"&lt;html&gt;\" &lt;nul | sort\n&lt;html&gt;\n</code></pre>\n\n<p>Note that this will not preserve leading spaces on the prompt text.</p>\n" }, { "answer_id": 26041395, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 3, "selected": false, "text": "<p>There are methods that avoid <code>^</code> escape sequences.</p>\n\n<p>You could use variables with delayed expansion. Below is a small batch script demonstration</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\nset \"line=&lt;html&gt;\"\necho !line!\n</code></pre>\n\n<p>Or you could use a FOR /F loop. From the command line:</p>\n\n<pre><code>for /f \"delims=\" %A in (\"&lt;html&gt;\") do @echo %~A\n</code></pre>\n\n<p>Or from a batch script:</p>\n\n<pre><code>@echo off\nfor /f \"delims=\" %%A in (\"&lt;html&gt;\") do echo %%~A\n</code></pre>\n\n<p>The reason these methods work is because both delayed expansion and FOR variable expansion occur after special operators like <code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>, <code>|</code>, <code>&amp;&amp;</code>, <code>||</code> are parsed. See <a href=\"https://stackoverflow.com/a/4095133/1012053\">How does the Windows Command Interpreter (CMD.EXE) parse scripts?</a> for more info.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/a/11594161/1012053\">sin3.14 points out that pipes may require multiple escapes</a>. For example:</p>\n\n<pre><code>echo ^^^&lt;html^^^&gt;|findstr .\n</code></pre>\n\n<p>The reason pipes require multiple escapes is because each side of the pipe is executed in a new CMD process, so the line gets parsed multiple times. See <a href=\"https://stackoverflow.com/q/8192318/1012053\">Why does delayed expansion fail when inside a piped block of code?</a> for an explanation of many awkward consequences of Window's pipe implementation.</p>\n\n<p>There is another method to avoid multiple escapes when using pipes. You can explicitly instantiate your own CMD process, and protect the single escape with quotes:</p>\n\n<pre><code>cmd /c \"echo ^&lt;html^&gt;\"|findstr .\n</code></pre>\n\n<p>If you want to use the delayed expansion technique to avoid escapes, then there are even more surprises (You might not be surprised if you are an expert on the design of CMD.EXE, but there is no official MicroSoft documentation that explains this stuff)</p>\n\n<p>Remember that each side of the pipe gets executed in its own CMD.EXE process, but the process does <strong><em>not</em></strong> inherit the delayed expansion state - it defaults to OFF. So you must explicitly instantiate your own CMD.EXE process and use the /V:ON option to enable delayed expansion.</p>\n\n<pre><code>@echo off\nsetlocal disableDelayedExpansion\nset \"line=&lt;html&gt;\"\ncmd /v:on /c echo !test!|findstr .\n</code></pre>\n\n<p>Note that delayed expansion is OFF in the parent batch script.</p>\n\n<p>But all hell breaks loose if delayed expansion is enabled in the parent script. The following does <strong><em>not</em></strong> work:</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\nset \"line=&lt;html&gt;\"\nREM - the following command fails\ncmd /v:on /c echo !test!|findstr .\n</code></pre>\n\n<p>The problem is that <code>!test!</code> is expanded in the parent script, so the new CMD process is trying to parse unprotected <code>&lt;</code> and <code>&gt;</code>.</p>\n\n<p>You could escape the <code>!</code>, but that can get tricky, because it depends on whether the <code>!</code> is quoted or not.</p>\n\n<p>If not quoted, then double escape is required:</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\nset \"line=&lt;html&gt;\"\ncmd /v:on /c echo ^^!test^^!|findstr .\n</code></pre>\n\n<p>If quoted, then a single escape is used:</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\nset \"line=&lt;html&gt;\"\ncmd /v:on /c \"echo ^!test^!\"|findstr .\n</code></pre>\n\n<p>But there is a surprising trick that avoids all escapes - enclosing the left side of the pipe prevents the parent script from expanding <code>!test!</code> prematurely:</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\nset \"line=&lt;html&gt;\"\n(cmd /v:on /c echo !test!)|findstr .\n</code></pre>\n\n<p>But I suppose even that is not a free lunch, because the batch parser introduces an extra (perhaps unwanted) space at the end when parentheses are used.</p>\n\n<p>Aint batch scripting fun ;-)</p>\n" }, { "answer_id": 33872568, "author": "orbitcowboy", "author_id": 4070000, "author_profile": "https://Stackoverflow.com/users/4070000", "pm_score": 2, "selected": false, "text": "<p>In order to use special characters, such as '>' on Windows with echo, you need to place a special escape character before it. </p>\n\n<p>For instance </p>\n\n<pre><code>echo A-&gt;B\n</code></pre>\n\n<p>will no work since '>' has to be escaped by '^':</p>\n\n<pre><code> echo A-^&gt;B\n</code></pre>\n\n<p>See also <a href=\"https://sites.google.com/site/opensourceconstriubtions/ettl-martin-1/tutorials/how-to-escape-special-characters-in-windows-batch-files-when-using-echo\" rel=\"nofollow noreferrer\">escape sequences</a>. \n<a href=\"https://i.stack.imgur.com/NfH6K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NfH6K.png\" alt=\"enter image description here\"></a></p>\n\n<p>There is a short batch file, which prints a basic set of special character and their escape sequences.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
I need to echo a string containing angle brackets (< and >) to a file on a Windows machine. Basically what I want to do is the following: `echo some string < with angle > brackets >>myfile.txt` This doesn't work since the command interpreter gets confused with the angle brackets. I could quote the whole string like this: `echo "some string < with angle > brackets" >>myfile.txt` But then I have double quotes in my file that I don't want. Escaping the brackets ala unix doesn't work either: `echo some string \< with angle \> brackets >>myfile.txt` Ideas?
The Windows escape character is ^, for some reason. ``` echo some string ^< with angle ^> brackets >>myfile.txt ```
251,560
<p>Our app (already deployed) is using an Access/Jet database. The upcoming version of our software requires some additional columns in one of the tables. I need to first check if these columns exist, and then add them if they don't.</p> <p>Can someone provide a quick code sample, link, or nudge in the right direction?</p> <p>(I'm using c#, but a VB.NET sample would be fine, too).</p>
[ { "answer_id": 251581, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Query the table for the field you expect and handle the error if the field is not there.</p>\n\n<p>Too add the column, just feed the database an <a href=\"http://msdn.microsoft.com/en-us/library/bb177883.aspx\" rel=\"nofollow noreferrer\">alter table</a> SQL statement.</p>\n" }, { "answer_id": 251596, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 4, "selected": true, "text": "<p>Off the top of my head, but something like:</p>\n\n<pre><code>Dim conn as New AdoConnection(someConnStr)\nDim cmd as New AdoCommand\ncmd.Connection = conn\ncmd.CommandText = \"ALTER TABLE X ADD COLUMN y COLUMNTYPE\"\ncmd.ComandType = CommandType.Text\ncmd.ExecuteNonQuery()\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
Our app (already deployed) is using an Access/Jet database. The upcoming version of our software requires some additional columns in one of the tables. I need to first check if these columns exist, and then add them if they don't. Can someone provide a quick code sample, link, or nudge in the right direction? (I'm using c#, but a VB.NET sample would be fine, too).
Off the top of my head, but something like: ``` Dim conn as New AdoConnection(someConnStr) Dim cmd as New AdoCommand cmd.Connection = conn cmd.CommandText = "ALTER TABLE X ADD COLUMN y COLUMNTYPE" cmd.ComandType = CommandType.Text cmd.ExecuteNonQuery() ```
251,592
<p>PHP (among others) will execute the deepest function first, working its way out. For example,</p> <pre><code>$text = strtoupper(str_replace('_', ' ', file_get_contents('file.txt'))); </code></pre> <p>I'm doing something very similar to the above example for a template parser. It looks for the tags</p> <pre><code>{@tag_name} </code></pre> <p>and replaces it with a variable of the name <strong>$tag_name</strong>. One more example:</p> <pre><code>$a = 'hello'; $b = ' world'; INPUT = 'This is my test {@a{@b}} string.'; OUTPUT (step 1) = 'This is my test {@a} world string.'; OUTPUT output = 'This is my test hello world string.'; </code></pre> <p>How can I go about doing this? Does this make sense? If not, I can try explaining better.</p>
[ { "answer_id": 251606, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": false, "text": "<p>This is not a trivial task. You need to parse the string manually and do your own logical substitutions. There's no magic function or functionality that will do this for you.</p>\n\n<p>My own template engine does about that (and more) and only the core (no template macros) weighs in at 600+ LOC</p>\n" }, { "answer_id": 251610, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "<p>At least in the given example, I don't understand why the @b token would be nested in the @a token. The two don't seem to have any need for each other. Are you trying to do something like this in Perl?</p>\n\n<pre><code>$a = \"b\";\n$b = \"Hello World!\";\n\nprint $$a;\n</code></pre>\n\n<p>output would then be \"Hello World\"</p>\n" }, { "answer_id": 251655, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 1, "selected": false, "text": "<p>Use a stack - put on top <code>array_push</code> each opened element and evaluate topmost <code>array_pop</code> on first closing mark.</p>\n" }, { "answer_id": 251869, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": true, "text": "<p>I'm not sure I understand the nesting in your example, as the example doesn't demonstrate a purpose behind nesting. Your example input could very easily be</p>\n\n<pre><code>'This is my test {@a} {@b} string.'\n</code></pre>\n\n<p>And using arrays in str_replace would handle this very simply and quickly.</p>\n\n<pre><code>$aVars = array('{@a}' =&gt; 'hello', '{@b}' =&gt; 'world');\n$sString = 'This is my test {@a} {@b} string.';\n\necho str_replace(array_keys($aVars), array_values($aVars), $sString);\n</code></pre>\n\n<p>Which gives us</p>\n\n<blockquote>\n <p>This is my test hello world string.</p>\n</blockquote>\n\n<p>Now, a recursive function for this isn't too difficult, though I'm not sure I understand how useful it would be. Here's a working example:</p>\n\n<pre><code>function template($sText, $aVars) {\n if (preg_match_all('/({@([^{}]+)})/',\n $sText, $aMatches, PREG_SET_ORDER)) {\n foreach($aMatches as $aMatch) {\n echo '&lt;pre&gt;' . print_r($aMatches, 1) . '&lt;/pre&gt;';\n\n if (array_key_exists($aMatch[2], $aVars)) {\n // replace the guy inside\n $sText = str_replace($aMatch[1], $aVars[$aMatch[2]], $sText);\n\n // now run through the text again since we have new variables\n $sText = template($sText, $aVars);\n }\n }\n }\n\n return $sText;\n}\n</code></pre>\n\n<p>That print_r will show you what the matches look like so you can follow the function through its paces. Now lets try it out...</p>\n\n<pre><code>$aVars = array('a' =&gt; 'hello', 'b' =&gt; 'world');\n$sStringOne = 'This is my test {@a} {@b} string.';\n$sStringTwo = 'This is my test {@a{@b}} string.';\n\necho template($sStringOne, $aVars) . '&lt;br /&gt;';\n</code></pre>\n\n<p>First Result:</p>\n\n<blockquote>\n <p>This is my test hello world string.</p>\n</blockquote>\n\n<p>Now lets try String Two</p>\n\n<pre><code>echo template($sStringTwo, $aVars) . '&lt;br /&gt;';\n</code></pre>\n\n<p>Second Result:</p>\n\n<blockquote>\n <p>This is my test {@aworld} string.</p>\n</blockquote>\n\n<p>That may very well be what you're looking for. Obviously you would need an <code>aworld</code> variable for this to work recursively...</p>\n\n<pre><code>$aVars = array('a' =&gt; '', 'b' =&gt; '2', 'a2' =&gt; 'hello world');\n\necho template($sStringTwo, $aVars) . '&lt;br /&gt;';\n</code></pre>\n\n<p>And our result.</p>\n\n<blockquote>\n <p>This is my test hello world string.</p>\n</blockquote>\n\n<p>And just for some fun with the recursion...</p>\n\n<pre><code>$aVars = array('a3' =&gt; 'hello world', 'b2' =&gt; '3', 'c1' =&gt; '2', 'd' =&gt; '1');\n$sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.';\n\necho template($sStringTre, $aVars) . '&lt;br /&gt;';\n</code></pre>\n\n<blockquote>\n <p>This is my test hello world string.</p>\n</blockquote>\n\n<p>Not sure if this is what you're asking for...</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32881/" ]
PHP (among others) will execute the deepest function first, working its way out. For example, ``` $text = strtoupper(str_replace('_', ' ', file_get_contents('file.txt'))); ``` I'm doing something very similar to the above example for a template parser. It looks for the tags ``` {@tag_name} ``` and replaces it with a variable of the name **$tag\_name**. One more example: ``` $a = 'hello'; $b = ' world'; INPUT = 'This is my test {@a{@b}} string.'; OUTPUT (step 1) = 'This is my test {@a} world string.'; OUTPUT output = 'This is my test hello world string.'; ``` How can I go about doing this? Does this make sense? If not, I can try explaining better.
I'm not sure I understand the nesting in your example, as the example doesn't demonstrate a purpose behind nesting. Your example input could very easily be ``` 'This is my test {@a} {@b} string.' ``` And using arrays in str\_replace would handle this very simply and quickly. ``` $aVars = array('{@a}' => 'hello', '{@b}' => 'world'); $sString = 'This is my test {@a} {@b} string.'; echo str_replace(array_keys($aVars), array_values($aVars), $sString); ``` Which gives us > > This is my test hello world string. > > > Now, a recursive function for this isn't too difficult, though I'm not sure I understand how useful it would be. Here's a working example: ``` function template($sText, $aVars) { if (preg_match_all('/({@([^{}]+)})/', $sText, $aMatches, PREG_SET_ORDER)) { foreach($aMatches as $aMatch) { echo '<pre>' . print_r($aMatches, 1) . '</pre>'; if (array_key_exists($aMatch[2], $aVars)) { // replace the guy inside $sText = str_replace($aMatch[1], $aVars[$aMatch[2]], $sText); // now run through the text again since we have new variables $sText = template($sText, $aVars); } } } return $sText; } ``` That print\_r will show you what the matches look like so you can follow the function through its paces. Now lets try it out... ``` $aVars = array('a' => 'hello', 'b' => 'world'); $sStringOne = 'This is my test {@a} {@b} string.'; $sStringTwo = 'This is my test {@a{@b}} string.'; echo template($sStringOne, $aVars) . '<br />'; ``` First Result: > > This is my test hello world string. > > > Now lets try String Two ``` echo template($sStringTwo, $aVars) . '<br />'; ``` Second Result: > > This is my test {@aworld} string. > > > That may very well be what you're looking for. Obviously you would need an `aworld` variable for this to work recursively... ``` $aVars = array('a' => '', 'b' => '2', 'a2' => 'hello world'); echo template($sStringTwo, $aVars) . '<br />'; ``` And our result. > > This is my test hello world string. > > > And just for some fun with the recursion... ``` $aVars = array('a3' => 'hello world', 'b2' => '3', 'c1' => '2', 'd' => '1'); $sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.'; echo template($sStringTre, $aVars) . '<br />'; ``` > > This is my test hello world string. > > > Not sure if this is what you're asking for...
251,636
<p>ExtJS has Ext.each() function, but is there a map() also hidden somewhere?</p> <p>I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.</p> <p>Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:</p> <pre><code>Ext.map = function(arr, f) { ... }; </code></pre> <p>But is this really the correct way to do this?</p>
[ { "answer_id": 251689, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>Since <code>map</code> is more of a utility than anything, I don't see why there would be any special way of plugging it into the Ext namespace; the way you propose would work well enough, though you might want to do it thusly:</p>\n\n<pre><code>if(Ext &amp;&amp; typeof(Ext.map) == \"undefined\") { // only if Ext exists &amp; map isn't already defined\n Ext.map = function(arr, f) { ... };\n}\n</code></pre>\n\n<p>Seems like that would be fine...but then, I don't use ExtJS, so I don't know. I did take a gander at their docs and it doesn't seem like there is anything special to do in this case.</p>\n" }, { "answer_id": 252049, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 3, "selected": true, "text": "<p>It appears, that my colleges here are using <a href=\"http://code.google.com/p/ext-basex/\" rel=\"nofollow noreferrer\">ext-basex</a>, which extends Array.prototype with map() and other methods.</p>\n\n<p>So I can just write:</p>\n\n<pre><code>[1, 2, 3].map( function(){ ... } );\n</code></pre>\n\n<p>Problem solved.</p>\n" }, { "answer_id": 252159, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "<p>ExtJS doesn't replace Javascript language itself. Array functions aren't in the focus of ExtJS core. However there is a special Ext.Array object type. You can extend it on your own.</p>\n\n<p>EDIT: Not Ext.Array, but just extended Array object.</p>\n" }, { "answer_id": 254194, "author": "David", "author_id": 9908, "author_profile": "https://Stackoverflow.com/users/9908", "pm_score": 1, "selected": false, "text": "<p>What about using one of the hybrid libraries like Ext+Prototype or Ext+Jquery. I've been using Extjs+Prototypejs for a while now and it helped me a lot to work into the Extjs code with having the more familiar prototypejs along for the ride as well.</p>\n\n<p><a href=\"http://extjs.com/products/extjs/build/\" rel=\"nofollow noreferrer\">http://extjs.com/products/extjs/build/</a> will build a custom tar/zip file of all the files you need to run extjs and (prototypejs|jquery|yahooUI).</p>\n" }, { "answer_id": 10012833, "author": "David Kanarek", "author_id": 98848, "author_profile": "https://Stackoverflow.com/users/98848", "pm_score": 2, "selected": false, "text": "<p>As of at least Ext4, Ext.Array.map is included.</p>\n\n<p><a href=\"http://docs.sencha.com/extjs/5.0.1/#!/api/Ext.Array-method-map\" rel=\"nofollow\">http://docs.sencha.com/extjs/5.0.1/#!/api/Ext.Array-method-map</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15982/" ]
ExtJS has Ext.each() function, but is there a map() also hidden somewhere? I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have. Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write: ``` Ext.map = function(arr, f) { ... }; ``` But is this really the correct way to do this?
It appears, that my colleges here are using [ext-basex](http://code.google.com/p/ext-basex/), which extends Array.prototype with map() and other methods. So I can just write: ``` [1, 2, 3].map( function(){ ... } ); ``` Problem solved.
251,651
<p>I have a table of about a million rows and I need to update every row in the table with the result of a lengthy calculation (the calculation gets a potentially different result for each row). Because it is time consuming, the DBA must be able to control execution. This particular calculation needs to be run once a year (it does a year-end summary). I wanted to create a job using DBMS_SCHEDULER.CREATE_JOB that would grab 100 rows from the table, update them and then stop; the next execution of the job would then pick up where the prior execution left off.</p> <p>My first thought was to include this code at the end of my stored procedure:</p> <pre><code>-- update 100 rows, storing the primary key of the last -- updated row in last_id -- make a new job that will run in about a minute and will -- start from the primary key value just after last_id dbms_scheduler.create_job ( job_name=&gt;'yearly_summary' , job_type=&gt;'STORED_PROCEDURE' , job_action=&gt;'yearly_summary_proc(' || last_id || ')' , start_date=&gt;CURRENT_TIMESTAMP + 1/24/60 , enabled=&gt;TRUE ); </code></pre> <p>But I get this error when the stored procedure runs:</p> <pre><code>ORA-27486: insufficient privileges ORA-06512: at "SYS.DBMS_ISCHED", line 99 ORA-06512: at "SYS.DBMS_SCHEDULER", line 262 ORA-06512: at "JBUI.YEARLY_SUMMARY_PROC", line 37 ORA-06512: at line 1 </code></pre> <p>Suggestions for other ways to do this are welcome. I'd prefer to use DBMS_SCHEDULER and I'd prefer not to have to create any tables; that's why I'm passing in the last_id to the stored procedure.</p>
[ { "answer_id": 251725, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "<p>I would tend to be wary about using jobs like this to control execution. Either the delay between successive jobs would tend to be too short for the DBA to figure out what job to kill/ pause/ etc. or the delay would be long enough that a significant fraction of the run time would be spent in delays between successive jobs.</p>\n\n<p>Without creating any new objects, you can use the <a href=\"http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_alert.htm#CHDCFHCI\" rel=\"noreferrer\">DBMS_ALERT</a> package to allow your DBA to send an alert that pauses the job. Your code could call the <code>DBMS_ALERT.WAITONE</code> method every hundred rows to check whether the DBA has signaled a particular alert (i.e. the <code>PAUSE_YEAREND_JOB</code> alert). If no alert was received, the code could continue on. If an alert was received, you could pause the code either until another alert (i.e. <code>RESUME_YEAREND_JOB</code>) was received or a fixed period of time or based on the message the DBA sent with the <code>PAUSE_YEAREND_JOB</code> alert (i.e. the message could be a number of seconds to pause or a date to pause until, etc.)</p>\n\n<p>Of course, you could do the same thing by creating a new table, having the DBA write a row to the table to pause the job, and reading from the table every N rows.</p>\n" }, { "answer_id": 251739, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 2, "selected": false, "text": "<p>Another avenue to explore would be the dbms scheduler's support tools for execution windows and resource plans.</p>\n\n<p><a href=\"http://www.oracle-base.com/articles/10g/Scheduler10g.php\" rel=\"nofollow noreferrer\">http://www.oracle-base.com/articles/10g/Scheduler10g.php</a></p>\n\n<p>and also:</p>\n\n<p><a href=\"http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14231/schedover.htm#sthref3501\" rel=\"nofollow noreferrer\">http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14231/schedover.htm#sthref3501</a></p>\n\n<p>With windows and resource plans your DBA can simply configure the system to execute your procedure to obey certain rules - including a job window and executing using only a certain number of resources (i.e. CPU usage).</p>\n\n<p>This way the procedure can run once a year, and CPU usage can be controlled.</p>\n\n<p>This though may not provide the manual control your DBA would like.</p>\n\n<p>Another idea would be to write your procedure to process all records, but commit every 1000 or so. The dbms job.cancel() command could be used by your DBA to cancel the job if they wanted it to stop, and then they can resume it (by rescheduling or rerunning it) when they're ready to go. The trick would be that the procedure would need to be able to keep track of rows processed, e.g. using a 'processed_date' column, or a separate table listing primary keys and processed date.</p>\n" }, { "answer_id": 252696, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>In addition to the answer about <code>DBMS_ALERT</code>, your DBA would appreciate the ability to see where your stored procedure is up to. You should use the <a href=\"http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_appinf.htm#sthref412\" rel=\"nofollow noreferrer\"><code>DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS</code></a> functionality in Oracle to do this.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3275/" ]
I have a table of about a million rows and I need to update every row in the table with the result of a lengthy calculation (the calculation gets a potentially different result for each row). Because it is time consuming, the DBA must be able to control execution. This particular calculation needs to be run once a year (it does a year-end summary). I wanted to create a job using DBMS\_SCHEDULER.CREATE\_JOB that would grab 100 rows from the table, update them and then stop; the next execution of the job would then pick up where the prior execution left off. My first thought was to include this code at the end of my stored procedure: ``` -- update 100 rows, storing the primary key of the last -- updated row in last_id -- make a new job that will run in about a minute and will -- start from the primary key value just after last_id dbms_scheduler.create_job ( job_name=>'yearly_summary' , job_type=>'STORED_PROCEDURE' , job_action=>'yearly_summary_proc(' || last_id || ')' , start_date=>CURRENT_TIMESTAMP + 1/24/60 , enabled=>TRUE ); ``` But I get this error when the stored procedure runs: ``` ORA-27486: insufficient privileges ORA-06512: at "SYS.DBMS_ISCHED", line 99 ORA-06512: at "SYS.DBMS_SCHEDULER", line 262 ORA-06512: at "JBUI.YEARLY_SUMMARY_PROC", line 37 ORA-06512: at line 1 ``` Suggestions for other ways to do this are welcome. I'd prefer to use DBMS\_SCHEDULER and I'd prefer not to have to create any tables; that's why I'm passing in the last\_id to the stored procedure.
I would tend to be wary about using jobs like this to control execution. Either the delay between successive jobs would tend to be too short for the DBA to figure out what job to kill/ pause/ etc. or the delay would be long enough that a significant fraction of the run time would be spent in delays between successive jobs. Without creating any new objects, you can use the [DBMS\_ALERT](http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_alert.htm#CHDCFHCI) package to allow your DBA to send an alert that pauses the job. Your code could call the `DBMS_ALERT.WAITONE` method every hundred rows to check whether the DBA has signaled a particular alert (i.e. the `PAUSE_YEAREND_JOB` alert). If no alert was received, the code could continue on. If an alert was received, you could pause the code either until another alert (i.e. `RESUME_YEAREND_JOB`) was received or a fixed period of time or based on the message the DBA sent with the `PAUSE_YEAREND_JOB` alert (i.e. the message could be a number of seconds to pause or a date to pause until, etc.) Of course, you could do the same thing by creating a new table, having the DBA write a row to the table to pause the job, and reading from the table every N rows.
251,688
<p>Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?</p> <pre><code>$ar = array(array(1, 10, 9.0, 'HELLO'), array(1, 11, 12.9, 'HELLO'), array(3, 12, 10.9, 'HELLO')); </code></pre> <p>Output should be like:</p> <p>max(12.9) min(10)</p>
[ { "answer_id": 251721, "author": "belunch", "author_id": 32867, "author_profile": "https://Stackoverflow.com/users/32867", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;?php\n$ar = array(array(1, 10, 9.0, 'HELLO'),\n array(1, 11, 12.9, 'HELLO'),\n array(3, 12, 10.9, 'HELLO'));\nfunction col($tbl,$col){\n $ret = array();\n foreach ($tbl as $row){\n $ret[count($ret)+1] = $row[$col];\n }\n return $ret;\n}\nprint (max(col($ar,2)).\"\\n\");\nprint (min(col($ar,1)).\"\\n\");\n?&gt;\n</code></pre>\n\n<p>is this what you look for? I guess its not the most efficient way. </p>\n" }, { "answer_id": 251754, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<p>Another option</p>\n\n<pre><code>&lt;?php\n\nfunction array_rotate( $array )\n{\n $rotated = array();\n foreach ( $array as $rowIndex =&gt; $col )\n {\n foreach ( $col as $colIndex =&gt; $value )\n {\n $rotated[$colIndex][$rowIndex] = $value;\n }\n }\n return $rotated;\n}\n\n$ar = array(array(1, 10, 9.0, 'HELLO'),\n array(1, 11, 12.9, 'HELLO'),\n array(3, 12, 10.9, 'HELLO'));\n\n$ar = array_rotate( $ar );\n\necho max( $ar[2] ), \"\\n\", min( $ar[1] );\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP? ``` $ar = array(array(1, 10, 9.0, 'HELLO'), array(1, 11, 12.9, 'HELLO'), array(3, 12, 10.9, 'HELLO')); ``` Output should be like: max(12.9) min(10)
``` <?php $ar = array(array(1, 10, 9.0, 'HELLO'), array(1, 11, 12.9, 'HELLO'), array(3, 12, 10.9, 'HELLO')); function col($tbl,$col){ $ret = array(); foreach ($tbl as $row){ $ret[count($ret)+1] = $row[$col]; } return $ret; } print (max(col($ar,2))."\n"); print (min(col($ar,1))."\n"); ?> ``` is this what you look for? I guess its not the most efficient way.
251,694
<p>I have Perl code which relies on <code>Term::ReadKey</code> to get the terminal width. My installation is missing this module, so I want to provide a default if the module isn't present rather than throw an exception.</p> <p>How can I conditionally use an optional module, without knowing ahead of time whether it is available.</p> <pre><code># but only if the module is installed and exists use Term::ReadKey; ... </code></pre> <p>How can I accomplish this?</p>
[ { "answer_id": 251736, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 4, "selected": false, "text": "<p>Check out the CPAN module <a href=\"http://search.cpan.org/perldoc?Module::Load::Conditional\" rel=\"noreferrer\">Module::Load::Conditional</a>. It will do what you want.</p>\n" }, { "answer_id": 251786, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 8, "selected": true, "text": "<p>Here's a bare-bones solution that does not require another module:</p>\n\n<pre><code>my $rc = eval\n{\n require Term::ReadKey;\n Term::ReadKey-&gt;import();\n 1;\n};\n\nif($rc)\n{\n # Term::ReadKey loaded and imported successfully\n ...\n}\n</code></pre>\n\n<p>Note that all the answers below (I hope they're below this one! :-) that use <code>eval { use SomeModule }</code> are wrong because <code>use</code> statements are evaluated at compile time, regardless of where in the code they appear. So if <code>SomeModule</code> is not available, the script will die immediately upon compiling.</p>\n\n<p>(A string eval of a <code>use</code> statement will also work (<code>eval 'use SomeModule';</code>), but there's no sense parsing and compiling new code at runtime when the <code>require</code>/<code>import</code> pair does the same thing, and is syntax-checked at compile time to boot.)</p>\n\n<p>Finally, note that my use of <code>eval { ... }</code> and <code>$@</code> here is succinct for the purpose of this example. In real code, you should use something like <a href=\"http://search.cpan.org/dist/Try-Tiny/\" rel=\"noreferrer\">Try::Tiny</a>, or at least <a href=\"http://search.cpan.org/dist/Try-Tiny/lib/Try/Tiny.pm#BACKGROUND\" rel=\"noreferrer\">be aware of the issues it addresses</a>.</p>\n" }, { "answer_id": 251833, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>The classic answer (dating back to Perl 4, at least, long before there was a 'use') was to 'require()' a module. This is executed as the script is run, rather than when compiled, and you can test for success or failure and react appropriately.</p>\n" }, { "answer_id": 261474, "author": "Hinrik", "author_id": 10689, "author_profile": "https://Stackoverflow.com/users/10689", "pm_score": 2, "selected": false, "text": "<p>And if you require a specific version of the module:</p>\n\n<pre><code>my $GOT_READKEY;\nBEGIN {\n eval {\n require Term::ReadKey;\n Term::ReadKey->import();\n $GOT_READKEY = 1 if $Term::ReadKey::VERSION >= 2.30;\n };\n}\n\n\n# elsewhere in the code\nif ($GOT_READKEY) {\n # ...\n}\n</code></pre>\n" }, { "answer_id": 823638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>if (eval {require Term::ReadKey;1;} ne 1) {\n# if module can't load\n} else {\nTerm::ReadKey-&gt;import();\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (eval {require Term::ReadKey;1;}) {\n#module loaded\nTerm::ReadKey-&gt;import();\n}\n</code></pre>\n\n<p>Note: the <code>1;</code> only executes if <code>require Term::...</code> loaded properly.</p>\n" }, { "answer_id": 26519509, "author": "Utkarsh Kumar", "author_id": 1566968, "author_profile": "https://Stackoverflow.com/users/1566968", "pm_score": -1, "selected": false, "text": "<p>I think it doesn't work when using variables. \nPlease check <a href=\"http://perldoc.perl.org/functions/require.html\" rel=\"nofollow\">this link</a> which explains how it can be used with variable</p>\n\n<pre><code>$class = 'Foo::Bar';\n require $class; # $class is not a bareword\n #or\n require \"Foo::Bar\"; # not a bareword because of the \"\"\n</code></pre>\n\n<p>The require function will look for the \"Foo::Bar\" file in the @INC array and will complain about not finding \"Foo::Bar\" there. In this case you can do:</p>\n\n<pre><code> eval \"require $class\";\n</code></pre>\n" }, { "answer_id": 64922599, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 0, "selected": false, "text": "<p>This is an effective idiom for loading an optional module (<a href=\"https://stackoverflow.com/q/65835906/124486\">so long as you're not using it in a code base with sigdie handler</a>),</p>\n<pre><code>use constant HAS_MODULE =&gt; defined eval { require Module };\n</code></pre>\n<p>This will require the module if available, and store the status in a constant.</p>\n<p>You can use this like,</p>\n<pre><code>use constant HAS_READLINE =&gt; defined eval { require Term::ReadKey };\n\nmy $width = 80;\nif ( HAS_READLINE ) {\n $width = # ... code, override default.\n}\n</code></pre>\n<p>Note, if you need to import it and bring in the symbols you can easily do that too. You can follow it up.</p>\n<pre><code>use constant HAS_READLINE =&gt; defined eval { require Term::ReadKey };\nTerm::ReadKey-&gt;import if HAS_READLINE;\n</code></pre>\n<p>This method uses constants. This has the advantage that if you don't have this module the dead code paths are purged from the optree.</p>\n" }, { "answer_id": 65610898, "author": "Elvin", "author_id": 13762488, "author_profile": "https://Stackoverflow.com/users/13762488", "pm_score": 2, "selected": false, "text": "<pre><code>use Module::Load::Conditional qw(check_install);\n\nuse if check_install(module =&gt; 'Clipboard') != undef, 'Clipboard'; # class methods: paste, copy\n</code></pre>\n<p>using <a href=\"https://perldoc.perl.org/if\" rel=\"nofollow noreferrer\">if</a> pragma and <a href=\"https://perldoc.perl.org/Module::Load::Conditional\" rel=\"nofollow noreferrer\">Module::Load::Conditional</a> core module.</p>\n<p><a href=\"https://perldoc.perl.org/Module::Load::Conditional#$href-=-check_install(-module-=%3E-NAME-%5B,-version-=%3E-VERSION,-verbose-=%3E-BOOL-%5D-);\" rel=\"nofollow noreferrer\">check_install</a> returns hashref or <code>undef</code>.</p>\n<hr />\n<p>this module is also mentioned in the <a href=\"https://perldoc.perl.org/if\" rel=\"nofollow noreferrer\">see also</a> section of the pragma's documentation:</p>\n<blockquote>\n<p>Module::Load::Conditional provides a number of functions you can use to query what modules are available, and then load one or more of them at runtime.</p>\n</blockquote>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
I have Perl code which relies on `Term::ReadKey` to get the terminal width. My installation is missing this module, so I want to provide a default if the module isn't present rather than throw an exception. How can I conditionally use an optional module, without knowing ahead of time whether it is available. ``` # but only if the module is installed and exists use Term::ReadKey; ... ``` How can I accomplish this?
Here's a bare-bones solution that does not require another module: ``` my $rc = eval { require Term::ReadKey; Term::ReadKey->import(); 1; }; if($rc) { # Term::ReadKey loaded and imported successfully ... } ``` Note that all the answers below (I hope they're below this one! :-) that use `eval { use SomeModule }` are wrong because `use` statements are evaluated at compile time, regardless of where in the code they appear. So if `SomeModule` is not available, the script will die immediately upon compiling. (A string eval of a `use` statement will also work (`eval 'use SomeModule';`), but there's no sense parsing and compiling new code at runtime when the `require`/`import` pair does the same thing, and is syntax-checked at compile time to boot.) Finally, note that my use of `eval { ... }` and `$@` here is succinct for the purpose of this example. In real code, you should use something like [Try::Tiny](http://search.cpan.org/dist/Try-Tiny/), or at least [be aware of the issues it addresses](http://search.cpan.org/dist/Try-Tiny/lib/Try/Tiny.pm#BACKGROUND).
251,705
<p>Here is my situation: I know almost nothing about Perl but it is the only language available on a porting machine. I only have permissions to write in my local work area and not the Perl install location. I need to use the <a href="http://search.cpan.org/dist/Parallel-ForkManager" rel="noreferrer">Parallel::ForkManager</a> Perl module from CPAN </p> <p>How do I use this Parallel::ForkManager without doing a central install? Is there an environment variable that I can set so it is located?</p> <p>Thanks</p> <p>JD</p>
[ { "answer_id": 251766, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 6, "selected": true, "text": "<p>From <a href=\"http://faq.perl.org/perlfaq8.html#How_do_I_keep_my_own\" rel=\"noreferrer\">perlfaq8: How do I keep my own module/library directory?</a>:</p>\n\n<p>When you build modules, tell Perl where to install the modules.</p>\n\n<p>For C-based distributions, use the INSTALL_BASE option\nwhen generating Makefiles:</p>\n\n<pre><code>perl Makefile.PL INSTALL_BASE=/mydir/perl\n</code></pre>\n\n<p>You can set this in your CPAN.pm configuration so modules automatically install\nin your private library directory when you use the CPAN.pm shell:</p>\n\n<pre><code>% cpan\ncpan&gt; o conf makepl_arg INSTALL_BASE=/mydir/perl\ncpan&gt; o conf commit\n</code></pre>\n\n<p>For C-based distributions, use the --install_base option:</p>\n\n<pre><code>perl Build.PL --install_base /mydir/perl\n</code></pre>\n\n<p>You can configure CPAN.pm to automatically use this option too:</p>\n\n<pre><code>% cpan\ncpan&gt; o conf mbuild_arg --install_base /mydir/perl\ncpan&gt; o conf commit\n</code></pre>\n\n<p>INSTALL_BASE tells these tools to put your modules into\nF. See L for details on how to run your newly\ninstalled moudles.</p>\n\n<p>There is one caveat with INSTALL_BASE, though, since it acts\ndifferently than the PREFIX and LIB settings that older versions of\nExtUtils::MakeMaker advocated. INSTALL_BASE does not support\ninstalling modules for multiple versions of Perl or different\narchitectures under the same directory. You should consider if you\nreally want that , and if you do, use the older PREFIX and LIB\nsettings. See the ExtUtils::Makemaker documentation for more details.</p>\n" }, { "answer_id": 251767, "author": "mikegrb", "author_id": 13462, "author_profile": "https://Stackoverflow.com/users/13462", "pm_score": 3, "selected": false, "text": "<p>Check out <a href=\"http://blog.plover.com/prog/lib.html\" rel=\"noreferrer\">this post</a> from Mark Dominus</p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n <ul>\n <li>Set PREFIX=X when building the Makefile</li>\n <li>Set INSTALLDIRS=vendor and VENDORPREFIX=X when building the Makefile\n \n <ul>\n <li>Or maybe instead of VENDORPREFIX you need to set INSTALLVENDORLIB or something</li>\n <li>Or maybe instead of setting them while building the Makefile you need to set them while running the make install target </li>\n </ul></li>\n <li>Set LIB=X/lib when building the Makefile</li>\n <li>Use PAR</li>\n <li>Use local::lib</li>\n </ul>\n</blockquote>\n\n<p>Mark also gives another solution in his blog which takes a bit more space to desribe but boils down to running make and make test but not make install and then using the stuff in blib/.</p>\n" }, { "answer_id": 251774, "author": "Alex", "author_id": 12204, "author_profile": "https://Stackoverflow.com/users/12204", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>-I</code> (capital i) command-line switch followed by the directory where you'll place the module; or try the \"use lib\" directive followed by the directory.</p>\n" }, { "answer_id": 251808, "author": "dexedrine", "author_id": 20266, "author_profile": "https://Stackoverflow.com/users/20266", "pm_score": 2, "selected": false, "text": "<pre><code>use lib 'directory';\nuse Parallel::ForkManager;\n</code></pre>\n" }, { "answer_id": 251820, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>There's the PERL5LIB environment variable, and <code>-I</code> on the command line when it comes to using the module. There are mechanisms for telling CPAN and CPANPLUS.</p>\n\n<p>There is information in question 5 of the CPAN manual (perldoc CPAN, or look at <a href=\"http://search.cpan.org/\" rel=\"nofollow noreferrer\">CPAN</a> itself).</p>\n" }, { "answer_id": 256690, "author": "Corion", "author_id": 21731, "author_profile": "https://Stackoverflow.com/users/21731", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://perlmonks.org/?node_id=693828\" rel=\"nofollow noreferrer\">Yes Even You Can Use CPAN</a></p>\n" }, { "answer_id": 3032152, "author": "Juan A. Navarro", "author_id": 359178, "author_profile": "https://Stackoverflow.com/users/359178", "pm_score": 0, "selected": false, "text": "<p>Consider using cpanminus, a suggested on <a href=\"https://stackoverflow.com/questions/2980297/how-to-use-cpan-as-a-non-root-user\">this other thread</a></p>\n" }, { "answer_id": 12144409, "author": "Viraj", "author_id": 1628007, "author_profile": "https://Stackoverflow.com/users/1628007", "pm_score": 2, "selected": false, "text": "<pre><code>perl Makefile.PL LIB=/my/perl_modules/lib/\nmake\nmake install\nPERL5LIB=$PERL5LIB:/my/perl_modules/lib/\nperl myperlcode.pl\n</code></pre>\n" }, { "answer_id": 21911478, "author": "ChathuraG", "author_id": 2437599, "author_profile": "https://Stackoverflow.com/users/2437599", "pm_score": 3, "selected": false, "text": "<p>Download package form CPAN to a folder:</p>\n\n<pre><code>wget http://search.cpan.org/CPAN/authors/id/S/SZ/SZABGAB/Parallel-ForkManager-1.06.tar.gz\ngunzip Parallel-ForkManager-1.06.tar.gz\ntar -xvf Parallel-ForkManager-1.06.tar\n</code></pre>\n\n<p>before this create a folder in home to store your local modules, now go into downloaded folder and run follwing cmmands:</p>\n\n<pre><code>perl Makefile.PL PREFIX=/home/username/myModules\nmake\nmake test\nmake install\n</code></pre>\n\n<p>get the path to ForkManager from the installed folder,/home/username/myModules\nand locate Parallel folder and get the full path to this.</p>\n\n<p>Now in your perl file put these at the beggining</p>\n\n<pre><code>use lib '/home/username/myModules/bin.../Parallel';\nuse parallel::ForkManager;\n</code></pre>\n\n<p>--That should do it.</p>\n" }, { "answer_id": 26688145, "author": "Ron Abraham", "author_id": 2742748, "author_profile": "https://Stackoverflow.com/users/2742748", "pm_score": 2, "selected": false, "text": "<p>use <code>cpanm -l $DIR_NAME</code> option.</p>\n" }, { "answer_id": 57907772, "author": "serv-inc", "author_id": 1587329, "author_profile": "https://Stackoverflow.com/users/1587329", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://perlbrew.pl\" rel=\"nofollow noreferrer\"><code>perlbrew</code></a> lets you use a local perl and installs it's packages to a local directory.</p>\n\n<pre><code>\\curl -L https://install.perlbrew.pl | bash\n\nperlbrew init # put this in .bash_profile etc\n\nperlbrew install 5.27.11\n\nperlbrew switch 5.27.11\n</code></pre>\n\n<p>See also <a href=\"https://opensource.com/article/18/7/perlbrew\" rel=\"nofollow noreferrer\">https://opensource.com/article/18/7/perlbrew</a>.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7743/" ]
Here is my situation: I know almost nothing about Perl but it is the only language available on a porting machine. I only have permissions to write in my local work area and not the Perl install location. I need to use the [Parallel::ForkManager](http://search.cpan.org/dist/Parallel-ForkManager) Perl module from CPAN How do I use this Parallel::ForkManager without doing a central install? Is there an environment variable that I can set so it is located? Thanks JD
From [perlfaq8: How do I keep my own module/library directory?](http://faq.perl.org/perlfaq8.html#How_do_I_keep_my_own): When you build modules, tell Perl where to install the modules. For C-based distributions, use the INSTALL\_BASE option when generating Makefiles: ``` perl Makefile.PL INSTALL_BASE=/mydir/perl ``` You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell: ``` % cpan cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl cpan> o conf commit ``` For C-based distributions, use the --install\_base option: ``` perl Build.PL --install_base /mydir/perl ``` You can configure CPAN.pm to automatically use this option too: ``` % cpan cpan> o conf mbuild_arg --install_base /mydir/perl cpan> o conf commit ``` INSTALL\_BASE tells these tools to put your modules into F. See L for details on how to run your newly installed moudles. There is one caveat with INSTALL\_BASE, though, since it acts differently than the PREFIX and LIB settings that older versions of ExtUtils::MakeMaker advocated. INSTALL\_BASE does not support installing modules for multiple versions of Perl or different architectures under the same directory. You should consider if you really want that , and if you do, use the older PREFIX and LIB settings. See the ExtUtils::Makemaker documentation for more details.
251,711
<p>I have a SQL database (SQL Server 2008) which contains the following design</p> <h2>ITEM</h2> <ul> <li>ID (Int, Identity)</li> <li>Name (NVarChar(50))</li> <li>Description (NVarChar(200))</li> </ul> <h2>META</h2> <ul> <li>ID (Int, Identity)</li> <li>Name (NVarChar(50))</li> </ul> <p>There exists a N-N relationship between these two, i.e an Item can contain zero or more meta references and a meta can be associated with more than one item. Each meta can only be assocated with the same item once. This means I have the classic table in the middle</p> <h2>ITEMMETA</h2> <ul> <li>ItemID (Int)</li> <li>MetaID (Int)</li> </ul> <p>I would like to to execute a LinqToSql query to extract all of the item entities which contains a specific set of meta links. For example, give me all the Items which have the following meta items associated with it</p> <ul> <li>Car</li> <li>Ford</li> <li>Offroad</li> </ul> <p>Is it possible to write such a query with the help of LinqToSql? Let me provide some more requirements</p> <ul> <li>I will have a list of Meta tags I want to use to filter the items which will be returned (for example in the example above I had Car, Ford and Offroad)</li> <li>An item can have MORE meta items associated with it than what I provide in the match, i.e if an item had Car, Ford, Offroad and Red assocated to it then providing any combination of them in the filter should result in a match</li> <li>However ALL of the meta names which are provided in the filter MUST be assocated with an item for it to be returned in the resultset. So sending in Car, Ford, Offroad and Red SHOULD NOT be a match for an item which has Car, Ford and Offroad (no Red) associated with itself</li> </ul> <p>I hope its clear what I'm trying to achieve, I feel Im not being quite as clear as I'd hoped =/ Let's hope its enough :)</p> <p>Thank you!</p>
[ { "answer_id": 252011, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 1, "selected": false, "text": "<p>this brings back anything that matchs any of the meta criteria, and then filters it down to only things that match all the criteria. (also, keep in mind that you'll need to have your relationship defined in your datacontext). Let us know if you need clarification.</p>\n\n<pre><code>var db = new YourDataContext();\nvar possibleItems = (from m in db.Metas where &lt;meta criteria&gt; select m.ItemMetas.Item);\n\nvar items = possibleItems.GroupBy(y=&gt;y).Where(x=&gt;x.Count() == criteriaCount).Select(x=&gt;x.Key);\n</code></pre>\n" }, { "answer_id": 252152, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>You could filter the items by counting the filtered metas.</p>\n\n<pre><code>List&lt;string&gt; metaList = new List&lt;string&gt;() { \"Car\", \"Ford\", \"Offroad\" };\nint metaListCount = metaList.Count;\nList&lt;Item&gt; result =\n db.Items\n .Where(i =&gt; metaListCount ==\n i.ItemMeta.Meta\n .Where(m =&gt; metaList.Contains(m.Name))\n .Count()\n )\n .ToList();\n</code></pre>\n\n<p>Be aware that there is an upper limit for this in-memory collection .Contains imposed by SqlServer's parameter limit (it's either ~200 or ~2000, I can never remember).</p>\n" }, { "answer_id": 252647, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": true, "text": "<p>This should work for you:</p>\n\n<pre><code>string[] criteria = new[] { \"Car\", \"Ford\", \"Offroad\" };\n\nvar items = \n from i in db.Item\n let wantedMetas = db.Meta.Where(m =&gt; criteria.Contains(m.Name))\n let metas = i.ItemMeta.Select(im =&gt; im.Meta)\n where wantedMetas.All(m =&gt; metas.Contains(m))\n select i;\n</code></pre>\n\n<p>Basically it compares the \"wanted\" metas against each item's metas, and selects the items which have all the wanted metas (or more).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25319/" ]
I have a SQL database (SQL Server 2008) which contains the following design ITEM ---- * ID (Int, Identity) * Name (NVarChar(50)) * Description (NVarChar(200)) META ---- * ID (Int, Identity) * Name (NVarChar(50)) There exists a N-N relationship between these two, i.e an Item can contain zero or more meta references and a meta can be associated with more than one item. Each meta can only be assocated with the same item once. This means I have the classic table in the middle ITEMMETA -------- * ItemID (Int) * MetaID (Int) I would like to to execute a LinqToSql query to extract all of the item entities which contains a specific set of meta links. For example, give me all the Items which have the following meta items associated with it * Car * Ford * Offroad Is it possible to write such a query with the help of LinqToSql? Let me provide some more requirements * I will have a list of Meta tags I want to use to filter the items which will be returned (for example in the example above I had Car, Ford and Offroad) * An item can have MORE meta items associated with it than what I provide in the match, i.e if an item had Car, Ford, Offroad and Red assocated to it then providing any combination of them in the filter should result in a match * However ALL of the meta names which are provided in the filter MUST be assocated with an item for it to be returned in the resultset. So sending in Car, Ford, Offroad and Red SHOULD NOT be a match for an item which has Car, Ford and Offroad (no Red) associated with itself I hope its clear what I'm trying to achieve, I feel Im not being quite as clear as I'd hoped =/ Let's hope its enough :) Thank you!
This should work for you: ``` string[] criteria = new[] { "Car", "Ford", "Offroad" }; var items = from i in db.Item let wantedMetas = db.Meta.Where(m => criteria.Contains(m.Name)) let metas = i.ItemMeta.Select(im => im.Meta) where wantedMetas.All(m => metas.Contains(m)) select i; ``` Basically it compares the "wanted" metas against each item's metas, and selects the items which have all the wanted metas (or more).
251,727
<p>I've set hibernate.generate_statistics=true and now need to register the mbeans so I can see the statistics in the jmx console. I can't seem to get anywhere and this doesn't seem like it should be such a difficult problem. Maybe I'm making things overcomplicated, but in any case so far I've tried:</p> <ul> <li>I copied EhCacheProvider and had it instantiate an extended version of CacheManager which overloaded init() and called ManagementService.registerMBeans(...) after initialization. The code all ran fine until the actual call to registerMBeans(...) which would cause the provider initialization to fail with a generic error (unfortunately I didn't write it down.) This approach was motivated by the methods used in <a href="http://www.kanonbra.com/index.php/projects/performance-testing/18-using-visualvm-on-liferay" rel="nofollow noreferrer">this liferay performance walkthrough.</a></li> <li>I created my own MBean with a start method that ran similar code to <a href="http://weblogs.java.net/blog/maxpoon/archive/2007/06/extending_the_n_2.html" rel="nofollow noreferrer">this example of registering ehcache's jmx mbeans</a>. Everything appeared to work correctly and my mbean shows up in the jmx console but nothing for net.sf.ehcache.</li> <li>I've since upgraded ehcache to 1.5 (we were using 1.3, not sure if that's specific to jboss 4.2.1 or just something we chose ourselves) and changed to using the SingletonEhCacheProvider and trying to just manually grab the statistics instead of dealing with the mbean registration. It hasn't really gone any better though; if I call getInstance() the CacheManager that's returned only has a copy of StandardQueryCache, but jboss logs show that many other caches have been initialized (one for each of the cached entities in our application.)</li> </ul> <p>EDIT: Well I have figured out one thing...connecting via JConsole does reveal the statistics mbeans. I guess ManagementFactory.getPlatformMBeanServer() doesn't give you the same mbean server as jboss is using. Anyway it looks like I'm encountering a similar problem as when I tried collecting the statistics manually, because I'm getting all zeros even after clicking through my app for a bit.</p>
[ { "answer_id": 251822, "author": "Matt S.", "author_id": 1458, "author_profile": "https://Stackoverflow.com/users/1458", "pm_score": 1, "selected": true, "text": "<p>Solved. Since I was not seeing all the caches for my entities I suspected I was not getting the right SessionFactory instance. I started out with this line (see the example jmx registration code in the link I provided in the question):</p>\n\n<pre><code>SessionFactory sf = (new Configuration()).configure().buildSessionFactory();\n</code></pre>\n\n<p>The end result was the cache manager I ultimately ended up with was a new instance and not the one from the persistence context. So I tried refactoring as:</p>\n\n<pre><code>EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"myPersistenceUnit\");\nreturn ((EntityManagerFactoryImpl)emf).getSessionFactory();\n</code></pre>\n\n<p>but that just threw an exception (I don't remember the exact text; something to the effect of \"can't initialize persistence context.\") So left with no other options, I added a stateless bean (UtilMgr) to my application and let persistence inject the correct SessionFactory. Here's that bean:</p>\n\n<pre><code>import javax.ejb.Stateless;\nimport javax.persistence.PersistenceUnit;\nimport net.sf.ehcache.CacheManager;\nimport org.hibernate.SessionFactory;\n\n@Stateless\npublic class UtilMgrBean implements UtilMgr {\n // NOTE: rename as necessary\n @PersistenceUnit(unitName = \"myPersistenceCtx\")\n private SessionFactory sessionFactory;\n\n public SessionFactory getSessionFactory() {\n return this.sessionFactory;\n }\n\n public CacheManager getCacheManager() {\n return CacheManager.getInstance(); // NOTE: assumes SingletonEhCacheProvider\n }\n}\n</code></pre>\n\n<p>and here's the corrected code from the previously mentioned walkthrough:</p>\n\n<pre><code>try {\n // NOTE: lookupBean is a utility method in our app we use for jndi lookups.\n // replace as necessary for your application.\n UtilMgr utilMgr = (UtilMgr)Manager.lookupBean(\"UtilMgrBean\", UtilMgr.class);\n SessionFactory sf = utilMgr.getSessionFactory();\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n\n // NOTE: replace myAppName as necessary\n ObjectName on = new ObjectName(\"Hibernate:type=statistics,application=myAppName\");\n\n // Enable Hibernate JMX Statistics\n StatisticsService statsMBean = new StatisticsService();\n statsMBean.setSessionFactory(sf);\n statsMBean.setStatisticsEnabled(true);\n mbs.registerMBean(statsMBean, on);\n\n CacheManager cacheMgr = utilMgr.getCacheManager();\n ManagementService.registerMBeans(cacheMgr, mbs, true, true, true, true);\n} catch(Throwable t) {\n throw new RuntimeException(t);\n}\n</code></pre>\n\n<p>You can also use this getCacheManager() method of UtilMgr if you want to retrieve statistics manually (which is what I'll probably do anyway.) You can find more info about how use use the Cache and Statistics objects <a href=\"http://ehcache.sourceforge.net/documentation/samples.html\" rel=\"nofollow noreferrer\">in the ehcache code samples.</a></p>\n\n<p>If anyone can fill me in on a way to statically lookup the session factory without the need for creating this extra session bean, I'd love to hear it.</p>\n" }, { "answer_id": 2591306, "author": "sans_sense", "author_id": 310818, "author_profile": "https://Stackoverflow.com/users/310818", "pm_score": 1, "selected": false, "text": "<p>The answer given above assumes that SingletonEhcacheProvider is being used and it also needs the utilmgr bean, this other solution uses a startup bean and does not make the singleton assumption</p>\n\n<pre><code>@Name(\"hibernateStatistics\")\n@Scope(ScopeType.APPLICATION)\n@Startup\npublic class HibernateUtils {\n@In\nprivate EntityManager entityManager;\n\n@Create\npublic void onStartup() {\n if (entityManager != null) {\n try {\n //lookup the jboss mbean server\n MBeanServer beanServer = org.jboss.mx.util.MBeanServerLocator.locateJBoss();\n StatisticsService mBean = new StatisticsService();\n ObjectName objectName = new ObjectName(\"Hibernate:type=statistics,application=&lt;application-name&gt;\");\n try{\n beanServer.unregisterMBean(objectName);\n }catch(Exception exc) {\n //no problems, as unregister is not important\n }\n SessionFactory sessionFactory = ((HibernateSessionProxy) entityManager.getDelegate()).getSessionFactory();\n mBean.setSessionFactory(sessionFactory);\n beanServer.registerMBean(mBean, objectName);\n\n if (sessionFactory instanceof SessionFactoryImplementor ){\n CacheProvider cacheProvider = ((SessionFactoryImplementor)sessionFactory).getSettings().getCacheProvider();\n if (cacheProvider instanceof EhCacheProvider) {\n try{\n Field field = EhCacheProvider.class.getDeclaredField(\"manager\");\n field.setAccessible(true);\n CacheManager cacheMgr = (CacheManager) field.get(cacheProvider);\n ManagementService.registerMBeans(cacheMgr, beanServer, true, true, true, true);\n }catch(Exception exc) {\n //do nothing\n exc.printStackTrace();\n }\n }\n }\n\n } catch (Exception e) {\n throw new RuntimeException(\"The persistence context \" + entityManager.toString() + \"is not properly configured.\", e);\n }\n }\n }\n</code></pre>\n\n<p>}</p>\n\n<p>We use MbeanServerLocator as jboss mbean would be the second mbean server in environments like linux.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458/" ]
I've set hibernate.generate\_statistics=true and now need to register the mbeans so I can see the statistics in the jmx console. I can't seem to get anywhere and this doesn't seem like it should be such a difficult problem. Maybe I'm making things overcomplicated, but in any case so far I've tried: * I copied EhCacheProvider and had it instantiate an extended version of CacheManager which overloaded init() and called ManagementService.registerMBeans(...) after initialization. The code all ran fine until the actual call to registerMBeans(...) which would cause the provider initialization to fail with a generic error (unfortunately I didn't write it down.) This approach was motivated by the methods used in [this liferay performance walkthrough.](http://www.kanonbra.com/index.php/projects/performance-testing/18-using-visualvm-on-liferay) * I created my own MBean with a start method that ran similar code to [this example of registering ehcache's jmx mbeans](http://weblogs.java.net/blog/maxpoon/archive/2007/06/extending_the_n_2.html). Everything appeared to work correctly and my mbean shows up in the jmx console but nothing for net.sf.ehcache. * I've since upgraded ehcache to 1.5 (we were using 1.3, not sure if that's specific to jboss 4.2.1 or just something we chose ourselves) and changed to using the SingletonEhCacheProvider and trying to just manually grab the statistics instead of dealing with the mbean registration. It hasn't really gone any better though; if I call getInstance() the CacheManager that's returned only has a copy of StandardQueryCache, but jboss logs show that many other caches have been initialized (one for each of the cached entities in our application.) EDIT: Well I have figured out one thing...connecting via JConsole does reveal the statistics mbeans. I guess ManagementFactory.getPlatformMBeanServer() doesn't give you the same mbean server as jboss is using. Anyway it looks like I'm encountering a similar problem as when I tried collecting the statistics manually, because I'm getting all zeros even after clicking through my app for a bit.
Solved. Since I was not seeing all the caches for my entities I suspected I was not getting the right SessionFactory instance. I started out with this line (see the example jmx registration code in the link I provided in the question): ``` SessionFactory sf = (new Configuration()).configure().buildSessionFactory(); ``` The end result was the cache manager I ultimately ended up with was a new instance and not the one from the persistence context. So I tried refactoring as: ``` EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit"); return ((EntityManagerFactoryImpl)emf).getSessionFactory(); ``` but that just threw an exception (I don't remember the exact text; something to the effect of "can't initialize persistence context.") So left with no other options, I added a stateless bean (UtilMgr) to my application and let persistence inject the correct SessionFactory. Here's that bean: ``` import javax.ejb.Stateless; import javax.persistence.PersistenceUnit; import net.sf.ehcache.CacheManager; import org.hibernate.SessionFactory; @Stateless public class UtilMgrBean implements UtilMgr { // NOTE: rename as necessary @PersistenceUnit(unitName = "myPersistenceCtx") private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return this.sessionFactory; } public CacheManager getCacheManager() { return CacheManager.getInstance(); // NOTE: assumes SingletonEhCacheProvider } } ``` and here's the corrected code from the previously mentioned walkthrough: ``` try { // NOTE: lookupBean is a utility method in our app we use for jndi lookups. // replace as necessary for your application. UtilMgr utilMgr = (UtilMgr)Manager.lookupBean("UtilMgrBean", UtilMgr.class); SessionFactory sf = utilMgr.getSessionFactory(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // NOTE: replace myAppName as necessary ObjectName on = new ObjectName("Hibernate:type=statistics,application=myAppName"); // Enable Hibernate JMX Statistics StatisticsService statsMBean = new StatisticsService(); statsMBean.setSessionFactory(sf); statsMBean.setStatisticsEnabled(true); mbs.registerMBean(statsMBean, on); CacheManager cacheMgr = utilMgr.getCacheManager(); ManagementService.registerMBeans(cacheMgr, mbs, true, true, true, true); } catch(Throwable t) { throw new RuntimeException(t); } ``` You can also use this getCacheManager() method of UtilMgr if you want to retrieve statistics manually (which is what I'll probably do anyway.) You can find more info about how use use the Cache and Statistics objects [in the ehcache code samples.](http://ehcache.sourceforge.net/documentation/samples.html) If anyone can fill me in on a way to statically lookup the session factory without the need for creating this extra session bean, I'd love to hear it.
251,730
<p>We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation.</p> <p>Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build.</p> <p>Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.</p>
[ { "answer_id": 251760, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 5, "selected": true, "text": "<p>Normally you would add a profile to your maven configuration that runs a different set of tests:</p>\n\n<p>run this with mvn -Pintegrationtest install</p>\n\n<pre><code> &lt;profile&gt;\n &lt;id&gt;integrationtest&lt;/id&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n &lt;configuration&gt;\n &lt;argLine&gt;-client -Xmx896m -XX:MaxPermSize=192m&lt;/argLine&gt;\n &lt;forkMode&gt;once&lt;/forkMode&gt;\n &lt;includes&gt;\n &lt;include&gt;**/**/*Test.java&lt;/include&gt;\n &lt;include&gt;**/**/*IntTest.java&lt;/include&gt;\n &lt;/includes&gt;\n &lt;excludes&gt;\n &lt;exclude&gt;**/**/*SeleniumTest.java&lt;/exclude&gt;\n &lt;/excludes&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n &lt;activation&gt;\n &lt;property&gt;\n &lt;name&gt;integrationtest&lt;/name&gt;\n &lt;/property&gt;\n &lt;/activation&gt;\n &lt;/profile&gt;\n</code></pre>\n" }, { "answer_id": 549838, "author": "Matthew McCullough", "author_id": 56039, "author_profile": "https://Stackoverflow.com/users/56039", "pm_score": 1, "selected": false, "text": "<p>Use an integration test plugin such as the <a href=\"http://mojo.codehaus.org/shitty-maven-plugin/\" rel=\"nofollow noreferrer\">Super Helpful Integration Test Thingy</a> to separate Integration Tests (long running, systemic) from Unit Test (purists say 30 seconds max for all true unit tests to run). Make two Java packages for your unit tests versus integration tests.</p>\n\n<p>Then do not bind this plugin to a phase (the normal maven lifecycle) and only run it when it is explicitly called as a target, like so:\n<code>mvn shitty:clean shitty:install shitty:test</code> </p>\n\n<pre><code>&lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;\n &lt;artifactId&gt;shitty-maven-plugin&lt;/artifactId&gt;\n &lt;/plugin&gt;\n&lt;/plugins&gt;\n</code></pre>\n\n<p>This way, your normal developers will not be impacted, and you'll be able to run integration tests on demand.</p>\n" }, { "answer_id": 550476, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 0, "selected": false, "text": "<p>Another option is to have the stress test detect it is running in maven and run only once or twice. i.e. turn into a regular functional test. This way you can check the code is still good, but not run for a long time.</p>\n" }, { "answer_id": 7325398, "author": "Joel Westberg", "author_id": 840333, "author_profile": "https://Stackoverflow.com/users/840333", "pm_score": 2, "selected": false, "text": "<p>Adding to <strong>krosenvold</strong>'s answer, to ensure no unexpected behavior, make sure you also have a default profile that is active by default that <em>excludes</em> the integration or stresstests you want to run in your special profile. </p>\n\n<pre><code>&lt;profile&gt;\n &lt;id&gt;normal&lt;/id&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n &lt;configuration&gt;\n &lt;excludes&gt;\n &lt;exclude&gt;**/**/*IntTest.java&lt;/exclude&gt;\n &lt;/excludes&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n &lt;activation&gt;\n &lt;activeByDefault&gt;true&lt;/activeByDefault&gt;\n &lt;/activation&gt;\n&lt;/profile&gt;\n</code></pre>\n\n<p>You will need to create a profile like this, simply listing the surefire-plugin outside of a profile will override the profile should it be selected with:</p>\n\n<pre><code>mvn -P integrationtest clean install\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32514/" ]
We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation. Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build. Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.
Normally you would add a profile to your maven configuration that runs a different set of tests: run this with mvn -Pintegrationtest install ``` <profile> <id>integrationtest</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>-client -Xmx896m -XX:MaxPermSize=192m</argLine> <forkMode>once</forkMode> <includes> <include>**/**/*Test.java</include> <include>**/**/*IntTest.java</include> </includes> <excludes> <exclude>**/**/*SeleniumTest.java</exclude> </excludes> </configuration> </plugin> </plugins> </build> <activation> <property> <name>integrationtest</name> </property> </activation> </profile> ```
251,740
<p>This code was working properly before, basically I have a master page that has a single text box for searching, I named it <strong><code>searchBox</code></strong>. I have a method to pull the content of <strong><code>searchBox</code></strong> on form submit and set it to a variable <strong><code>userQuery</code></strong>. Here is the method:</p> <pre><code>Public Function searchString(ByVal oTextBoxName As String) As String If Master IsNot Nothing Then Dim txtBoxSrc As New TextBox txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox) If txtBoxSrc IsNot Nothing Then Return txtBoxSrc.Text End If End If Return Nothing End Function </code></pre> <p>The results are displayed on <strong><code>search.aspx</code></strong>. Now, however, if <strong><code>searchBox</code></strong> is filled and submitted on a page other than <strong><code>search.aspx</code></strong>, the contents of the text box are not passed through. The form is very simple, just:</p> <p><code>&lt;asp:TextBox ID="searchBox" runat="server"&gt;&lt;/asp:TextBox&gt;<br> &lt;asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" /&gt;</code>.</p>
[ { "answer_id": 251761, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": true, "text": "<p>Simply remove the permission to delete things from those unable to get it right. You can give very fine-grained permissions in AD.</p>\n\n<p>There is no \"readonly\" attribute. That's what the <a href=\"http://en.wikipedia.org/wiki/Access_control_list\" rel=\"nofollow noreferrer\">ACLs</a> are for.</p>\n" }, { "answer_id": 251768, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "<p>You could deny the Delete privalge from Administrators through Delegation at the root level and then you would need to be an enterprise admin to perform deletions. Ensure that no admins are in the Enterprise Admins group for day-to-day usage.</p>\n" }, { "answer_id": 6282635, "author": "uSlackr", "author_id": 172918, "author_profile": "https://Stackoverflow.com/users/172918", "pm_score": 2, "selected": false, "text": "<p>There is a feature in AD for Win2k3 and higher to mark an object to prevent accidental deletion. This check box on the object actually changes the underlying permissions for you to remove delete permissions. Therefore it is not tool specific and must be respected by other tools (like powershell and vbscript).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
This code was working properly before, basically I have a master page that has a single text box for searching, I named it **`searchBox`**. I have a method to pull the content of **`searchBox`** on form submit and set it to a variable **`userQuery`**. Here is the method: ``` Public Function searchString(ByVal oTextBoxName As String) As String If Master IsNot Nothing Then Dim txtBoxSrc As New TextBox txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox) If txtBoxSrc IsNot Nothing Then Return txtBoxSrc.Text End If End If Return Nothing End Function ``` The results are displayed on **`search.aspx`**. Now, however, if **`searchBox`** is filled and submitted on a page other than **`search.aspx`**, the contents of the text box are not passed through. The form is very simple, just: `<asp:TextBox ID="searchBox" runat="server"></asp:TextBox> <asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" />`.
Simply remove the permission to delete things from those unable to get it right. You can give very fine-grained permissions in AD. There is no "readonly" attribute. That's what the [ACLs](http://en.wikipedia.org/wiki/Access_control_list) are for.
251,746
<p>I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.</p> <pre><code>import scalax.data._ import scalax.io.CommandLineParser class TestCLI(arguments: Array[String]) extends CommandLineParser { private val opt1Option = new Flag("p", "print") with AllowAll private val opt2Option = new Flag("o", "out") with AllowAll private val strOption = new StringOption("v", "value") with AllowAll private val result = parse(arguments) // true or false val opt1 = result(opt1Option) val opt2 = result(opt2Option) val str = result(strOption) } </code></pre>
[ { "answer_id": 252007, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>I'm not personally familiar with Scalax or <code>Bistate</code> in particular, but just looking at the scaladocs, it looks like a left-right disjunction. Scala's main library has a monad very much like this (<code>Either</code>), so I'm surprised that they didn't just use the standard one.</p>\n\n<p>In essence, <code>Bistate</code> and <code>Either</code> are a bit like <code>Option</code>, except their \"<code>None</code>-equivalent\" can contain a value. For example, if I were writing code using <code>Either</code>, I might do something like this:</p>\n\n<pre><code>def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right(\"Divide by zero\")\n\ndiv(4, 2) match {\n case Left(x) =&gt; println(\"Result: \" + x)\n case Right(e) =&gt; Println(\"Error: \" + e)\n}\n</code></pre>\n\n<p>This would print \"<code>Result: 2</code>\". In this case, we're using <code>Either</code> to simulate an exception. We return an instance of <code>Left</code> which contains the value we want, unless that value cannot be computed for some reason, in which case we return an error message wrapped up inside an instance of <code>Right</code>.</p>\n" }, { "answer_id": 256638, "author": "JtR", "author_id": 30958, "author_profile": "https://Stackoverflow.com/users/30958", "pm_score": 0, "selected": false, "text": "<p>So if I want to assign to variable boolean value of whether flag is found I have to do like below?</p>\n\n<pre><code>val opt1 = result(opt1Option) match {\n case Positive(_) =&gt; true\n case Negative(_) =&gt; false\n}\n</code></pre>\n\n<p>Isn't there a way to write this common case with less code than that?</p>\n" }, { "answer_id": 260444, "author": "Germán", "author_id": 17138, "author_profile": "https://Stackoverflow.com/users/17138", "pm_score": 3, "selected": true, "text": "<p>Here are shorter alternatives to that pattern matching to get a boolean:</p>\n\n<pre><code>val opt1 = result(opt1Option).isInstanceOf[Positive[_]]\nval opt2 = result(opt2Option).posValue.isDefined\n</code></pre>\n\n<p>The second one is probably better. The field <strong>posValue</strong> is an Option (there's <strong>negValue</strong> as well). The method <strong>isDefined</strong> from Option tells you whether it is a Some(x) or None.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30958/" ]
I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works. ``` import scalax.data._ import scalax.io.CommandLineParser class TestCLI(arguments: Array[String]) extends CommandLineParser { private val opt1Option = new Flag("p", "print") with AllowAll private val opt2Option = new Flag("o", "out") with AllowAll private val strOption = new StringOption("v", "value") with AllowAll private val result = parse(arguments) // true or false val opt1 = result(opt1Option) val opt2 = result(opt2Option) val str = result(strOption) } ```
Here are shorter alternatives to that pattern matching to get a boolean: ``` val opt1 = result(opt1Option).isInstanceOf[Positive[_]] val opt2 = result(opt2Option).posValue.isDefined ``` The second one is probably better. The field **posValue** is an Option (there's **negValue** as well). The method **isDefined** from Option tells you whether it is a Some(x) or None.
251,753
<p>Using VB.net (.net 2.0) I have a string in this format:</p> <pre><code>record1_field1,record1_field2,record2_field3,record2_field1,record2_field2, </code></pre> <p>etc...</p> <p>I wonder what the best (easiest) way is to get this into an xml?</p> <p>I can think of 2 ways:</p> <p>Method 1: - use split to get the items in an array - loop through array and build an xml string using concatenation</p> <p>Method 2: - use split to get the items in an array - loops through array to build a datatable - use writexml to output xml from the datatable</p> <p>The first sounds pretty simple but would require more logic to build the string.</p> <p>The second seems slicker and easier to understand.</p> <p>Are there other ways to do this?</p>
[ { "answer_id": 251763, "author": "JGW", "author_id": 26288, "author_profile": "https://Stackoverflow.com/users/26288", "pm_score": 1, "selected": false, "text": "<p>Instead of doing string concatenation, you could probably create an XmlDocument and stuff it with the appropriate XmlElement and XmlAttribute objects from your string... Then, write out the XmlDocument object...</p>\n" }, { "answer_id": 251770, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 3, "selected": true, "text": "<p>I would do something like this:</p>\n\n<pre>\n<code>\nXmlDocument doc = new XmlDocuent();\n\nstring[] data = csv.split(',');\n\nXmlNode = doc.CreateElement(\"root\");\nforeach(string str in data)\n{\n XmlNode node = doc.CreateElement(\"data\");\n node.innerText = str;\n root.AppendChild(node);\n}\nConsole.WriteLine(doc.InnerXML);\n</code>\n</pre>\n\n<p>Should return something like this:</p>\n\n<pre>\n<code>\n&lt;root>\n &lt;data>field 1&lt;/data>\n &lt;data>field 2&lt;/data>\n &lt;data>field 3&lt;/data>\n&lt/root>\n</code>\n</pre>\n\n<p>You would have to nest loops / tokenize a bit differently for nested data...</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32892/" ]
Using VB.net (.net 2.0) I have a string in this format: ``` record1_field1,record1_field2,record2_field3,record2_field1,record2_field2, ``` etc... I wonder what the best (easiest) way is to get this into an xml? I can think of 2 ways: Method 1: - use split to get the items in an array - loop through array and build an xml string using concatenation Method 2: - use split to get the items in an array - loops through array to build a datatable - use writexml to output xml from the datatable The first sounds pretty simple but would require more logic to build the string. The second seems slicker and easier to understand. Are there other ways to do this?
I would do something like this: ``` XmlDocument doc = new XmlDocuent(); string[] data = csv.split(','); XmlNode = doc.CreateElement("root"); foreach(string str in data) { XmlNode node = doc.CreateElement("data"); node.innerText = str; root.AppendChild(node); } Console.WriteLine(doc.InnerXML); ``` Should return something like this: ``` <root> <data>field 1</data> <data>field 2</data> <data>field 3</data> </root> ``` You would have to nest loops / tokenize a bit differently for nested data...
251,759
<p>I'm writing an application that uses renaming rules to rename a list of files based on information given by the user. The files may be inconsistently named to begin with, or the filenames may be consistent. The user selects a list of files, and inputs information about the files (for MP3s, they would be Artist, Title, Album, etc). Using a rename rule (example below), the program uses the user-inputted information to rename the files accordingly.</p> <p>However, if all or some the files are named consistently, I would like to allow the program to 'guess' the file information. That is the problem I'm having. What is the best way to do this?</p> <p>Sample filenames:</p> <pre><code>Kraftwerk-Kraftwerk-01-RuckZuck.mp3 Kraftwerk-Autobahn-01-Autobahn.mp3 Kraftwerk-Computer World-03-Numbers.mp3 </code></pre> <p>Rename Rule:</p> <pre><code>%Artist%-%Album%-%Track%-%Title%.mp3 </code></pre> <p>The program should properly deduce the Artist, Track number, Title, and Album name.</p> <p>Again, what's the best way to do this? I was thinking regular expressions, but I'm a bit confused.</p>
[ { "answer_id": 251779, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 1, "selected": false, "text": "<p>Not the answer to the question you asked, but an <a href=\"http://en.wikipedia.org/wiki/ID3\" rel=\"nofollow noreferrer\">ID3 tag</a> reading library might be a better way to do this when you are using MP3s. A quick Google came up with: <a href=\"http://sourceforge.net/projects/csid3lib\" rel=\"nofollow noreferrer\">C# ID3 Library</a>.</p>\n\n<p>As for guessing which string positions hold the artist, album, and song title... the first thing I can think of is that if you have a good selection to work with, say several albums, you could first see which position repeats the most, which would be the artist, which repeats the second most (album) and which repeats the least (song title). </p>\n\n<p>Otherwise, it seems like a difficult guess to make based solely on a few strings in the file name... could you ask the user to also input a matching expression for the file name that describes the order of the fields?</p>\n" }, { "answer_id": 251874, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 0, "selected": false, "text": "<p>The filenames in your example seem pretty consistent to me. \nYou can simply do string.Split() and add each element of the resulting array to its according tag information.</p>\n\n<p>Guessing at which position is which tag information would involve TONS of heuristics.</p>\n\n<p>Btw. folders that contain song files usually have some pattern in their name as well, f.e.</p>\n\n<p>1998 - Seven</p>\n\n<p>1999 - Periscope</p>\n\n<p>2000 - CO2</p>\n\n<p>The format here is %Year% - %AlbumName%, that might help you to identify which element in the filename is the album.</p>\n" }, { "answer_id": 251894, "author": "Mike Christiansen", "author_id": 29249, "author_profile": "https://Stackoverflow.com/users/29249", "pm_score": 0, "selected": false, "text": "<p>To clarify, I <strong>DO</strong> have a pattern to match the filenames against.</p>\n\n<p>I don't know the filename or pattern ahead of time, it is all run-time.</p>\n\n<p>Pattern:</p>\n\n<pre>%Artist%-%Album%-%Track%-%Title%.mp3</pre>\n\n<p>Filenames:</p>\n\n<pre>Kraftwerk-Kraftwerk-01-RuckZuck.mp3\nKraftwerk-Autobahn-01-Autobahn.mp3\nKraftwerk-Computer World-03-Numbers.mp3</pre>\n\n<p>Expected Result:</p>\n\n<pre>\nArtist Album Track Title\nKraftwerk Kraftwerk 01 RuckZuck\nKraftwerk Autobahn 01 Autobahn\nKraftwerk Computer World 01 Numbers\n</pre>\n\n<p>Again, the format, and filenames are not always the same.</p>\n" }, { "answer_id": 251897, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "<p>Easiest would be to replace each <code>%Label%</code> with <code>(?&lt;Label&gt;.*?)</code>, and escape any other characters.</p>\n\n<pre><code>%Artist%-%Album%-%Track%-%Title%.mp3\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(?&lt;Artist&gt;.*?)-(?&lt;Album&gt;.*?)-(?&lt;Track&gt;.*?)-(?&lt;Title&gt;.*?)\\.mp3\n</code></pre>\n\n<p>You would then get each component into named capture groups.</p>\n\n<pre><code>Dictinary&lt;string,string&gt; match_filename(string rule, string filename) {\n Regex tag_re = new Regex(@'%(\\w+)%');\n string pattern = tag_re.Replace(Regex.escape(rule), @'(?&lt;$1&gt;.*?)');\n Regex filename_re = new Regex(pattern);\n Match match = filename_re.Match(filename);\n\n Dictionary&lt;string,string&gt; tokens =\n new Dictionary&lt;string,string&gt;();\n for (int counter = 1; counter &lt; match.Groups.Count; counter++)\n {\n string group_name = filename_re.GroupNameFromNumber(counter);\n tokens.Add(group_name, m.Groups[counter].Value);\n }\n return tokens;\n}\n</code></pre>\n\n<p>But if the user leaves out the delimiters, or if the delimiters could be contained within the fields, you could get some strange results. The pattern would for <code>%Artist%%Album%</code> would become <code>(?&lt;Artist&gt;.*?)(?&lt;Album&gt;.*?)</code> which is equivalent to <code>.*?.*?</code>. The pattern wouldn't know where to split.</p>\n\n<p>This could be solved if you know the format of certain fields, such as the track-number. If you translate <code>%Track%</code> to <code>(?&lt;Track&gt;\\d+)</code> instead, the pattern would know that any digits in the filename must be the <code>Track</code>.</p>\n" }, { "answer_id": 256740, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 0, "selected": false, "text": "<p>I have written a command-line file renamer --- <a href=\"http://renamewand.sourceforge.net/\" rel=\"nofollow noreferrer\">RenameWand</a> --- that does the kind of pattern matching you are describing. It's in Java though, but I think some of the source code and usage documentation may be of interest to you. A simple example of what the program can do:</p>\n\n<p>Source Pattern (user-specified):</p>\n\n<pre><code>&lt;artist&gt;-&lt;album&gt;-&lt;track&gt;-&lt;title&gt;.mp3\n</code></pre>\n\n<p>Target Pattern (user-specified):</p>\n\n<pre><code>&lt;title.upper&gt;-&lt;3|track+10&gt;-&lt;album.lower&gt;-&lt;artist&gt;.mp3\n</code></pre>\n\n<p>Original Filename:</p>\n\n<pre><code>Kraftwerk-Computer World-03-Numbers.mp3\n</code></pre>\n\n<p>Renamed Filename:</p>\n\n<pre><code>NUMBERS-013-computer world-Kraftwerk.mp3\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29249/" ]
I'm writing an application that uses renaming rules to rename a list of files based on information given by the user. The files may be inconsistently named to begin with, or the filenames may be consistent. The user selects a list of files, and inputs information about the files (for MP3s, they would be Artist, Title, Album, etc). Using a rename rule (example below), the program uses the user-inputted information to rename the files accordingly. However, if all or some the files are named consistently, I would like to allow the program to 'guess' the file information. That is the problem I'm having. What is the best way to do this? Sample filenames: ``` Kraftwerk-Kraftwerk-01-RuckZuck.mp3 Kraftwerk-Autobahn-01-Autobahn.mp3 Kraftwerk-Computer World-03-Numbers.mp3 ``` Rename Rule: ``` %Artist%-%Album%-%Track%-%Title%.mp3 ``` The program should properly deduce the Artist, Track number, Title, and Album name. Again, what's the best way to do this? I was thinking regular expressions, but I'm a bit confused.
Easiest would be to replace each `%Label%` with `(?<Label>.*?)`, and escape any other characters. ``` %Artist%-%Album%-%Track%-%Title%.mp3 ``` becomes ``` (?<Artist>.*?)-(?<Album>.*?)-(?<Track>.*?)-(?<Title>.*?)\.mp3 ``` You would then get each component into named capture groups. ``` Dictinary<string,string> match_filename(string rule, string filename) { Regex tag_re = new Regex(@'%(\w+)%'); string pattern = tag_re.Replace(Regex.escape(rule), @'(?<$1>.*?)'); Regex filename_re = new Regex(pattern); Match match = filename_re.Match(filename); Dictionary<string,string> tokens = new Dictionary<string,string>(); for (int counter = 1; counter < match.Groups.Count; counter++) { string group_name = filename_re.GroupNameFromNumber(counter); tokens.Add(group_name, m.Groups[counter].Value); } return tokens; } ``` But if the user leaves out the delimiters, or if the delimiters could be contained within the fields, you could get some strange results. The pattern would for `%Artist%%Album%` would become `(?<Artist>.*?)(?<Album>.*?)` which is equivalent to `.*?.*?`. The pattern wouldn't know where to split. This could be solved if you know the format of certain fields, such as the track-number. If you translate `%Track%` to `(?<Track>\d+)` instead, the pattern would know that any digits in the filename must be the `Track`.
251,781
<p>I believe there's a way to find the kth largest element in an unsorted array of length n in O(n). Or perhaps it's "expected" O(n) or something. How can we do this?</p>
[ { "answer_id": 251793, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 1, "selected": false, "text": "<p>iterate through the list. if the current value is larger than the stored largest value, store it as the largest value and bump the 1-4 down and 5 drops off the list. If not,compare it to number 2 and do the same thing. Repeat, checking it against all 5 stored values. this should do it in O(n)</p>\n" }, { "answer_id": 251797, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 4, "selected": false, "text": "<p>A quick Google on that ('kth largest element array') returned this: <a href=\"http://discuss.joelonsoftware.com/default.asp?interview.11.509587.17\" rel=\"nofollow noreferrer\">http://discuss.joelonsoftware.com/default.asp?interview.11.509587.17</a></p>\n\n<pre><code>\"Make one pass through tracking the three largest values so far.\" \n</code></pre>\n\n<p>(it was specifically for 3d largest)</p>\n\n<p>and this answer:</p>\n\n<pre><code>Build a heap/priority queue. O(n)\nPop top element. O(log n)\nPop top element. O(log n)\nPop top element. O(log n)\n\nTotal = O(n) + 3 O(log n) = O(n)\n</code></pre>\n" }, { "answer_id": 251813, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://books.google.com/books?id=E6BNGFQ6m_IC&amp;pg=RA2-PA68&amp;lpg=RA2-PA68&amp;dq=kth+largest+element+algorithm&amp;source=web&amp;ots=I_hwqNJre_&amp;sig=aFEdhfpQrfDc0osCC69YyR_HCHc&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result#PRA2-PA70,M1\" rel=\"noreferrer\">A Programmer's Companion to Algorithm Analysis</a> gives a version that <em>is</em> O(n), although the author states that the constant factor is so high, you'd probably prefer the naive sort-the-list-then-select method.</p>\n\n<p>I answered the letter of your question :)</p>\n" }, { "answer_id": 251815, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>You can do it in O(n + kn) = O(n) (for constant k) for time and O(k) for space, by keeping track of the k largest elements you've seen. </p>\n\n<p>For each element in the array you can scan the list of k largest and replace the smallest element with the new one if it is bigger.</p>\n\n<p>Warren's priority heap solution is neater though.</p>\n" }, { "answer_id": 251818, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": -1, "selected": false, "text": "<p>What I would do is this:</p>\n\n<pre><code>initialize empty doubly linked list l\nfor each element e in array\n if e larger than head(l)\n make e the new head of l\n if size(l) &gt; k\n remove last element from l\n\nthe last element of l should now be the kth largest element\n</code></pre>\n\n<p>You can simply store pointers to the first and last element in the linked list. They only change when updates to the list are made.</p>\n\n<p>Update:</p>\n\n<pre><code>initialize empty sorted tree l\nfor each element e in array\n if e between head(l) and tail(l)\n insert e into l // O(log k)\n if size(l) &gt; k\n remove last element from l\n\nthe last element of l should now be the kth largest element\n</code></pre>\n" }, { "answer_id": 251884, "author": "eladv", "author_id": 7314, "author_profile": "https://Stackoverflow.com/users/7314", "pm_score": 8, "selected": true, "text": "<p>This is called finding the <strong>k-th order statistic</strong>. There's a very simple randomized algorithm (called <em>quickselect</em>) taking <code>O(n)</code> average time, <code>O(n^2)</code> worst case time, and a pretty complicated non-randomized algorithm (called <em>introselect</em>) taking <code>O(n)</code> worst case time. There's some info on <a href=\"http://en.wikipedia.org/wiki/Selection_algorithm\" rel=\"noreferrer\">Wikipedia</a>, but it's not very good.</p>\n\n<p><strike>Everything you need is in <a href=\"http://web.archive.org/web/20160402214842/http://c3p0demo.googlecode.com/svn/trunk/scalaDemo/script/Order_statistics.ppt\" rel=\"noreferrer\">these powerpoint slides</a></strike>. Just to extract the basic algorithm of the <code>O(n)</code> worst-case algorithm (introselect):</p>\n\n<pre><code>Select(A,n,i):\n Divide input into ⌈n/5⌉ groups of size 5.\n\n /* Partition on median-of-medians */\n medians = array of each group’s median.\n pivot = Select(medians, ⌈n/5⌉, ⌈n/10⌉)\n Left Array L and Right Array G = partition(A, pivot)\n\n /* Find ith element in L, pivot, or G */\n k = |L| + 1\n If i = k, return pivot\n If i &lt; k, return Select(L, k-1, i)\n If i &gt; k, return Select(G, n-k, i-k)\n</code></pre>\n\n<p>It's also very nicely detailed in the Introduction to Algorithms book by Cormen et al.</p>\n" }, { "answer_id": 252047, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>The C++ standard library has almost exactly that <a href=\"http://www.cplusplus.com/reference/algorithm/nth_element.html\" rel=\"nofollow noreferrer\">function</a> call <code>nth_element</code>, although it does modify your data. It has expected linear run-time, O(N), and it also does a partial sort.</p>\n\n<pre><code>const int N = ...;\ndouble a[N];\n// ... \nconst int m = ...; // m &lt; N\nnth_element (a, a + m, a + N);\n// a[m] contains the mth element in a\n</code></pre>\n" }, { "answer_id": 255128, "author": "Ying Xiao", "author_id": 30202, "author_profile": "https://Stackoverflow.com/users/30202", "pm_score": 7, "selected": false, "text": "<p>If you want a true <code>O(n)</code> algorithm, as opposed to <code>O(kn)</code> or something like that, then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in). My prof has a great writeup, with the runtime analysis: (<a href=\"http://pine.cs.yale.edu/pinewiki/QuickSelect\" rel=\"noreferrer\">reference</a>)</p>\n\n<p>The QuickSelect algorithm quickly finds the k-th smallest element of an unsorted array of <code>n</code> elements. It is a <a href=\"http://pine.cs.yale.edu/pinewiki/RandomizedAlgorithm\" rel=\"noreferrer\">RandomizedAlgorithm</a>, so we compute the worst-case <em>expected</em> running time.</p>\n\n<p>Here is the algorithm.</p>\n\n<pre><code>QuickSelect(A, k)\n let r be chosen uniformly at random in the range 1 to length(A)\n let pivot = A[r]\n let A1, A2 be new arrays\n # split into a pile A1 of small elements and A2 of big elements\n for i = 1 to n\n if A[i] &lt; pivot then\n append A[i] to A1\n else if A[i] &gt; pivot then\n append A[i] to A2\n else\n # do nothing\n end for\n if k &lt;= length(A1):\n # it's in the pile of small elements\n return QuickSelect(A1, k)\n else if k &gt; length(A) - length(A2)\n # it's in the pile of big elements\n return QuickSelect(A2, k - (length(A) - length(A2))\n else\n # it's equal to the pivot\n return pivot\n</code></pre>\n\n<p>What is the running time of this algorithm? If the adversary flips coins for us, we may find that the pivot is always the largest element and <code>k</code> is always 1, giving a running time of </p>\n\n<pre><code>T(n) = Theta(n) + T(n-1) = Theta(n<sup>2</sup>)</code></pre>\n\n<p>But if the choices are indeed random, the expected running time is given by</p>\n\n<pre><code>T(n) &lt;= Theta(n) + (1/n) ∑<sub>i=1 to n</sub>T(max(i, n-i-1))</code></pre>\n\n<p>where we are making the not entirely reasonable assumption that the recursion always lands in the larger of <code>A1</code> or <code>A2</code>.</p>\n\n<p>Let's guess that <code>T(n) &lt;= an</code> for some <code>a</code>. Then we get</p>\n\n<pre><code>T(n) \n &lt;= cn + (1/n) ∑<sub>i=1 to n</sub>T(max(i-1, n-i))\n = cn + (1/n) ∑<sub>i=1 to floor(n/2)</sub> T(n-i) + (1/n) ∑<sub>i=floor(n/2)+1 to n</sub> T(i)\n &lt;= cn + 2 (1/n) ∑<sub>i=floor(n/2) to n</sub> T(i)\n &lt;= cn + 2 (1/n) ∑<sub>i=floor(n/2) to n</sub> ai</code></pre>\n\n<p>and now somehow we have to get the horrendous sum on the right of the plus sign to absorb the <code>cn</code> on the left. If we just bound it as <code>2(1/n) ∑<sub>i=n/2 to n</sub> an</code>, we get roughly <code>2(1/n)(n/2)an = an</code>. But this is too big - there's no room to squeeze in an extra <code>cn</code>. So let's expand the sum using the arithmetic series formula:</p>\n\n<pre><code>∑<sub>i=floor(n/2) to n</sub> i \n = ∑<sub>i=1 to n</sub> i - ∑<sub>i=1 to floor(n/2)</sub> i \n = n(n+1)/2 - floor(n/2)(floor(n/2)+1)/2 \n &lt;= n<sup>2</sup>/2 - (n/4)<sup>2</sup>/2 \n = (15/32)n<sup>2</sup></code></pre>\n\n<p>where we take advantage of n being \"sufficiently large\" to replace the ugly <code>floor(n/2)</code> factors with the much cleaner (and smaller) <code>n/4</code>. Now we can continue with</p>\n\n<pre><code>cn + 2 (1/n) ∑<sub>i=floor(n/2) to n</sub> ai,\n &lt;= cn + (2a/n) (15/32) n<sup>2</sup>\n = n (c + (15/16)a)\n &lt;= an</code></pre>\n\n<p>provided <code>a &gt; 16c</code>.</p>\n\n<p>This gives <code>T(n) = O(n)</code>. It's clearly <code>Omega(n)</code>, so we get <code>T(n) = Theta(n)</code>.</p>\n" }, { "answer_id": 1213653, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>i would like to suggest one answer</p>\n\n<p>if we take the first k elements and sort them into a linked list of k values</p>\n\n<p>now for every other value even for the worst case if we do insertion sort for rest n-k values even in the worst case number of comparisons will be k*(n-k) and for prev k values to be sorted let it be k*(k-1) so it comes out to be (nk-k) which is o(n)</p>\n\n<p>cheers </p>\n" }, { "answer_id": 2663358, "author": "pranjal", "author_id": 319806, "author_profile": "https://Stackoverflow.com/users/319806", "pm_score": 2, "selected": false, "text": "<p>Find the median of the array in linear time, then use partition procedure exactly as in quicksort to divide the array in two parts, values to the left of the median lesser( &lt; ) than than median and to the right greater than ( > ) median, that too can be done in lineat time, now, go to that part of the array where kth element lies, \nNow recurrence becomes:\nT(n) = T(n/2) + cn \nwhich gives me O (n) overal.</p>\n" }, { "answer_id": 3098488, "author": "stinky", "author_id": 373806, "author_profile": "https://Stackoverflow.com/users/373806", "pm_score": 4, "selected": false, "text": "<p>You do like quicksort. Pick an element at random and shove everything either higher or lower. At this point you'll know which element you actually picked, and if it is the kth element you're done, otherwise you repeat with the bin (higher or lower), that the kth element would fall in. Statistically speaking, the time it takes to find the kth element grows with n, O(n). </p>\n" }, { "answer_id": 4590973, "author": "Malkit S. Bhasin", "author_id": 560176, "author_profile": "https://Stackoverflow.com/users/560176", "pm_score": 2, "selected": false, "text": "<p>I implemented finding kth minimimum in n unsorted elements using dynamic programming, specifically tournament method. The execution time is O(n + klog(n)). The mechanism used is listed as one of methods on Wikipedia page about Selection Algorithm (as indicated in one of the posting above). You can read about the algorithm and also find code (java) on my blog page <a href=\"http://malkit.blogspot.com/2012/07/finding-kth-minimum-partial-ordering.html\" rel=\"nofollow noreferrer\">Finding Kth Minimum</a>. In addition the logic can do partial ordering of the list - return first K min (or max) in O(klog(n)) time.</p>\n\n<p>Though the code provided result kth minimum, similar logic can be employed to find kth maximum in O(klog(n)), ignoring the pre-work done to create tournament tree.</p>\n" }, { "answer_id": 7103794, "author": "prithvi zankat", "author_id": 606270, "author_profile": "https://Stackoverflow.com/users/606270", "pm_score": 2, "selected": false, "text": "<p><strong>Although not very sure about O(n) complexity, but it will be sure to be between O(n) and nLog(n). Also sure to be closer to O(n) than nLog(n). Function is written in Java</strong></p>\n\n<pre><code>public int quickSelect(ArrayList&lt;Integer&gt;list, int nthSmallest){\n //Choose random number in range of 0 to array length\n Random random = new Random();\n //This will give random number which is not greater than length - 1\n int pivotIndex = random.nextInt(list.size() - 1); \n\n int pivot = list.get(pivotIndex);\n\n ArrayList&lt;Integer&gt; smallerNumberList = new ArrayList&lt;Integer&gt;();\n ArrayList&lt;Integer&gt; greaterNumberList = new ArrayList&lt;Integer&gt;();\n\n //Split list into two. \n //Value smaller than pivot should go to smallerNumberList\n //Value greater than pivot should go to greaterNumberList\n //Do nothing for value which is equal to pivot\n for(int i=0; i&lt;list.size(); i++){\n if(list.get(i)&lt;pivot){\n smallerNumberList.add(list.get(i));\n }\n else if(list.get(i)&gt;pivot){\n greaterNumberList.add(list.get(i));\n }\n else{\n //Do nothing\n }\n }\n\n //If smallerNumberList size is greater than nthSmallest value, nthSmallest number must be in this list \n if(nthSmallest &lt; smallerNumberList.size()){\n return quickSelect(smallerNumberList, nthSmallest);\n }\n //If nthSmallest is greater than [ list.size() - greaterNumberList.size() ], nthSmallest number must be in this list\n //The step is bit tricky. If confusing, please see the above loop once again for clarification.\n else if(nthSmallest &gt; (list.size() - greaterNumberList.size())){\n //nthSmallest will have to be changed here. [ list.size() - greaterNumberList.size() ] elements are already in \n //smallerNumberList\n nthSmallest = nthSmallest - (list.size() - greaterNumberList.size());\n return quickSelect(greaterNumberList,nthSmallest);\n }\n else{\n return pivot;\n }\n}\n</code></pre>\n" }, { "answer_id": 12739961, "author": "Sandeep Mathias", "author_id": 1533689, "author_profile": "https://Stackoverflow.com/users/1533689", "pm_score": -1, "selected": false, "text": "<p>For very small values of k (i.e. when k &lt;&lt; n), we can get it done in ~O(n) time. Otherwise, if k is comparable to n, we get it in O(nlogn).</p>\n" }, { "answer_id": 15144377, "author": "totjammykd", "author_id": 2056223, "author_profile": "https://Stackoverflow.com/users/2056223", "pm_score": 1, "selected": false, "text": "<p>Explanation of the median - of - medians algorithm to find the k-th largest integer out of n can be found here:\n<a href=\"http://cs.indstate.edu/~spitla/presentation.pdf\" rel=\"nofollow\">http://cs.indstate.edu/~spitla/presentation.pdf</a></p>\n\n<p>Implementation in c++ is below:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nint findMedian(vector&lt;int&gt; vec){\n// Find median of a vector\n int median;\n size_t size = vec.size();\n median = vec[(size/2)];\n return median;\n}\n\nint findMedianOfMedians(vector&lt;vector&lt;int&gt; &gt; values){\n vector&lt;int&gt; medians;\n\n for (int i = 0; i &lt; values.size(); i++) {\n int m = findMedian(values[i]);\n medians.push_back(m);\n }\n\n return findMedian(medians);\n}\n\nvoid selectionByMedianOfMedians(const vector&lt;int&gt; values, int k){\n// Divide the list into n/5 lists of 5 elements each\n vector&lt;vector&lt;int&gt; &gt; vec2D;\n\n int count = 0;\n while (count != values.size()) {\n int countRow = 0;\n vector&lt;int&gt; row;\n\n while ((countRow &lt; 5) &amp;&amp; (count &lt; values.size())) {\n row.push_back(values[count]);\n count++;\n countRow++;\n }\n vec2D.push_back(row);\n }\n\n cout&lt;&lt;endl&lt;&lt;endl&lt;&lt;\"Printing 2D vector : \"&lt;&lt;endl;\n for (int i = 0; i &lt; vec2D.size(); i++) {\n for (int j = 0; j &lt; vec2D[i].size(); j++) {\n cout&lt;&lt;vec2D[i][j]&lt;&lt;\" \";\n }\n cout&lt;&lt;endl;\n }\n cout&lt;&lt;endl;\n\n// Calculating a new pivot for making splits\n int m = findMedianOfMedians(vec2D);\n cout&lt;&lt;\"Median of medians is : \"&lt;&lt;m&lt;&lt;endl;\n\n// Partition the list into unique elements larger than 'm' (call this sublist L1) and\n// those smaller them 'm' (call this sublist L2)\n vector&lt;int&gt; L1, L2;\n\n for (int i = 0; i &lt; vec2D.size(); i++) {\n for (int j = 0; j &lt; vec2D[i].size(); j++) {\n if (vec2D[i][j] &gt; m) {\n L1.push_back(vec2D[i][j]);\n }else if (vec2D[i][j] &lt; m){\n L2.push_back(vec2D[i][j]);\n }\n }\n }\n\n// Checking the splits as per the new pivot 'm'\n cout&lt;&lt;endl&lt;&lt;\"Printing L1 : \"&lt;&lt;endl;\n for (int i = 0; i &lt; L1.size(); i++) {\n cout&lt;&lt;L1[i]&lt;&lt;\" \";\n }\n\n cout&lt;&lt;endl&lt;&lt;endl&lt;&lt;\"Printing L2 : \"&lt;&lt;endl;\n for (int i = 0; i &lt; L2.size(); i++) {\n cout&lt;&lt;L2[i]&lt;&lt;\" \";\n }\n\n// Recursive calls\n if ((k - 1) == L1.size()) {\n cout&lt;&lt;endl&lt;&lt;endl&lt;&lt;\"Answer :\"&lt;&lt;m;\n }else if (k &lt;= L1.size()) {\n return selectionByMedianOfMedians(L1, k);\n }else if (k &gt; (L1.size() + 1)){\n return selectionByMedianOfMedians(L2, k-((int)L1.size())-1);\n }\n\n}\n\nint main()\n{\n int values[] = {2, 3, 5, 4, 1, 12, 11, 13, 16, 7, 8, 6, 10, 9, 17, 15, 19, 20, 18, 23, 21, 22, 25, 24, 14};\n\n vector&lt;int&gt; vec(values, values + 25);\n\n cout&lt;&lt;\"The given array is : \"&lt;&lt;endl;\n for (int i = 0; i &lt; vec.size(); i++) {\n cout&lt;&lt;vec[i]&lt;&lt;\" \";\n }\n\n selectionByMedianOfMedians(vec, 8);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 17742397, "author": "Zoran Horvat", "author_id": 2279448, "author_profile": "https://Stackoverflow.com/users/2279448", "pm_score": 2, "selected": false, "text": "<p>Below is the link to full implementation with quite an extensive explanation how the algorithm for finding Kth element in an unsorted algorithm works. Basic idea is to partition the array like in QuickSort. But in order to avoid extreme cases (e.g. when smallest element is chosen as pivot in every step, so that algorithm degenerates into O(n^2) running time), special pivot selection is applied, called median-of-medians algorithm. The whole solution runs in O(n) time in worst and in average case.</p>\n\n<p>Here is link to the full article (it is about finding Kth <em>smallest</em> element, but the principle is the same for finding Kth <em>largest</em>):</p>\n\n<p><strong><a href=\"http://www.codinghelmet.com/?path=exercises/kth-smallest\" rel=\"nofollow\">Finding Kth Smallest Element in an Unsorted Array</a></strong></p>\n" }, { "answer_id": 18848682, "author": "user2601131", "author_id": 2601131, "author_profile": "https://Stackoverflow.com/users/2601131", "pm_score": -1, "selected": false, "text": "<p>First we can build a BST from unsorted array which takes O(n) time and from the BST we can find the kth smallest element in O(log(n)) which over all counts to an order of O(n).</p>\n" }, { "answer_id": 19089380, "author": "Chris Cinelli", "author_id": 407245, "author_profile": "https://Stackoverflow.com/users/407245", "pm_score": 0, "selected": false, "text": "<p>This is an implementation in Javascript.</p>\n\n<p>If you release the constraint that you cannot modify the array, you can prevent the use of extra memory using two indexes to identify the \"current partition\" (in classic quicksort style - <a href=\"http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/\" rel=\"nofollow\">http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/</a>).</p>\n\n<pre><code>function kthMax(a, k){\n var size = a.length;\n\n var pivot = a[ parseInt(Math.random()*size) ]; //Another choice could have been (size / 2) \n\n //Create an array with all element lower than the pivot and an array with all element higher than the pivot\n var i, lowerArray = [], upperArray = [];\n for (i = 0; i &lt; size; i++){\n var current = a[i];\n\n if (current &lt; pivot) {\n lowerArray.push(current);\n } else if (current &gt; pivot) {\n upperArray.push(current);\n }\n }\n\n //Which one should I continue with?\n if(k &lt;= upperArray.length) {\n //Upper\n return kthMax(upperArray, k);\n } else {\n var newK = k - (size - lowerArray.length);\n\n if (newK &gt; 0) {\n ///Lower\n return kthMax(lowerArray, newK);\n } else {\n //None ... it's the current pivot!\n return pivot;\n } \n }\n} \n</code></pre>\n\n<p>If you want to test how it perform, you can use this variation:</p>\n\n<pre><code> function kthMax (a, k, logging) {\n var comparisonCount = 0; //Number of comparison that the algorithm uses\n var memoryCount = 0; //Number of integers in memory that the algorithm uses\n var _log = logging;\n\n if(k &lt; 0 || k &gt;= a.length) {\n if (_log) console.log (\"k is out of range\"); \n return false;\n } \n\n function _kthmax(a, k){\n var size = a.length;\n var pivot = a[parseInt(Math.random()*size)];\n if(_log) console.log(\"Inputs:\", a, \"size=\"+size, \"k=\"+k, \"pivot=\"+pivot);\n\n // This should never happen. Just a nice check in this exercise\n // if you are playing with the code to avoid never ending recursion \n if(typeof pivot === \"undefined\") {\n if (_log) console.log (\"Ops...\"); \n return false;\n }\n\n var i, lowerArray = [], upperArray = [];\n for (i = 0; i &lt; size; i++){\n var current = a[i];\n if (current &lt; pivot) {\n comparisonCount += 1;\n memoryCount++;\n lowerArray.push(current);\n } else if (current &gt; pivot) {\n comparisonCount += 2;\n memoryCount++;\n upperArray.push(current);\n }\n }\n if(_log) console.log(\"Pivoting:\",lowerArray, \"*\"+pivot+\"*\", upperArray);\n\n if(k &lt;= upperArray.length) {\n comparisonCount += 1;\n return _kthmax(upperArray, k);\n } else if (k &gt; size - lowerArray.length) {\n comparisonCount += 2;\n return _kthmax(lowerArray, k - (size - lowerArray.length));\n } else {\n comparisonCount += 2;\n return pivot;\n }\n /* \n * BTW, this is the logic for kthMin if we want to implement that... ;-)\n * \n\n if(k &lt;= lowerArray.length) {\n return kthMin(lowerArray, k);\n } else if (k &gt; size - upperArray.length) {\n return kthMin(upperArray, k - (size - upperArray.length));\n } else \n return pivot;\n */ \n }\n\n var result = _kthmax(a, k);\n return {result: result, iterations: comparisonCount, memory: memoryCount};\n }\n</code></pre>\n\n<p>The rest of the code is just to create some playground: </p>\n\n<pre><code> function getRandomArray (n){\n var ar = [];\n for (var i = 0, l = n; i &lt; l; i++) {\n ar.push(Math.round(Math.random() * l))\n }\n\n return ar;\n }\n\n //Create a random array of 50 numbers\n var ar = getRandomArray (50); \n</code></pre>\n\n<p>Now, run you tests a few time.\nBecause of the Math.random() it will produce every time different results:</p>\n\n<pre><code> kthMax(ar, 2, true);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 2);\n kthMax(ar, 34, true);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n kthMax(ar, 34);\n</code></pre>\n\n<p>If you test it a few times you can see even empirically that the number of iterations is, on average, O(n) ~= constant * n and the value of k does not affect the algorithm.</p>\n" }, { "answer_id": 24893260, "author": "hoder", "author_id": 2525478, "author_profile": "https://Stackoverflow.com/users/2525478", "pm_score": 2, "selected": false, "text": "<p>Sexy quickselect in Python</p>\n\n<pre><code>def quickselect(arr, k):\n '''\n k = 1 returns first element in ascending order.\n can be easily modified to return first element in descending order\n '''\n\n r = random.randrange(0, len(arr))\n\n a1 = [i for i in arr if i &lt; arr[r]] '''partition'''\n a2 = [i for i in arr if i &gt; arr[r]]\n\n if k &lt;= len(a1):\n return quickselect(a1, k)\n elif k &gt; len(arr)-len(a2):\n return quickselect(a2, k - (len(arr) - len(a2)))\n else:\n return arr[r]\n</code></pre>\n" }, { "answer_id": 26725019, "author": "estama", "author_id": 4212243, "author_profile": "https://Stackoverflow.com/users/4212243", "pm_score": 1, "selected": false, "text": "<p>There is also <a href=\"http://mail.scipy.org/pipermail/numpy-discussion/2009-August/044893.html\" rel=\"nofollow\">Wirth's selection algorithm</a>, which has a simpler implementation than QuickSelect. Wirth's selection algorithm is slower than QuickSelect, but with some improvements it becomes faster. </p>\n\n<p>In more detail. Using Vladimir Zabrodsky's MODIFIND optimization and the median-of-3 pivot selection and paying some attention to the final steps of the partitioning part of the algorithm, i've came up with the following algorithm (imaginably named \"LefSelect\"):</p>\n\n<pre><code>#define F_SWAP(a,b) { float temp=(a);(a)=(b);(b)=temp; }\n\n# Note: The code needs more than 2 elements to work\nfloat lefselect(float a[], const int n, const int k) {\n int l=0, m = n-1, i=l, j=m;\n float x;\n\n while (l&lt;m) {\n if( a[k] &lt; a[i] ) F_SWAP(a[i],a[k]);\n if( a[j] &lt; a[i] ) F_SWAP(a[i],a[j]);\n if( a[j] &lt; a[k] ) F_SWAP(a[k],a[j]);\n\n x=a[k];\n while (j&gt;k &amp; i&lt;k) {\n do i++; while (a[i]&lt;x);\n do j--; while (a[j]&gt;x);\n\n F_SWAP(a[i],a[j]);\n }\n i++; j--;\n\n if (j&lt;k) {\n while (a[i]&lt;x) i++;\n l=i; j=m;\n }\n if (k&lt;i) {\n while (x&lt;a[j]) j--;\n m=j; i=l;\n }\n }\n return a[k];\n}\n</code></pre>\n\n<p>In benchmarks that i did <a href=\"http://www.beamng.com/entries/86-A-faster-selection\" rel=\"nofollow\">here</a>, LefSelect is 20-30% faster than QuickSelect.</p>\n" }, { "answer_id": 28120511, "author": "user3585010", "author_id": 3585010, "author_profile": "https://Stackoverflow.com/users/3585010", "pm_score": 1, "selected": false, "text": "<p>Haskell Solution:</p>\n\n<pre><code>kthElem index list = sort list !! index\n\nwithShape ~[] [] = []\nwithShape ~(x:xs) (y:ys) = x : withShape xs ys\n\nsort [] = []\nsort (x:xs) = (sort ls `withShape` ls) ++ [x] ++ (sort rs `withShape` rs)\n where\n ls = filter (&lt; x)\n rs = filter (&gt;= x)\n</code></pre>\n\n<p>This implements the median of median solutions by using the withShape method to discover the size of a partition without actually computing it. </p>\n" }, { "answer_id": 29729453, "author": "learner", "author_id": 1672427, "author_profile": "https://Stackoverflow.com/users/1672427", "pm_score": 1, "selected": false, "text": "<p>Here is a C++ implementation of Randomized QuickSelect. The idea is to randomly pick a pivot element. To implement randomized partition, we use a random function, rand() to generate index between l and r, swap the element at randomly generated index with the last element, and finally call the standard partition process which uses last element as pivot. </p>\n\n<pre><code>#include&lt;iostream&gt;\n#include&lt;climits&gt;\n#include&lt;cstdlib&gt;\nusing namespace std;\n\nint randomPartition(int arr[], int l, int r);\n\n// This function returns k'th smallest element in arr[l..r] using\n// QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT\nint kthSmallest(int arr[], int l, int r, int k)\n{\n // If k is smaller than number of elements in array\n if (k &gt; 0 &amp;&amp; k &lt;= r - l + 1)\n {\n // Partition the array around a random element and\n // get position of pivot element in sorted array\n int pos = randomPartition(arr, l, r);\n\n // If position is same as k\n if (pos-l == k-1)\n return arr[pos];\n if (pos-l &gt; k-1) // If position is more, recur for left subarray\n return kthSmallest(arr, l, pos-1, k);\n\n // Else recur for right subarray\n return kthSmallest(arr, pos+1, r, k-pos+l-1);\n }\n\n // If k is more than number of elements in array\n return INT_MAX;\n}\n\nvoid swap(int *a, int *b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\n// Standard partition process of QuickSort(). It considers the last\n// element as pivot and moves all smaller element to left of it and\n// greater elements to right. This function is used by randomPartition()\nint partition(int arr[], int l, int r)\n{\n int x = arr[r], i = l;\n for (int j = l; j &lt;= r - 1; j++)\n {\n if (arr[j] &lt;= x) //arr[i] is bigger than arr[j] so swap them\n {\n swap(&amp;arr[i], &amp;arr[j]);\n i++;\n }\n }\n swap(&amp;arr[i], &amp;arr[r]); // swap the pivot\n return i;\n}\n\n// Picks a random pivot element between l and r and partitions\n// arr[l..r] around the randomly picked element using partition()\nint randomPartition(int arr[], int l, int r)\n{\n int n = r-l+1;\n int pivot = rand() % n;\n swap(&amp;arr[l + pivot], &amp;arr[r]);\n return partition(arr, l, r);\n}\n\n// Driver program to test above methods\nint main()\n{\n int arr[] = {12, 3, 5, 7, 4, 19, 26};\n int n = sizeof(arr)/sizeof(arr[0]), k = 3;\n cout &lt;&lt; \"K'th smallest element is \" &lt;&lt; kthSmallest(arr, 0, n-1, k);\n return 0;\n}\n</code></pre>\n\n<p>The worst case time complexity of the above solution is still O(n2).In worst case, the randomized function may always pick a corner element. The expected time complexity of above randomized QuickSelect is Θ(n)</p>\n" }, { "answer_id": 31862041, "author": "advncd", "author_id": 996926, "author_profile": "https://Stackoverflow.com/users/996926", "pm_score": 0, "selected": false, "text": "<p>I came up with this algorithm and seems to be O(n):</p>\n\n<p>Let's say k=3 and we want to find the 3rd largest item in the array. I would create three variables and compare each item of the array with the minimum of these three variables. If array item is greater than our minimum, we would replace the min variable with the item value. We continue the same thing until end of the array. The minimum of our three variables is the 3rd largest item in the array.</p>\n\n<pre><code>define variables a=0, b=0, c=0\niterate through the array items\n find minimum a,b,c\n if item &gt; min then replace the min variable with item value\n continue until end of array\nthe minimum of a,b,c is our answer\n</code></pre>\n\n<p>And, to find Kth largest item we need K variables.</p>\n\n<p>Example: (k=3)</p>\n\n<pre><code>[1,2,4,1,7,3,9,5,6,2,9,8]\n\nFinal variable values:\n\na=7 (answer)\nb=8\nc=9\n</code></pre>\n\n<p>Can someone please review this and let me know what I am missing?</p>\n" }, { "answer_id": 32394237, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 2, "selected": false, "text": "<p>As per this paper <a href=\"http://cs.indstate.edu/~spitla/abstract2.pdf\" rel=\"nofollow\">Finding the Kth largest item in a list of n items</a> the following algorithm will take <code>O(n)</code> time in worst case.</p>\n\n<ol>\n<li>Divide the array in to n/5 lists of 5 elements each.</li>\n<li>Find the median in each sub array of 5 elements.</li>\n<li>Recursively find the median of all the medians, lets call it M</li>\n<li>Partition the array in to two sub array 1st sub-array contains the elements larger than M , lets say this sub-array is a1 , while other sub-array contains the elements smaller then M., lets call this sub-array a2.</li>\n<li>If k &lt;= |a1|, return selection (a1,k).</li>\n<li>If k− 1 = |a1|, return M.</li>\n<li>If k> |a1| + 1, return selection(a2,k −a1 − 1).</li>\n</ol>\n\n<p><strong>Analysis:</strong> As suggested in the original paper:</p>\n\n<blockquote>\n <p>We use the median to partition the list into two halves(the first half,\n if <code>k &lt;= n/2</code> , and the second half otherwise). This algorithm takes\n time <code>cn</code> at the first level of recursion for some constant <code>c</code>, <code>cn/2</code> at\n the next level (since we recurse in a list of size n/2), <code>cn/4</code> at the\n third level, and so on. The total time taken is <code>cn + cn/2 + cn/4 +\n .... = 2cn = o(n)</code>.</p>\n</blockquote>\n\n<p><strong>Why partition size is taken 5 and not 3?</strong></p>\n\n<p>As mentioned in original <a href=\"http://cs.indstate.edu/~spitla/abstract2.pdf\" rel=\"nofollow\">paper</a>: </p>\n\n<blockquote>\n <p>Dividing the list by 5 assures a worst-case split of 70 − 30. Atleast\n half of the medians greater than the median-of-medians, hence atleast\n half of the n/5 blocks have atleast 3 elements and this gives a\n <code>3n/10</code> split, which means the other partition is 7n/10 in worst case.\n That gives <code>T(n) = T(n/5)+T(7n/10)+O(n). Since n/5+7n/10 &lt; 1</code>, the\n worst-case running time is<code>O(n)</code>.</p>\n</blockquote>\n\n<p>Now I have tried to implement the above algorithm as:</p>\n\n<pre><code>public static int findKthLargestUsingMedian(Integer[] array, int k) {\n // Step 1: Divide the list into n/5 lists of 5 element each.\n int noOfRequiredLists = (int) Math.ceil(array.length / 5.0);\n // Step 2: Find pivotal element aka median of medians.\n int medianOfMedian = findMedianOfMedians(array, noOfRequiredLists);\n //Now we need two lists split using medianOfMedian as pivot. All elements in list listOne will be grater than medianOfMedian and listTwo will have elements lesser than medianOfMedian.\n List&lt;Integer&gt; listWithGreaterNumbers = new ArrayList&lt;&gt;(); // elements greater than medianOfMedian\n List&lt;Integer&gt; listWithSmallerNumbers = new ArrayList&lt;&gt;(); // elements less than medianOfMedian\n for (Integer element : array) {\n if (element &lt; medianOfMedian) {\n listWithSmallerNumbers.add(element);\n } else if (element &gt; medianOfMedian) {\n listWithGreaterNumbers.add(element);\n }\n }\n // Next step.\n if (k &lt;= listWithGreaterNumbers.size()) return findKthLargestUsingMedian((Integer[]) listWithGreaterNumbers.toArray(new Integer[listWithGreaterNumbers.size()]), k);\n else if ((k - 1) == listWithGreaterNumbers.size()) return medianOfMedian;\n else if (k &gt; (listWithGreaterNumbers.size() + 1)) return findKthLargestUsingMedian((Integer[]) listWithSmallerNumbers.toArray(new Integer[listWithSmallerNumbers.size()]), k-listWithGreaterNumbers.size()-1);\n return -1;\n }\n\n public static int findMedianOfMedians(Integer[] mainList, int noOfRequiredLists) {\n int[] medians = new int[noOfRequiredLists];\n for (int count = 0; count &lt; noOfRequiredLists; count++) {\n int startOfPartialArray = 5 * count;\n int endOfPartialArray = startOfPartialArray + 5;\n Integer[] partialArray = Arrays.copyOfRange((Integer[]) mainList, startOfPartialArray, endOfPartialArray);\n // Step 2: Find median of each of these sublists.\n int medianIndex = partialArray.length/2;\n medians[count] = partialArray[medianIndex];\n }\n // Step 3: Find median of the medians.\n return medians[medians.length / 2];\n }\n</code></pre>\n\n<p>Just for sake of completion, another algorithm makes use of Priority Queue and takes time <code>O(nlogn)</code>.</p>\n\n<pre><code>public static int findKthLargestUsingPriorityQueue(Integer[] nums, int k) {\n int p = 0;\n int numElements = nums.length;\n // create priority queue where all the elements of nums will be stored\n PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;Integer&gt;();\n\n // place all the elements of the array to this priority queue\n for (int n : nums) {\n pq.add(n);\n }\n\n // extract the kth largest element\n while (numElements - k + 1 &gt; 0) {\n p = pq.poll();\n k++;\n }\n\n return p;\n }\n</code></pre>\n\n<p>Both of these algorithms can be tested as:</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n Integer[] numbers = new Integer[]{2, 3, 5, 4, 1, 12, 11, 13, 16, 7, 8, 6, 10, 9, 17, 15, 19, 20, 18, 23, 21, 22, 25, 24, 14};\n System.out.println(findKthLargestUsingMedian(numbers, 8));\n System.out.println(findKthLargestUsingPriorityQueue(numbers, 8));\n }\n</code></pre>\n\n<p>As expected output is:\n<code>18\n18</code> </p>\n" }, { "answer_id": 37587307, "author": "TheLogicGuy", "author_id": 2671102, "author_profile": "https://Stackoverflow.com/users/2671102", "pm_score": 0, "selected": false, "text": "<p>Here is the implementation of the algorithm eladv suggested(I also put here the implementation with random pivot):</p>\n\n<pre><code>public class Median {\n\n public static void main(String[] s) {\n\n int[] test = {4,18,20,3,7,13,5,8,2,1,15,17,25,30,16};\n System.out.println(selectK(test,8));\n\n /*\n int n = 100000000;\n int[] test = new int[n];\n for(int i=0; i&lt;test.length; i++)\n test[i] = (int)(Math.random()*test.length);\n\n long start = System.currentTimeMillis();\n random_selectK(test, test.length/2);\n long end = System.currentTimeMillis();\n System.out.println(end - start);\n */\n }\n\n public static int random_selectK(int[] a, int k) {\n if(a.length &lt;= 1)\n return a[0];\n\n int r = (int)(Math.random() * a.length);\n int p = a[r];\n\n int small = 0, equal = 0, big = 0;\n for(int i=0; i&lt;a.length; i++) {\n if(a[i] &lt; p) small++;\n else if(a[i] == p) equal++;\n else if(a[i] &gt; p) big++;\n }\n\n if(k &lt;= small) {\n int[] temp = new int[small];\n for(int i=0, j=0; i&lt;a.length; i++)\n if(a[i] &lt; p)\n temp[j++] = a[i];\n return random_selectK(temp, k);\n }\n\n else if (k &lt;= small+equal)\n return p;\n\n else {\n int[] temp = new int[big];\n for(int i=0, j=0; i&lt;a.length; i++)\n if(a[i] &gt; p)\n temp[j++] = a[i];\n return random_selectK(temp,k-small-equal);\n }\n }\n\n public static int selectK(int[] a, int k) {\n if(a.length &lt;= 5) {\n Arrays.sort(a);\n return a[k-1];\n }\n\n int p = median_of_medians(a);\n\n int small = 0, equal = 0, big = 0;\n for(int i=0; i&lt;a.length; i++) {\n if(a[i] &lt; p) small++;\n else if(a[i] == p) equal++;\n else if(a[i] &gt; p) big++;\n }\n\n if(k &lt;= small) {\n int[] temp = new int[small];\n for(int i=0, j=0; i&lt;a.length; i++)\n if(a[i] &lt; p)\n temp[j++] = a[i];\n return selectK(temp, k);\n }\n\n else if (k &lt;= small+equal)\n return p;\n\n else {\n int[] temp = new int[big];\n for(int i=0, j=0; i&lt;a.length; i++)\n if(a[i] &gt; p)\n temp[j++] = a[i];\n return selectK(temp,k-small-equal);\n }\n }\n\n private static int median_of_medians(int[] a) {\n int[] b = new int[a.length/5];\n int[] temp = new int[5];\n for(int i=0; i&lt;b.length; i++) {\n for(int j=0; j&lt;5; j++)\n temp[j] = a[5*i + j];\n Arrays.sort(temp);\n b[i] = temp[2];\n }\n\n return selectK(b, b.length/2 + 1);\n }\n}\n</code></pre>\n" }, { "answer_id": 37855810, "author": "Aishwat Singh", "author_id": 5227718, "author_profile": "https://Stackoverflow.com/users/5227718", "pm_score": 2, "selected": false, "text": "<p>How about this kinda approach </p>\n\n<p>Maintain a <code>buffer of length k</code> and a <code>tmp_max</code>, getting tmp_max is O(k) and is done n times so something like <code>O(kn)</code> </p>\n\n<p><a href=\"https://i.stack.imgur.com/f0P3y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/f0P3y.png\" alt=\"enter image description here\"></a></p>\n\n<p>Is it right or am i missing something ?</p>\n\n<p><em>Although it doesn't beat average case of quickselect and worst case of median statistics method but its pretty easy to understand and implement.</em> </p>\n" }, { "answer_id": 38143116, "author": "Lee.O.", "author_id": 5976676, "author_profile": "https://Stackoverflow.com/users/5976676", "pm_score": 0, "selected": false, "text": "<p>it is similar to the quickSort strategy, where we pick an arbitrary pivot, and bring the smaller elements to its left, and the larger to the right</p>\n\n<pre><code> public static int kthElInUnsortedList(List&lt;int&gt; list, int k)\n {\n if (list.Count == 1)\n return list[0];\n\n List&lt;int&gt; left = new List&lt;int&gt;();\n List&lt;int&gt; right = new List&lt;int&gt;();\n\n int pivotIndex = list.Count / 2;\n int pivot = list[pivotIndex]; //arbitrary\n\n for (int i = 0; i &lt; list.Count &amp;&amp; i != pivotIndex; i++)\n {\n int currentEl = list[i];\n if (currentEl &lt; pivot)\n left.Add(currentEl);\n else\n right.Add(currentEl);\n }\n\n if (k == left.Count + 1)\n return pivot;\n\n if (left.Count &lt; k)\n return kthElInUnsortedList(right, k - left.Count - 1);\n else\n return kthElInUnsortedList(left, k);\n }\n</code></pre>\n" }, { "answer_id": 38573638, "author": "Victor", "author_id": 4368994, "author_profile": "https://Stackoverflow.com/users/4368994", "pm_score": 0, "selected": false, "text": "<p>Go to the End of this link : ...........</p>\n\n<p><a href=\"http://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time/\" rel=\"nofollow\">http://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time/</a></p>\n" }, { "answer_id": 40210625, "author": "Bhagwati Malav", "author_id": 3572733, "author_profile": "https://Stackoverflow.com/users/3572733", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Have Priority queue created.</li>\n<li>Insert all the elements into heap.</li>\n<li><p>Call poll() k times.</p>\n\n<pre><code>public static int getKthLargestElements(int[] arr)\n{\n PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;((x , y) -&gt; (y-x));\n //insert all the elements into heap\n for(int ele : arr)\n pq.offer(ele);\n // call poll() k times\n int i=0;\n while(i&amp;lt;k)\n {\n int result = pq.poll();\n } \n return result; \n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 47044986, "author": "Anubhav Agarwal", "author_id": 1032610, "author_profile": "https://Stackoverflow.com/users/1032610", "pm_score": 0, "selected": false, "text": "<p>You can find the kth smallest element in O(n) time and constant space. If we consider the array is only for integers.</p>\n\n<p>The approach is to do a binary search on the range of Array values. If we have a min_value and a max_value both in integer range, we can do a binary search on that range.\nWe can write a comparator function which will tell us if any value is the kth-smallest or smaller than kth-smallest or bigger than kth-smallest.\nDo the binary search until you reach the kth-smallest number</p>\n\n<p>Here is the code for that</p>\n\n<p>class Solution:</p>\n\n<pre><code>def _iskthsmallest(self, A, val, k):\n less_count, equal_count = 0, 0\n for i in range(len(A)):\n if A[i] == val: equal_count += 1\n if A[i] &lt; val: less_count += 1\n\n if less_count &gt;= k: return 1\n if less_count + equal_count &lt; k: return -1\n return 0\n\ndef kthsmallest_binary(self, A, min_val, max_val, k):\n if min_val == max_val:\n return min_val\n mid = (min_val + max_val)/2\n iskthsmallest = self._iskthsmallest(A, mid, k)\n if iskthsmallest == 0: return mid\n if iskthsmallest &gt; 0: return self.kthsmallest_binary(A, min_val, mid, k)\n return self.kthsmallest_binary(A, mid+1, max_val, k)\n\n# @param A : tuple of integers\n# @param B : integer\n# @return an integer\ndef kthsmallest(self, A, k):\n if not A: return 0\n if k &gt; len(A): return 0\n min_val, max_val = min(A), max(A)\n return self.kthsmallest_binary(A, min_val, max_val, k)\n</code></pre>\n" }, { "answer_id": 48825994, "author": "L'ahim", "author_id": 4145053, "author_profile": "https://Stackoverflow.com/users/4145053", "pm_score": 2, "selected": false, "text": "<p>There is also one algorithm, that outperforms quickselect algorithm. It's called <strong>Floyd-Rivets (FR) algorithm</strong>.</p>\n\n<p>Original article: <a href=\"https://doi.org/10.1145/360680.360694\" rel=\"nofollow noreferrer\">https://doi.org/10.1145/360680.360694</a></p>\n\n<p>Downloadable version: <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.7108&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow noreferrer\">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.7108&amp;rep=rep1&amp;type=pdf</a></p>\n\n<p>Wikipedia article <a href=\"https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm</a> </p>\n\n<p>I tried to implement quickselect and FR algorithm in C++. Also I compared them to the standard C++ library implementations std::nth_element (which is basically introselect hybrid of quickselect and heapselect). The result was quickselect and nth_element ran comparably on average, but FR algorithm ran approx. twice as fast compared to them. </p>\n\n<p>Sample code that I used for FR algorithm:</p>\n\n<pre><code>template &lt;typename T&gt;\nT FRselect(std::vector&lt;T&gt;&amp; data, const size_t&amp; n)\n{\n if (n == 0)\n return *(std::min_element(data.begin(), data.end()));\n else if (n == data.size() - 1)\n return *(std::max_element(data.begin(), data.end()));\n else\n return _FRselect(data, 0, data.size() - 1, n);\n}\n\ntemplate &lt;typename T&gt;\nT _FRselect(std::vector&lt;T&gt;&amp; data, const size_t&amp; left, const size_t&amp; right, const size_t&amp; n)\n{\n size_t leftIdx = left;\n size_t rightIdx = right;\n\n while (rightIdx &gt; leftIdx)\n {\n if (rightIdx - leftIdx &gt; 600)\n {\n size_t range = rightIdx - leftIdx + 1;\n long long i = n - (long long)leftIdx + 1;\n long long z = log(range);\n long long s = 0.5 * exp(2 * z / 3);\n long long sd = 0.5 * sqrt(z * s * (range - s) / range) * sgn(i - (long long)range / 2);\n\n size_t newLeft = fmax(leftIdx, n - i * s / range + sd);\n size_t newRight = fmin(rightIdx, n + (range - i) * s / range + sd);\n\n _FRselect(data, newLeft, newRight, n);\n }\n T t = data[n];\n size_t i = leftIdx;\n size_t j = rightIdx;\n // arrange pivot and right index\n std::swap(data[leftIdx], data[n]);\n if (data[rightIdx] &gt; t)\n std::swap(data[rightIdx], data[leftIdx]);\n\n while (i &lt; j)\n {\n std::swap(data[i], data[j]);\n ++i; --j;\n while (data[i] &lt; t) ++i;\n while (data[j] &gt; t) --j;\n }\n\n if (data[leftIdx] == t)\n std::swap(data[leftIdx], data[j]);\n else\n {\n ++j;\n std::swap(data[j], data[rightIdx]);\n }\n // adjust left and right towards the boundaries of the subset\n // containing the (k - left + 1)th smallest element\n if (j &lt;= n)\n leftIdx = j + 1;\n if (n &lt;= j)\n rightIdx = j - 1;\n }\n\n return data[leftIdx];\n}\n\ntemplate &lt;typename T&gt;\nint sgn(T val) {\n return (T(0) &lt; val) - (val &lt; T(0));\n}\n</code></pre>\n" }, { "answer_id": 69081325, "author": "Chandrakesha Rao", "author_id": 12041867, "author_profile": "https://Stackoverflow.com/users/12041867", "pm_score": -1, "selected": false, "text": "<pre><code><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function nthMax(arr, nth = 1, maxNumber = Infinity) {\n let large = -Infinity;\n for(e of arr) {\n if(e &gt; large &amp;&amp; e &lt; maxNumber ) {\n large = e;\n } else if (maxNumber == large) {\n nth++;\n }\n }\n return nth==0 ? maxNumber: nthMax(arr, nth-1, large);\n }\n\n let array = [11,12,12,34,23,34];\n\n let secondlargest = nthMax(array, 1);\n\n console.log(\"Number:\", secondlargest);</code></pre>\r\n</div>\r\n</div>\r\n\n\n \n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I believe there's a way to find the kth largest element in an unsorted array of length n in O(n). Or perhaps it's "expected" O(n) or something. How can we do this?
This is called finding the **k-th order statistic**. There's a very simple randomized algorithm (called *quickselect*) taking `O(n)` average time, `O(n^2)` worst case time, and a pretty complicated non-randomized algorithm (called *introselect*) taking `O(n)` worst case time. There's some info on [Wikipedia](http://en.wikipedia.org/wiki/Selection_algorithm), but it's not very good. Everything you need is in [these powerpoint slides](http://web.archive.org/web/20160402214842/http://c3p0demo.googlecode.com/svn/trunk/scalaDemo/script/Order_statistics.ppt). Just to extract the basic algorithm of the `O(n)` worst-case algorithm (introselect): ``` Select(A,n,i): Divide input into ⌈n/5⌉ groups of size 5. /* Partition on median-of-medians */ medians = array of each group’s median. pivot = Select(medians, ⌈n/5⌉, ⌈n/10⌉) Left Array L and Right Array G = partition(A, pivot) /* Find ith element in L, pivot, or G */ k = |L| + 1 If i = k, return pivot If i < k, return Select(L, k-1, i) If i > k, return Select(G, n-k, i-k) ``` It's also very nicely detailed in the Introduction to Algorithms book by Cormen et al.
251,791
<p>I need to use JUnit 4.4 (or newer) in a set of eclipse plugin tests, but I've run into the following problem:</p> <p>Tests are not detected when running with the junit 4.4 or 4.5 bundles from springsource (<a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&amp;version=4.4.0" rel="nofollow noreferrer">junit44</a> and <a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&amp;version=4.5.0&amp;searchType=bundlesByName&amp;searchQuery=junit" rel="nofollow noreferrer">junit45</a>). The org.junit4 bundle that can be obtained with eclipse supplies junit 4.3 (as of Ganymead / Eclipse 3.4). The org.junit4 bundle <em>does</em> work in that it identifies and runs the tests, but it is not compatible with the latest versions of JMock, and I need to use a mocking library.</p> <p>Here is a sample test:</p> <pre><code>package testingplugin; import static org.junit.Assert.*; import org.junit.Test; public class ActivatorTest { @Test public final void testDoaddTest() { fail("Not yet implemented"); } } </code></pre> <p>When running this test, I receive the following exception:</p> <pre><code>java.lang.Exception: No runnable methods at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:33) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:62) at org.eclipse.pde.internal.junit.runtime.CoreTestApplication.run(CoreTestApplication.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:574) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:195) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504) at org.eclipse.equinox.launcher.Main.run(Main.java:1236) at org.eclipse.equinox.launcher.Main.main(Main.java:1212) </code></pre> <p>However, if I switch the project dependencies from com.springsource.org.junit to org.junit4, then the test runs and fails (as expected).</p> <p>I am running the test as a JUnit Plug-in Test in Eclipse, with the following program arguments:</p> <p>-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}</p> <p>The following plug-ins selected during launch (selected by me, then I used "add required plugins" to get the rest of the dependencies.):</p> <pre><code>Workspace: testingPlugin Target Platform: com.springsource.org.hamcrest.core (1.1.0) com.springsource.org.junit (4.5.0) ....and a bunch of others... (nothing related to testing was auto-selected) </code></pre> <p>Here is my MANIFEST.MF:</p> <pre><code>Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: TestingPlugin Plug-in Bundle-SymbolicName: testingPlugin Bundle-Version: 1.0.0 Bundle-Activator: testingplugin.Activator Import-Package: org.osgi.framework;version="1.3.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: com.springsource.org.junit;bundle-version="4.5.0" </code></pre> <p>Switching the last line to:</p> <pre><code>Require-Bundle: org.junit4;bundle-version="4.3.1" </code></pre> <p>And updating the selected plugins at launch to:</p> <pre><code>Workspace: testingPlugin Target Platform: org.junit4 (4.3.1) ...bunches of auto-selected bundles... (again, nothing else test related) </code></pre> <p>Causes the test to run properly (but with the wrong version of junit).</p>
[ { "answer_id": 261242, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "<p>I don't know which version of JUnit it was, but to succesfully find test the test methods name must start with the word \"<strong>test</strong>\".</p>\n\n<p>In newer version you can simply mark test with @Test, \nfor me it works in this combination:</p>\n\n<pre><code>import static junit.framework.Assert.*;\n...\n@Test\n public void testDummy() throws Exception\n</code></pre>\n" }, { "answer_id": 316645, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe your JUnit bundle is missing an entry in the MANIFEST.MF:</p>\n\n<p>Dynamic-Import-Package: *</p>\n\n<p>This is mandatory to load classes from other bundles.</p>\n\n<p>Bebbo</p>\n" }, { "answer_id": 316689, "author": "shsmurfy", "author_id": 2188962, "author_profile": "https://Stackoverflow.com/users/2188962", "pm_score": 0, "selected": false, "text": "<p>ActivatorTest needs to extend TestCase</p>\n" }, { "answer_id": 358705, "author": "Thomas Dufour", "author_id": 371593, "author_profile": "https://Stackoverflow.com/users/371593", "pm_score": 2, "selected": false, "text": "<p>I cannot test this right now as I don't have an Eclipse 3.4 installation handy, but I've run across a similar problem a while ago in (I think) IntelliJ IDEA 7.0.x, and a workaround was to explicitly specify a test runner. </p>\n\n<p>With JUnit 4.5:</p>\n\n<pre><code>import org.junit.runners.JUnit4;\n\n@RunWith(JUnit4.class)\npublic class ActivatorTest {\n //...\n}\n</code></pre>\n\n<p>If this does not work you may have more success with <code>org.junit.runners.BlockJUnit4ClassRunner</code></p>\n\n<p>For JUnit 4.4 I would try <code>org.junit.internal.runners.JUnit4ClassRunner</code></p>\n\n<p>EDIT : not too sure about the <code>com.springsource.</code> part as I don't use Springsource. From your question it seems that springsource repackages JUnit under <code>com.springsource.org.junit</code> but you use just <code>org.junit</code> in your code so I'll stick with that.</p>\n" }, { "answer_id": 494851, "author": "Volker Stolz", "author_id": 60462, "author_profile": "https://Stackoverflow.com/users/60462", "pm_score": 1, "selected": false, "text": "<p>I'm wondering whether you might need to import the @Test tag from com.springsource.org.junit and not from org.junit.</p>\n\n<p>Volker</p>\n" }, { "answer_id": 522640, "author": "James Mead", "author_id": 2025138, "author_profile": "https://Stackoverflow.com/users/2025138", "pm_score": 1, "selected": false, "text": "<p>I had some similar sounding problems with jMock, JUnit &amp; Eclipse <a href=\"http://blog.floehopper.org/articles/2009/01/22/climbing-back-onto-the-java-horse\" rel=\"nofollow noreferrer\">recently</a>, although admittedly not with <em>plugin</em> tests.</p>\n\n<p>I'm not sure if it's relevant, but I got it all working with the following versions :-</p>\n\n<ul>\n<li>jmock-2.5.1.jar</li>\n<li>hamcrest-core-1.1.jar</li>\n<li>hamcrest-library-1.1.jar</li>\n<li>jmock-junit4-2.5.1.jar</li>\n</ul>\n\n<p>I also found I had to use the <a href=\"http://www.jmock.org/javadoc/2.5.1/org/jmock/integration/junit4/JMock.html\" rel=\"nofollow noreferrer\">JMock test runner</a> like this :-</p>\n\n<pre><code> import org.junit.Test;\n import org.junit.runner.RunWith;\n\n import org.jmock.Mockery;\n import org.jmock.Expectations;\n import org.jmock.integration.junit4.JUnit4Mockery;\n import org.jmock.integration.junit4.JMock;\n\n @RunWith(JMock.class)\n public class PublisherTest {\n\n Mockery context = new JUnit4Mockery();\n\n @Test \n public void oneSubscriberReceivesAMessage() {\n</code></pre>\n" }, { "answer_id": 892198, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@RunWith(Suite.class)\n@SuiteClasses( { UserServiceTest.class,ABCServiceTest.class })</p>\n\n<p>public class AllTestSuite {</p>\n\n<p>public static Test suite() {</p>\n\n<pre><code> return new JUnit4TestAdapter(AllTestSuite .class);\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 892447, "author": "ssmithstone", "author_id": 100165, "author_profile": "https://Stackoverflow.com/users/100165", "pm_score": 0, "selected": false, "text": "<p>I think the spring testing framework is not compatible with junit 4.4+</p>\n" }, { "answer_id": 939288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In my experience this happens if the plugin which contains the plugin tests does not depend on junit. After adding the junit 4.4 dependency to my MANIFEST.MF file the error went away and all tests were executed. The junit dependency should be optional because the plugin usually only needs it for the test code.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
I need to use JUnit 4.4 (or newer) in a set of eclipse plugin tests, but I've run into the following problem: Tests are not detected when running with the junit 4.4 or 4.5 bundles from springsource ([junit44](http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&version=4.4.0) and [junit45](http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&version=4.5.0&searchType=bundlesByName&searchQuery=junit)). The org.junit4 bundle that can be obtained with eclipse supplies junit 4.3 (as of Ganymead / Eclipse 3.4). The org.junit4 bundle *does* work in that it identifies and runs the tests, but it is not compatible with the latest versions of JMock, and I need to use a mocking library. Here is a sample test: ``` package testingplugin; import static org.junit.Assert.*; import org.junit.Test; public class ActivatorTest { @Test public final void testDoaddTest() { fail("Not yet implemented"); } } ``` When running this test, I receive the following exception: ``` java.lang.Exception: No runnable methods at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:33) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:62) at org.eclipse.pde.internal.junit.runtime.CoreTestApplication.run(CoreTestApplication.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:574) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:195) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504) at org.eclipse.equinox.launcher.Main.run(Main.java:1236) at org.eclipse.equinox.launcher.Main.main(Main.java:1212) ``` However, if I switch the project dependencies from com.springsource.org.junit to org.junit4, then the test runs and fails (as expected). I am running the test as a JUnit Plug-in Test in Eclipse, with the following program arguments: -os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl} The following plug-ins selected during launch (selected by me, then I used "add required plugins" to get the rest of the dependencies.): ``` Workspace: testingPlugin Target Platform: com.springsource.org.hamcrest.core (1.1.0) com.springsource.org.junit (4.5.0) ....and a bunch of others... (nothing related to testing was auto-selected) ``` Here is my MANIFEST.MF: ``` Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: TestingPlugin Plug-in Bundle-SymbolicName: testingPlugin Bundle-Version: 1.0.0 Bundle-Activator: testingplugin.Activator Import-Package: org.osgi.framework;version="1.3.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: com.springsource.org.junit;bundle-version="4.5.0" ``` Switching the last line to: ``` Require-Bundle: org.junit4;bundle-version="4.3.1" ``` And updating the selected plugins at launch to: ``` Workspace: testingPlugin Target Platform: org.junit4 (4.3.1) ...bunches of auto-selected bundles... (again, nothing else test related) ``` Causes the test to run properly (but with the wrong version of junit).
I cannot test this right now as I don't have an Eclipse 3.4 installation handy, but I've run across a similar problem a while ago in (I think) IntelliJ IDEA 7.0.x, and a workaround was to explicitly specify a test runner. With JUnit 4.5: ``` import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ActivatorTest { //... } ``` If this does not work you may have more success with `org.junit.runners.BlockJUnit4ClassRunner` For JUnit 4.4 I would try `org.junit.internal.runners.JUnit4ClassRunner` EDIT : not too sure about the `com.springsource.` part as I don't use Springsource. From your question it seems that springsource repackages JUnit under `com.springsource.org.junit` but you use just `org.junit` in your code so I'll stick with that.
251,806
<p>I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing?</p> <pre><code>public class SomeClass: ISomeInterface { MyAttribute GetAttribute() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true); if (attributes.Count() == 0) throw new Exception("could not find MyAttribute defined for " + methodBase.Name); return attributes[0] as MyAttribute; } void DoSomething() { MyAttribute ma = GetAttribute(); string s = ma.SomeProperty; } } </code></pre>
[ { "answer_id": 251827, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method \"Foo\" can implement an interface method \"Bar\". To do this, you would need to investigate the interface map:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\ninterface IFoo\n{\n void AAA(); // just to push Bar to index 1\n [Description(\"abc\")]\n void Bar();\n}\nclass Foo : IFoo\n{\n public void AAA() { } // just to satisfy interface\n static void Main()\n {\n IFoo foo = new Foo();\n foo.Bar();\n }\n void IFoo.Bar()\n {\n GetAttribute();\n }\n\n void GetAttribute()\n { // simplified just to obtain the [Description]\n\n StackTrace stackTrace = new StackTrace();\n StackFrame stackFrame = stackTrace.GetFrame(1);\n MethodBase classMethod = stackFrame.GetMethod();\n InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));\n int index = Array.IndexOf(map.TargetMethods, classMethod);\n MethodBase iMethod = map.InterfaceMethods[index];\n string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;\n }\n}\n</code></pre>\n" }, { "answer_id": 251857, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 0, "selected": false, "text": "<p>While I will first confess that I have never tried to attach attributes to Interfaces but would something like the following work for you?</p>\n\n<pre><code>public abstract class SomeBaseClass: ISomeInterface\n{\n [MyAttribute]\n abstract void MyTestMethod();\n\n\n}\n\npublic SomeClass : SomeBaseClass{\n\n MyAttribute GetAttribute(){\n Type t = GetType();\n object[] attibutes = t.GetCustomAttributes(typeof(MyAttribute), false);\n\n if (attributes.Count() == 0)\n throw new Exception(\"could not find MyAttribute defined for \" + methodBase.Name);\n return attributes[0] as MyAttribute;\n }\n\n\n ....\n}\n</code></pre>\n" }, { "answer_id": 253602, "author": "Thad", "author_id": 24500, "author_profile": "https://Stackoverflow.com/users/24500", "pm_score": 2, "selected": false, "text": "<p>Mark's method will work for non-generic interfaces. But it appears that I am dealing with some that have generics</p>\n\n<pre><code>interface IFoo&lt;T&gt; {}\nclass Foo&lt;T&gt;: IFoo&lt;T&gt;\n{\n T Bar()\n}\n</code></pre>\n\n<p>It appears that the T is replaced with the actual classType in the map.TargetMethods.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24500/" ]
I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing? ``` public class SomeClass: ISomeInterface { MyAttribute GetAttribute() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true); if (attributes.Count() == 0) throw new Exception("could not find MyAttribute defined for " + methodBase.Name); return attributes[0] as MyAttribute; } void DoSomething() { MyAttribute ma = GetAttribute(); string s = ma.SomeProperty; } } ```
The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method "Foo" can implement an interface method "Bar". To do this, you would need to investigate the interface map: ``` using System; using System.ComponentModel; using System.Diagnostics; using System.Reflection; interface IFoo { void AAA(); // just to push Bar to index 1 [Description("abc")] void Bar(); } class Foo : IFoo { public void AAA() { } // just to satisfy interface static void Main() { IFoo foo = new Foo(); foo.Bar(); } void IFoo.Bar() { GetAttribute(); } void GetAttribute() { // simplified just to obtain the [Description] StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase classMethod = stackFrame.GetMethod(); InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo)); int index = Array.IndexOf(map.TargetMethods, classMethod); MethodBase iMethod = map.InterfaceMethods[index]; string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description; } } ```
251,807
<p>I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly.</p> <p>I want to programmatically generate a project for the application. The <code>.project</code> and <code>.classpath</code> files are easy enough to figure out, and I've learned that projects are stored in the workspace under <code>&lt;workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects</code></p> <p>Unfortunately, some of the files under here (particularly <code>.location</code>) seem to be encoded in some kind of binary format. On a hunch I tried to deserialize it using <code>ObjectInputStream</code> - no dice. So it doesn't appear to be a serialized java object.</p> <p>My question is: is there a way to generate these files automatically?</p> <p>For the curious, the error I get trying to deserialize the <code>.location</code> file is the following:</p> <p><code>java.io.StreamCorruptedException: java.io.StreamCorruptedException: invalid stream header: 40B18B81</code></p> <p><strong>Update:</strong> My goal here is to be able to replace the New Java Project wizard with a command-line script or program. The reason is the application in question is actually a very large J2EE/weblogic application, which I like to break down into a largish (nearly 20) collection of subprojects. Complicating matters, we use clearcase for SCM and create a new branch for every release. This means I need to recreate these projects for every development view (branch) I create. This happens often enough to automate.</p>
[ { "answer_id": 252168, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 5, "selected": true, "text": "<p>You should be able to accomplish this by writing a small Eclipse plugin. You could even extend it out to being a \"headless\" RCP app, and pass in the command line arguments you need.</p>\n\n<p>The barebones code to create a project is:</p>\n\n<pre><code>IProgressMonitor progressMonitor = new NullProgressMonitor();\nIWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();\nIProject project = root.getProject(\"DesiredProjectName\");\nproject.create(progressMonitor);\nproject.open(progressMonitor);\n</code></pre>\n\n<p>Just take a look at the eclipse code for the Import Project wizard to give you a better idea of where to go with it.</p>\n" }, { "answer_id": 252182, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://ant-eclipse.sourceforge.net\" rel=\"nofollow noreferrer\">AntEclipse</a></p>\n\n<p>It can create eclipse projects from ant.</p>\n" }, { "answer_id": 63685295, "author": "mikolayek", "author_id": 3115384, "author_profile": "https://Stackoverflow.com/users/3115384", "pm_score": 0, "selected": false, "text": "<p>To create java project you can use JavaCore from <code>org.eclipse.jdt.core.JavaCore</code>. As a <code>sourceProject</code> you can use generic project item, which has been suggested by @James Van Huis</p>\n<pre class=\"lang-java prettyprint-override\"><code>IJavaProject javaSourceProject = JavaCore.create(sourceProject);\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly. I want to programmatically generate a project for the application. The `.project` and `.classpath` files are easy enough to figure out, and I've learned that projects are stored in the workspace under `<workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects` Unfortunately, some of the files under here (particularly `.location`) seem to be encoded in some kind of binary format. On a hunch I tried to deserialize it using `ObjectInputStream` - no dice. So it doesn't appear to be a serialized java object. My question is: is there a way to generate these files automatically? For the curious, the error I get trying to deserialize the `.location` file is the following: `java.io.StreamCorruptedException: java.io.StreamCorruptedException: invalid stream header: 40B18B81` **Update:** My goal here is to be able to replace the New Java Project wizard with a command-line script or program. The reason is the application in question is actually a very large J2EE/weblogic application, which I like to break down into a largish (nearly 20) collection of subprojects. Complicating matters, we use clearcase for SCM and create a new branch for every release. This means I need to recreate these projects for every development view (branch) I create. This happens often enough to automate.
You should be able to accomplish this by writing a small Eclipse plugin. You could even extend it out to being a "headless" RCP app, and pass in the command line arguments you need. The barebones code to create a project is: ``` IProgressMonitor progressMonitor = new NullProgressMonitor(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject("DesiredProjectName"); project.create(progressMonitor); project.open(progressMonitor); ``` Just take a look at the eclipse code for the Import Project wizard to give you a better idea of where to go with it.
251,814
<p>I've been struggling lately with understanding the best way to organize jQuery code. I asked another question earlier and I don't think I was specific enough (<a href="https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess">found in this question here</a>).</p> <p>My problem is that the richer you make an application, the quicker your client side gets out of control. Consider this situation...</p> <pre><code>//Let's start some jQuery $(function() { var container = $("#inputContainer"); //Okay let's list text fields that can be updated for(var i=0; i &lt; 5; i++) { //okay let's add an event for when a field changes $("&lt;input/&gt;").change(function() { //okay something changed, let's update the server $.ajax({ success:function(data) { //Okay - no problem from the server... let's update //the bindings on our input fields $.each(container.children(), function(j,w) { //YIKES!! We're deep in here now!! $(w).unbind().change(function() { //Then insanity starts... }); // end some function }); //end some loop } // what was this again? }); //ending something... not sure anymore }).appendTo(container); //input added to the page... logic WAY split apart }; //the first loop - whew! almost out! }); //The start of the code!! </code></pre> <p>Now this situation isn't too far from impossible. I'm not saying this is the right way to do it, but it's not uncommon to find yourself several levels down into a jQuery command and starting to wonder how much more logic can add before the screen begins to melt.</p> <p><strong>My question is how are people managing this or organizing to limit the complexity of their code?</strong></p> <p><em><a href="https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess#247382">I listed how I'm doing it in my other post</a>...</em></p>
[ { "answer_id": 251848, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "<p>Stick some of the anon functions into global scope functions (or your own \"namespace\" object), especially the re-used functions, and it begins to look less like what you posted. Kind of like what you linked to.</p>\n" }, { "answer_id": 251854, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<p>Well, for one, having a good IDE that understands javascript can help tremendously, even if just to identify matching demarcations (braces, parens, etc).</p>\n\n<p>If your code starts to really get that complex, consider making your own static object to organize the mess - you don't have to work so hard to keep everything anonymous.</p>\n\n<pre><code>var aCustomObject = {\n container: $(\"#inputContainer\"),\n initialize: function()\n {\n for(var i=0; i &lt; 5; i++)\n {\n $(\"&lt;input/&gt;\").changed( aCustomObject.changeHandler );\n }\n },\n changeHandler: function( event )\n {\n $.ajax( {success: aCustomObject.ajaxSuccessHandler} );\n },\n ajaxSuccessHandler: function( data )\n {\n $.each( aCustomObject.container.children(), aCustomObject.updateBindings )\n },\n updateBindings: function( j, w )\n {\n $(w).unbind().changed( function(){} );\n }\n}\naCustomObject.initialize();\n</code></pre>\n" }, { "answer_id": 251864, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 4, "selected": false, "text": "<p>So far, I do it like this:</p>\n\n<pre><code>// initial description of this code block\n$(function() { \n var container = $(\"#inputContainer\");\n\n for(var i=0; i &lt; 5; i++) {\n $(\"&lt;input/&gt;\").changed(inputChanged).appendTo(container);\n }; \n\n function inputChanged() {\n $.ajax({\n success: inputChanged_onSuccess\n });\n } \n\n function inputChanged_onSuccess(data) {\n $.each(container.children(), function(j,w) {\n $(w).unbind().changed(function() {\n //replace the insanity with another refactored function\n });\n });\n }\n});\n</code></pre>\n\n<p>In JavaScript, functions are first-class objects and can thus be used as variables.</p>\n" }, { "answer_id": 252060, "author": "user32924", "author_id": 32924, "author_profile": "https://Stackoverflow.com/users/32924", "pm_score": 2, "selected": false, "text": "<p>In my opinion the method described by BaileyP is what I use to start off with then I normally abstract everything into more re-usable chunks, especially when some functionality expands to the point where it's easier to abstract it into a plugin then have it specific to one site.</p>\n\n<p>As long as you keep the large blocks of code in a seperate file and coded nicely you can then end up with some really clean syntax.</p>\n\n<pre><code>// Page specific code\njQuery(function() {\n for(var i = 0; i &lt; 5; i++) {\n $(\"&lt;input/&gt;\").bindWithServer(\"#inputContainer\");\n }\n});\n\n// Nicely abstracted code\njQuery.fn.bindWithServer = function(container) {\n this.change(function() {\n jQuery.ajax({\n url: 'http://example.com/',\n success: function() { jQuery(container).unbindChildren(); }\n });\n });\n}\njQuery.fn.unbindChildren = function() {\n this.children().each(function() {\n jQuery(this).unbind().change(function() {});\n });\n}\n</code></pre>\n" }, { "answer_id": 255222, "author": "John Resig", "author_id": 6524, "author_profile": "https://Stackoverflow.com/users/6524", "pm_score": 6, "selected": false, "text": "<p>Just want to add to what was mentioned previously that this:</p>\n\n<pre><code>$.each(container.children(), function(j,w) {\n $(w).unbind().change(function() { ... });\n});\n</code></pre>\n\n<p>can be optimized to:</p>\n\n<pre><code>container.children().unbind().change(function() { ... });\n</code></pre>\n\n<p>It's all about chaining, a great way to simplify your code.</p>\n" }, { "answer_id": 285309, "author": "Jason Moore", "author_id": 18158, "author_profile": "https://Stackoverflow.com/users/18158", "pm_score": 2, "selected": false, "text": "<p>I described my approach <a href=\"https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess#284700\">in your other post</a>. Short form:</p>\n\n<ul>\n<li>do not mix javascript and HTML</li>\n<li>use classes (basically start to see your application as a collection of widgets)</li>\n<li>only have a single $(document).ready(...) block</li>\n<li>send jQuery instances into your classes (instead of using plugins)</li>\n</ul>\n" }, { "answer_id": 2185057, "author": "Irfan", "author_id": 236324, "author_profile": "https://Stackoverflow.com/users/236324", "pm_score": 2, "selected": false, "text": "<p>Somebody wrote a post on the similar topic.</p>\n\n<p><a href=\"http://weblogs.asp.net/stevewellens/archive/2010/01/25/jquery-code-does-not-have-to-be-ugly.aspx\" rel=\"nofollow noreferrer\">jQuery Code Does not have to be Ugly</a></p>\n\n<p>For instance, the author, Steve Wellens, suggests to not use anonymous functions, as it makes code harder to read. Instead, push the function reference into the jQuery methods, like so:</p>\n\n<pre><code>$(document).ready(DocReady);\n\nfunction DocReady()\n{ \n AssignClickToToggleButtons();\n ColorCodeTextBoxes();\n}\n</code></pre>\n\n<p>Another takeaway from the article is to assign a jQuery object to a concrete variable, which makes the code look cleaner, less dependent on the actual jQuery object, and easier to tell what a certain line of code is doing:</p>\n\n<pre><code>function ColorCodeTextBoxes()\n{\n var TextBoxes = $(\":text.DataEntry\");\n\n TextBoxes.each(function()\n {\n if (this.value == \"\")\n this.style.backgroundColor = \"yellow\";\n else\n this.style.backgroundColor = \"White\";\n });\n}\n</code></pre>\n" }, { "answer_id": 4039418, "author": "Aldo Bucchi", "author_id": 489611, "author_profile": "https://Stackoverflow.com/users/489611", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://coffeescript.com/\" rel=\"nofollow\">http://coffeescript.com/</a> ;)</p>\n\n<pre>\n$ ->\n container = $ '#inputContainer'\n for i in [0...5]\n $('&lt;input/&gt;').change ->\n $.ajax success: (data) ->\n for w in container.children()\n $(w).unbind().change ->\n alert 'duh'\n</pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
I've been struggling lately with understanding the best way to organize jQuery code. I asked another question earlier and I don't think I was specific enough ([found in this question here](https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess)). My problem is that the richer you make an application, the quicker your client side gets out of control. Consider this situation... ``` //Let's start some jQuery $(function() { var container = $("#inputContainer"); //Okay let's list text fields that can be updated for(var i=0; i < 5; i++) { //okay let's add an event for when a field changes $("<input/>").change(function() { //okay something changed, let's update the server $.ajax({ success:function(data) { //Okay - no problem from the server... let's update //the bindings on our input fields $.each(container.children(), function(j,w) { //YIKES!! We're deep in here now!! $(w).unbind().change(function() { //Then insanity starts... }); // end some function }); //end some loop } // what was this again? }); //ending something... not sure anymore }).appendTo(container); //input added to the page... logic WAY split apart }; //the first loop - whew! almost out! }); //The start of the code!! ``` Now this situation isn't too far from impossible. I'm not saying this is the right way to do it, but it's not uncommon to find yourself several levels down into a jQuery command and starting to wonder how much more logic can add before the screen begins to melt. **My question is how are people managing this or organizing to limit the complexity of their code?** *[I listed how I'm doing it in my other post](https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess#247382)...*
Just want to add to what was mentioned previously that this: ``` $.each(container.children(), function(j,w) { $(w).unbind().change(function() { ... }); }); ``` can be optimized to: ``` container.children().unbind().change(function() { ... }); ``` It's all about chaining, a great way to simplify your code.
251,834
<p>Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length?</p> <p>ie. assuming val1 is the string I'm comparing:</p> <pre><code>0 : { val1 = "a" } 1 : { val1 = "aa" } 2 : { val1 = "aba" } 3 : { val1 = "c" } </code></pre> <p>what needs to be returned is object 2 because "aba" has the greatest length.</p>
[ { "answer_id": 251858, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<p>Sorry, I'll try again. You can use the following aggregation:</p>\n\n<pre><code>Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length &gt; b.val1.Length, a, b))\n</code></pre>\n" }, { "answer_id": 251860, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 0, "selected": false, "text": "<p>You could also use an order-by:</p>\n\n<pre><code>var x = myStringArray.OrderBy(s =&gt; s.Length).Last();\n</code></pre>\n" }, { "answer_id": 1054690, "author": "Joe Chung", "author_id": 86483, "author_profile": "https://Stackoverflow.com/users/86483", "pm_score": 0, "selected": false, "text": "<pre><code>Dim longestLength = elements.Max(Function(el) el.val1.Length)\nDim longest = elements.First(Function(el) el.val1.Length = longestLength)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847/" ]
Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length? ie. assuming val1 is the string I'm comparing: ``` 0 : { val1 = "a" } 1 : { val1 = "aa" } 2 : { val1 = "aba" } 3 : { val1 = "c" } ``` what needs to be returned is object 2 because "aba" has the greatest length.
Sorry, I'll try again. You can use the following aggregation: ``` Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length > b.val1.Length, a, b)) ```
251,842
<p>I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem? </p> <p>[Update] Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.</p>
[ { "answer_id": 251873, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>You can use the RegularExpressionValidator with the ValidationExpression property set to</p>\n\n<p>Edit: (whoops, 650 and 201 etc. were valid with the old pattern)</p>\n\n<pre><code>^(1\\d{2}|200|5\\d{2}|600)$\n</code></pre>\n\n<p>This will test the entered text for 100-200 and 500-600.</p>\n" }, { "answer_id": 251876, "author": "Kyle B.", "author_id": 6158, "author_profile": "https://Stackoverflow.com/users/6158", "pm_score": 1, "selected": false, "text": "<p>I do not believe this is possible using the standard RangeValidator control.</p>\n\n<p>I did some searching and I believe your best solution is going to be to create your own CustomValidator control which you can include in your project to handle this scenario.</p>\n\n<p><a href=\"http://www.dotnetjunkies.ddj.com/Article/592CE980-FB7E-4DF7-9AC1-FDD572776680.dcik\" rel=\"nofollow noreferrer\">http://www.dotnetjunkies.ddj.com/Article/592CE980-FB7E-4DF7-9AC1-FDD572776680.dcik</a></p>\n\n<p>You shouldn't have to compile it just to use it in your project, as long as you reference it properly.</p>\n" }, { "answer_id": 251881, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "<p>A CustomValidator should work. I'm not sure what you mean by \"pass the 2 ranges values from the server-side\". You could validate it on the server-side using a validation method like this:</p>\n\n<pre><code>void ValidateRange(object sender, ServerValidateEventArgs e)\n{\n int input;\n bool parseOk = int.TryParse(e.Value, out input);\n e.IsValid = parseOk &amp;&amp;\n ((input &gt;= 100 || input &lt;= 200) ||\n (input &gt;= 500 || input &lt;= 600));\n}\n</code></pre>\n\n<p>You will then need to set the OnServerValidate property of your CustomValidator to \"ValidateRange\", or whatever you happen to call it.</p>\n\n<p>Is this the sort of thing you're after?</p>\n" }, { "answer_id": 252556, "author": "HashName", "author_id": 28773, "author_profile": "https://Stackoverflow.com/users/28773", "pm_score": 1, "selected": true, "text": "<p>I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it.</p>\n\n<pre><code> public class RangeValidatorEx : BaseValidator\n{\n\n protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)\n {\n base.AddAttributesToRender(writer);\n\n if (base.RenderUplevel)\n {\n string clientId = this.ClientID;\n\n // The attribute evaluation funciton holds the name of client-side js function.\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"evaluationfunction\", \"RangeValidatorEx\");\n\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range1High\", this.Range1High.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range2High\", this.Range2High.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range1Low\", this.Range1Low.ToString());\n Page.ClientScript.RegisterExpandoAttribute(clientId, \"Range2Low\", this.Range2Low.ToString());\n\n }\n }\n\n // Will be invoked to validate the parameters \n protected override bool ControlPropertiesValid()\n {\n if ((Range1High &lt;= 0) || (this.Range1Low &lt;= 0) || (this.Range2High &lt;= 0) || (this.Range2Low &lt;= 0))\n throw new HttpException(\"The range values cannot be less than zero\");\n\n return base.ControlPropertiesValid();\n }\n\n // used to validation on server-side\n protected override bool EvaluateIsValid()\n {\n int code;\n if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code))\n return false;\n\n if ((code &lt; this.Range1High &amp;&amp; code &gt; this.Range1Low) || (code &lt; this.Range2High &amp;&amp; code &gt; this.Range2Low))\n return true;\n else\n return false;\n }\n\n // inject the client-side script to page\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (base.RenderUplevel)\n {\n this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), \"RangeValidatorEx\", RangeValidatorExJs(),true);\n }\n }\n\n\n string RangeValidatorExJs()\n {\n string js;\n // the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function.\n js = \"function RangeValidatorEx(val){ \"\n + \" var code=document.getElementById(val.controltovalidate).value; \"\n + \" if ((code &lt; rangeValidatorCtrl.Range1High &amp;&amp; code &gt; rangeValidatorCtrl.Range1Low ) || (code &lt; rangeValidatorCtrl.Range2High &amp;&amp; code &gt; rangeValidatorCtrl.Range2Low)) return true; else return false;}\";\n return js;\n }\n\n\n public int Range1Low\n {\n get {\n object obj2 = this.ViewState[\"Range1Low\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range1Low\"] = value; }\n }\n\n public int Range1High\n {\n get\n {\n object obj2 = this.ViewState[\"Range1High\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range1High\"] = value; }\n }\n public int Range2Low\n {\n get\n {\n object obj2 = this.ViewState[\"Range2Low\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range2Low\"] = value; }\n }\n public int Range2High\n {\n get\n {\n object obj2 = this.ViewState[\"Range2High\"];\n\n if (obj2 != null)\n return System.Convert.ToInt32(obj2);\n\n return 0;\n\n }\n set { this.ViewState[\"Range2High\"] = value; }\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28773/" ]
I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem? [Update] Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.
I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it. ``` public class RangeValidatorEx : BaseValidator { protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { base.AddAttributesToRender(writer); if (base.RenderUplevel) { string clientId = this.ClientID; // The attribute evaluation funciton holds the name of client-side js function. Page.ClientScript.RegisterExpandoAttribute(clientId, "evaluationfunction", "RangeValidatorEx"); Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1High", this.Range1High.ToString()); Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2High", this.Range2High.ToString()); Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1Low", this.Range1Low.ToString()); Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2Low", this.Range2Low.ToString()); } } // Will be invoked to validate the parameters protected override bool ControlPropertiesValid() { if ((Range1High <= 0) || (this.Range1Low <= 0) || (this.Range2High <= 0) || (this.Range2Low <= 0)) throw new HttpException("The range values cannot be less than zero"); return base.ControlPropertiesValid(); } // used to validation on server-side protected override bool EvaluateIsValid() { int code; if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code)) return false; if ((code < this.Range1High && code > this.Range1Low) || (code < this.Range2High && code > this.Range2Low)) return true; else return false; } // inject the client-side script to page protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (base.RenderUplevel) { this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RangeValidatorEx", RangeValidatorExJs(),true); } } string RangeValidatorExJs() { string js; // the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function. js = "function RangeValidatorEx(val){ " + " var code=document.getElementById(val.controltovalidate).value; " + " if ((code < rangeValidatorCtrl.Range1High && code > rangeValidatorCtrl.Range1Low ) || (code < rangeValidatorCtrl.Range2High && code > rangeValidatorCtrl.Range2Low)) return true; else return false;}"; return js; } public int Range1Low { get { object obj2 = this.ViewState["Range1Low"]; if (obj2 != null) return System.Convert.ToInt32(obj2); return 0; } set { this.ViewState["Range1Low"] = value; } } public int Range1High { get { object obj2 = this.ViewState["Range1High"]; if (obj2 != null) return System.Convert.ToInt32(obj2); return 0; } set { this.ViewState["Range1High"] = value; } } public int Range2Low { get { object obj2 = this.ViewState["Range2Low"]; if (obj2 != null) return System.Convert.ToInt32(obj2); return 0; } set { this.ViewState["Range2Low"] = value; } } public int Range2High { get { object obj2 = this.ViewState["Range2High"]; if (obj2 != null) return System.Convert.ToInt32(obj2); return 0; } set { this.ViewState["Range2High"] = value; } } } ```
251,850
<p>I'm using symfony and propel, and I'm trying to invoke a specific culture on an object and output some fields of that object to the screen in that specific culture. However, if the object's mapped database record doesn't have those fields in that specific culture, I would like it to default to the base culture (in this case, en_US)</p> <p>I'm doing it like this:</p> <pre><code>$currentLesson = $currentLesson-&gt;getCurrentLessonsI18n($lessonCulture); </code></pre> <p>But when I output such as this</p> <pre><code>$currentLesson-&gt;getTitle(); </code></pre> <p>It outputs an empty string if there is no culture record for it. My question is, is there a way to make an object default to a specific culuture if the one I specify isn't available, or is there a method to see if a specific object has a culture i18n record?</p> <p>something like this:</p> <pre><code>if($currentLesson-&gt;cultureExists($lessonCulture) $currentLesson = $currentLesson-&gt;getCurrentLessonsI18n($lessonCulture); </code></pre> <p>or</p> <pre><code>sfConfig::setPropelDefaultCulture("en_US"); </code></pre>
[ { "answer_id": 263772, "author": "Marek", "author_id": 34452, "author_profile": "https://Stackoverflow.com/users/34452", "pm_score": 2, "selected": true, "text": "<p>You will have to overwrite symfony itself to make it default to another language.\nTheres a good working solution here <a href=\"http://www.codemassacre.com/2008/03/10/symfony-default-language-fallback/\" rel=\"nofollow noreferrer\">http://www.codemassacre.com/2008/03/10/symfony-default-language-fallback/</a></p>\n" }, { "answer_id": 8790184, "author": "Bert-Jan de Lange", "author_id": 1138912, "author_profile": "https://Stackoverflow.com/users/1138912", "pm_score": 0, "selected": false, "text": "<p>The <code>i18n</code> record you get back from <code>getTranslation($language)</code> can be tested with <code>isNew()</code>, that will tell you if Propel has just made it up <code>(true)</code> or if it came from the database <code>(false)</code>.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53001/" ]
I'm using symfony and propel, and I'm trying to invoke a specific culture on an object and output some fields of that object to the screen in that specific culture. However, if the object's mapped database record doesn't have those fields in that specific culture, I would like it to default to the base culture (in this case, en\_US) I'm doing it like this: ``` $currentLesson = $currentLesson->getCurrentLessonsI18n($lessonCulture); ``` But when I output such as this ``` $currentLesson->getTitle(); ``` It outputs an empty string if there is no culture record for it. My question is, is there a way to make an object default to a specific culuture if the one I specify isn't available, or is there a method to see if a specific object has a culture i18n record? something like this: ``` if($currentLesson->cultureExists($lessonCulture) $currentLesson = $currentLesson->getCurrentLessonsI18n($lessonCulture); ``` or ``` sfConfig::setPropelDefaultCulture("en_US"); ```
You will have to overwrite symfony itself to make it default to another language. Theres a good working solution here <http://www.codemassacre.com/2008/03/10/symfony-default-language-fallback/>
251,851
<p>I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>Consider the DOS command FOR in a standard shell.</p>\n\n<pre><code>C:\\Documents and Settings\\Kenny&gt;help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "<p>Here is the Powershell way:</p>\n\n<pre><code>gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n</code></pre>\n\n<p>Or to make it a little more verbose and easier to understand:</p>\n\n<pre><code>Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n</code></pre>\n\n<p>EDIT: There is of course nothing wrong with the DOS way either. :)</p>\n\n<p>EDIT2: Powershell does support implicit (and explicit for that matter) line continuation and as Matt Hamilton's post shows it does make thing's easier to read.</p>\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<p>+1 to EBGreen, except that (at least on XP) the \"-exclude\" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says \"this parameter does not work properly in this cmdlet\"!</p>\n\n<p>So you can filter manually like this:</p>\n\n<pre><code>gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n</code></pre>\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "<p>Found this helpful while using PowerShell v4.</p>\n\n<pre class=\"lang-powershell prettyprint-override\"><code>Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?
+1 to EBGreen, except that (at least on XP) the "-exclude" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says "this parameter does not work properly in this cmdlet"! So you can filter manually like this: ``` gci | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") } | %{ ren -new ($_.Name + ".txt") } ```
251,861
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/174796/watermarked-textbox-for-compact-framework">Watermarked Textbox for Compact Framework</a> </p> </blockquote> <p>Using Visual Studio 2008 SP1, the latest Compact framework and Windows Mobile 5.</p> <p>I need to use DrawString to put a string over a TextBox. But as soon as I draw the string the TextBox Control just over writes it. (I Know because I drew slightly off the edge of the control and my text is half visible (where is is off the control) and half gone (where it is on the control.)</p> <p>Is there anyway I can get the TextBox to not refresh so I can keep my text there?</p> <p>NOTE: I have looked into subclassing TextBox and just having it paint my text. However, Paint events for the TextBox class are not catchable in the CompactFramework. If you know a way to be able to paint on the TextBox without the Paint events then I would love to subclass the TextBox class.</p> <p>--End of Question--</p> <p>Just in case you are wondering why I need to do this, here is what I am working on: I need to have a text box where a numeric value must be entered twice. I need some sort of clear clue that they have to enter the number again. I would like to have a slightly grayed out text appear over the text box telling the user to re-enter.</p> <p>I have tried using a label, a hyperlink label and another text box, but they obscure the text below (which has a default value that has to be partially visible).</p> <p>If anyone knows a different way cue for re-entry that would be great too!</p> <p>Vacano</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>Consider the DOS command FOR in a standard shell.</p>\n\n<pre><code>C:\\Documents and Settings\\Kenny&gt;help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "<p>Here is the Powershell way:</p>\n\n<pre><code>gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n</code></pre>\n\n<p>Or to make it a little more verbose and easier to understand:</p>\n\n<pre><code>Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n</code></pre>\n\n<p>EDIT: There is of course nothing wrong with the DOS way either. :)</p>\n\n<p>EDIT2: Powershell does support implicit (and explicit for that matter) line continuation and as Matt Hamilton's post shows it does make thing's easier to read.</p>\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<p>+1 to EBGreen, except that (at least on XP) the \"-exclude\" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says \"this parameter does not work properly in this cmdlet\"!</p>\n\n<p>So you can filter manually like this:</p>\n\n<pre><code>gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n</code></pre>\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "<p>Found this helpful while using PowerShell v4.</p>\n\n<pre class=\"lang-powershell prettyprint-override\"><code>Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16241/" ]
> > **Possible Duplicate:** > > [Watermarked Textbox for Compact Framework](https://stackoverflow.com/questions/174796/watermarked-textbox-for-compact-framework) > > > Using Visual Studio 2008 SP1, the latest Compact framework and Windows Mobile 5. I need to use DrawString to put a string over a TextBox. But as soon as I draw the string the TextBox Control just over writes it. (I Know because I drew slightly off the edge of the control and my text is half visible (where is is off the control) and half gone (where it is on the control.) Is there anyway I can get the TextBox to not refresh so I can keep my text there? NOTE: I have looked into subclassing TextBox and just having it paint my text. However, Paint events for the TextBox class are not catchable in the CompactFramework. If you know a way to be able to paint on the TextBox without the Paint events then I would love to subclass the TextBox class. --End of Question-- Just in case you are wondering why I need to do this, here is what I am working on: I need to have a text box where a numeric value must be entered twice. I need some sort of clear clue that they have to enter the number again. I would like to have a slightly grayed out text appear over the text box telling the user to re-enter. I have tried using a label, a hyperlink label and another text box, but they obscure the text below (which has a default value that has to be partially visible). If anyone knows a different way cue for re-entry that would be great too! Vacano
+1 to EBGreen, except that (at least on XP) the "-exclude" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says "this parameter does not work properly in this cmdlet"! So you can filter manually like this: ``` gci | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") } | %{ ren -new ($_.Name + ".txt") } ```
251,865
<p>For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed).</p> <p>The javascript code that receives the value is pretty standard:</p> <pre><code>//client code - javascript xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4) { var result = xmlHttp.responseText; alert(result); ... } ... } </code></pre> <p>To return the string, I originally had this in the server:</p> <pre><code>//server code - java myString = "..."; out.write(myString.getBytes("UTF-8")); </code></pre> <p>Which worked perfectly, if unsafe. Later, I replaced it with:</p> <pre><code>import org.apache.commons.lang.StringEscapeUtils; ... myString = "..."; out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8")); </code></pre> <p>But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ".</p> <p>For instance, using:</p> <pre><code>escapeJavaScript("años").getBytes("UTF-8"); </code></pre> <p>sends:</p> <pre><code>an\u00F1os </code></pre> <p>to the client.</p> <p>The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?</p>
[ { "answer_id": 251855, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>Consider the DOS command FOR in a standard shell.</p>\n\n<pre><code>C:\\Documents and Settings\\Kenny&gt;help for\nRuns a specified command for each file in a set of files.\n\nFOR %variable IN (set) DO command [command-parameters]\n\n %variable Specifies a single letter replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\n...\n\nIn addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n" }, { "answer_id": 251875, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "<p>Here is the Powershell way:</p>\n\n<pre><code>gci -ex \"*.xyz\" | ?{!$_.PsIsContainer} | ren -new {$_.name + \".txt\"}\n</code></pre>\n\n<p>Or to make it a little more verbose and easier to understand:</p>\n\n<pre><code>Get-ChildItem -exclude \"*.xyz\" \n | WHere-Object{!$_.PsIsContainer} \n | Rename-Item -newname {$_.name + \".txt\"}\n</code></pre>\n\n<p>EDIT: There is of course nothing wrong with the DOS way either. :)</p>\n\n<p>EDIT2: Powershell does support implicit (and explicit for that matter) line continuation and as Matt Hamilton's post shows it does make thing's easier to read.</p>\n" }, { "answer_id": 251886, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<p>+1 to EBGreen, except that (at least on XP) the \"-exclude\" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says \"this parameter does not work properly in this cmdlet\"!</p>\n\n<p>So you can filter manually like this:</p>\n\n<pre><code>gci \n | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(\".xyz\") } \n | %{ ren -new ($_.Name + \".txt\") }\n</code></pre>\n" }, { "answer_id": 30281035, "author": "Coding101", "author_id": 1277533, "author_profile": "https://Stackoverflow.com/users/1277533", "pm_score": 2, "selected": false, "text": "<p>Found this helpful while using PowerShell v4.</p>\n\n<pre class=\"lang-powershell prettyprint-override\"><code>Get-ChildItem -Path \"C:\\temp\" -Filter \"*.config\" -File | \n Rename-Item -NewName { $PSItem.Name + \".disabled\" }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed). The javascript code that receives the value is pretty standard: ``` //client code - javascript xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4) { var result = xmlHttp.responseText; alert(result); ... } ... } ``` To return the string, I originally had this in the server: ``` //server code - java myString = "..."; out.write(myString.getBytes("UTF-8")); ``` Which worked perfectly, if unsafe. Later, I replaced it with: ``` import org.apache.commons.lang.StringEscapeUtils; ... myString = "..."; out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8")); ``` But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ". For instance, using: ``` escapeJavaScript("años").getBytes("UTF-8"); ``` sends: ``` an\u00F1os ``` to the client. The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?
+1 to EBGreen, except that (at least on XP) the "-exclude" parameter to get-childitem doesn't seem to work. The help text (gci -?) actually says "this parameter does not work properly in this cmdlet"! So you can filter manually like this: ``` gci | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") } | %{ ren -new ($_.Name + ".txt") } ```
251,868
<p>I was watching <a href="http://channel9.msdn.com/pdc2008/TL16/" rel="noreferrer">Anders' talk about C# 4.0 and sneak preview of C# 5.0</a>, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?</p> <p>For example something like the <code>FileStream</code> class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an <code>IntPtr</code> and the ones from a <code>SafeFileHandle</code>.</p> <pre><code>FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool); </code></pre> <p>It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].</p> <p>What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?</p>
[ { "answer_id": 251883, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 4, "selected": false, "text": "<p>When a method overload normally performs the same thing with a different number of arguments then defaults will be used.</p>\n\n<p>When a method overload performs a function differently based on its parameters then overloading will continue to be used.</p>\n\n<p>I used optional back in my VB6 days and have since missed it, it will reduce a lot of XML comment duplication in C#.</p>\n" }, { "answer_id": 251893, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 2, "selected": false, "text": "<p>I'm looking forward to optional parameters because it keeps what the defaults are closer to the method. So instead of dozens of lines for the overloads that just call the \"expanded\" method, you just define the method once and you can see what the optional parameters default to in the method signature. I'd rather look at:</p>\n\n<pre><code>public Rectangle (Point start = Point.Zero, int width, int height)\n{\n Start = start;\n Width = width;\n Height = height;\n}\n</code></pre>\n\n<p>Instead of this:</p>\n\n<pre><code>public Rectangle (Point start, int width, int height)\n{\n Start = start;\n Width = width;\n Height = height;\n}\n\npublic Rectangle (int width, int height) :\n this (Point.Zero, width, height)\n{\n}\n</code></pre>\n\n<p>Obviously this example is really simple but the case in the OP with 5 overloads, things can get crowded real quick.</p>\n" }, { "answer_id": 251904, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>I'd consider the following:</p>\n\n<ul>\n<li>Do you need your code to be used from languages which don't support optional parameters? If so, consider including the overloads.</li>\n<li>Do you have any members on your team who violently oppose optional parameters? (Sometimes it's easier to live with a decision you don't like than to argue the case.)</li>\n<li>Are you confident that your defaults won't change between builds of your code, or if they might, will your callers be okay with that?</li>\n</ul>\n\n<p>I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to <code>const</code> fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.</p>\n" }, { "answer_id": 1039599, "author": "JP Alioto", "author_id": 86473, "author_profile": "https://Stackoverflow.com/users/86473", "pm_score": 3, "selected": false, "text": "<p>I will definitely be using the optional parameters feature of 4.0. It gets rid of the ridiculous ...</p>\n\n<pre><code>public void M1( string foo, string bar )\n{\n // do that thang\n}\n\npublic void M1( string foo )\n{\n M1( foo, \"bar default\" ); // I have always hated this line of code specifically\n}\n</code></pre>\n\n<p>... and puts the values right where the caller can see them ...</p>\n\n<pre><code>public void M1( string foo, string bar = \"bar default\" )\n{\n // do that thang\n}\n</code></pre>\n\n<p>Much more simple and much less error prone. I've actually seen this as a bug in the overload case ...</p>\n\n<pre><code>public void M1( string foo )\n{\n M2( foo, \"bar default\" ); // oops! I meant M1!\n}\n</code></pre>\n\n<p>I have not played with the 4.0 complier yet, but I would not be shocked to learn that the complier simply emits the overloads for you.</p>\n" }, { "answer_id": 1039609, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "<p>I've been using Delphi with optional parameters forever. I've switched to using overloads instead.</p>\n\n<p>Because when you go to create more overloads, you'll invariably conflict with an optional parameter form, and then you'll have to convert them to non-optional anyway.</p>\n\n<p>And I like the notion that there's generally one <em>super</em> method, and the rest are simpler wrappers around that one.</p>\n" }, { "answer_id": 2881191, "author": "mr.b", "author_id": 267491, "author_profile": "https://Stackoverflow.com/users/267491", "pm_score": 3, "selected": false, "text": "<p>It can be argued whether optional arguments or overloads should be used or not, but most importantly, each have their own area where they are irreplaceable.</p>\n\n<p>Optional arguments, when used in combination with named arguments, are extremely useful when combined with some long-argument-lists-with-all-optionals of COM calls.</p>\n\n<p>Overloads are extremely useful when method is able to operate on many different argument types (just one of examples), and does castings internally, for instance; you just feed it with any data type that makes sense (that is accepted by some existing overload). Can't beat that with optional arguments.</p>\n" }, { "answer_id": 14098791, "author": "sushil pandey", "author_id": 843294, "author_profile": "https://Stackoverflow.com/users/843294", "pm_score": 0, "selected": false, "text": "<p>Both Optional parameter , Method overload have there own advantage or disadvantage.it depends on your preference to choose between them.</p>\n\n<p>Optional Parameter:\navailable only in .Net 4.0.\noptional parameter reduce your code size.\nYou can't define out and ref parameter </p>\n\n<p>overloaded methods:\nYou can Define Out and ref parameters.\nCode size will increase but overloaded method's are easy to understand.</p>\n" }, { "answer_id": 14431423, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "<p>Optional parameters are essentially a piece of metadata which directs a compiler that's processing a method call to insert appropriate defaults at the call site. By contrast, overloads provide a means by which a compiler can select one of a number of methods, some of which might supply default values themselves. Note that if one tries to call a method that specifies optional parameters from code written in a language which doesn't support them, the compiler will require that the \"optional\" parameters be specified, but since calling a method without specifying an optional parameter is equivalent to calling it with a parameter equal to the default value, there's no obstacle to such languages calling such methods.</p>\n\n<p>A significant consequence of binding of optional parameters at the call site is that they will be assigned values based upon the version of the target code which is available to the compiler. If an assembly <code>Foo</code> has a method <code>Boo(int)</code> with a default value of 5, and assembly <code>Bar</code> contains a call to <code>Foo.Boo()</code>, the compiler will process that as a <code>Foo.Boo(5)</code>. If the default value is changed to 6 and assembly <code>Foo</code> is recompiled, <code>Bar</code> will continue to call <code>Foo.Boo(5)</code> unless or until it is recompiled with that new version of <code>Foo</code>. One should thus avoid using optional parameters for things that might change.</p>\n" }, { "answer_id": 30751678, "author": "Zoran Horvat", "author_id": 2279448, "author_profile": "https://Stackoverflow.com/users/2279448", "pm_score": 2, "selected": false, "text": "<p>In many cases optional parameters are used to switch execution. For example:</p>\n\n<pre><code>decimal GetPrice(string productName, decimal discountPercentage = 0)\n{\n\n decimal basePrice = CalculateBasePrice(productName);\n\n if (discountPercentage &gt; 0)\n return basePrice * (1 - discountPercentage / 100);\n else\n return basePrice;\n}\n</code></pre>\n\n<p>Discount parameter here is used to feed the if-then-else statement. There is the polymorphism that wasn't recognized, and then it was implemented as an if-then-else statement. In such cases, it is much better to split the two control flows into two independent methods:</p>\n\n<pre><code>decimal GetPrice(string productName)\n{\n decimal basePrice = CalculateBasePrice(productName);\n return basePrice;\n}\n\ndecimal GetPrice(string productName, decimal discountPercentage)\n{\n\n if (discountPercentage &lt;= 0)\n throw new ArgumentException();\n\n decimal basePrice = GetPrice(productName);\n\n decimal discountedPrice = basePrice * (1 - discountPercentage / 100);\n\n return discountedPrice;\n\n}\n</code></pre>\n\n<p>In this way, we have even protected the class from receiving a call with zero discount. That call would mean that the caller thinks that there is the discount, but in fact there is no discount at all. Such misunderstanding can easily cause a bug.</p>\n\n<p>In cases like this, I prefer not to have optional parameters, but to force the caller explicitly select the execution scenario that suits its current situation.</p>\n\n<p>The situation is very similar to having parameters that can be null. That is equally bad idea when implementation boils to statements like <code>if (x == null)</code>.</p>\n\n<p>You can find detailed analysis on these links: <a href=\"http://www.codinghelmet.com/?path=howto/reduce-cyclomatic-complexity-avoiding-optional-parameters\" rel=\"nofollow\">Avoiding Optional Parameters</a> and <a href=\"http://www.codinghelmet.com/?path=howto/reduce-cyclomatic-complexity-avoiding-null-parameters\" rel=\"nofollow\">Avoiding Null Parameters</a></p>\n" }, { "answer_id": 35862173, "author": "MakePeaceGreatAgain", "author_id": 2528063, "author_profile": "https://Stackoverflow.com/users/2528063", "pm_score": 2, "selected": false, "text": "<p>One of my favourites aspects of optional parameters is that you see what happens to your parameters if you do not provide them, even without going to the method definition. <strong>Visual Studio will simply show you the default value</strong> for the parameter when you type the method name. With an overload method you are stuck with either reading the documentation (if even available) or with directly navigating to the method's definition (if available) and to the method that the overload wraps. </p>\n\n<p>In particular: the documentation effort may increase rapidly with the amount of overloads, and you will probably end up copying already existing comments from the existing overloads. This is quite annoying, as it does not produce any value and breaks the <a href=\"https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY-principle</a>). On the other hand, with an optional parameter there's <em>exactly one place</em> where all the parameters are documented and you see their meaning as well as their <strong>default values</strong> while typing. </p>\n\n<p>Last but not least, if you are the consumer of an API you may not even have the option of inspecting the implementation details (if you don't have the source code) and therefore have no chance to see to which super method the overloaded ones are wrapping. Thus you're stuck with reading the doc and hoping that all default values are listed there, but this is not always the case.</p>\n\n<p>Of course, this is not an answer that handles all aspects, but I think it adds one which has not be covered so far. </p>\n" }, { "answer_id": 39498699, "author": "RayLuo", "author_id": 728675, "author_profile": "https://Stackoverflow.com/users/728675", "pm_score": 2, "selected": false, "text": "<p>While they are (supposedly?) two conceptually equivalent ways available for you to model your API from scratch, they unfortunately have some subtle difference when you need to consider runtime backward compatibility for your old clients in the wild. My colleague (thanks Brent!) pointed me to this <a href=\"http://haacked.com/archive/2010/08/10/versioning-issues-with-optional-arguments.aspx/\" rel=\"nofollow\">wonderful post: Versioning issues with optional arguments</a>. Some quote from it:</p>\n\n<blockquote>\n <p>The reason that optional parameters were introduced to C# 4 in the\n first place was to support COM interop. That’s it. And now, we’re\n learning about the full implications of this fact. If you have a\n method with optional parameters, you can never add an overload with\n additional optional parameters out of fear of causing a compile-time\n breaking change. And you can never remove an existing overload, as\n this has always been a runtime breaking change. You pretty much need\n to treat it like an interface. Your only recourse in this case is to\n write a new method with a new name. So be aware of this if you plan to\n use optional arguments in your APIs.</p>\n</blockquote>\n" }, { "answer_id": 47715752, "author": "Sebastian Mach", "author_id": 76722, "author_profile": "https://Stackoverflow.com/users/76722", "pm_score": 1, "selected": false, "text": "<p>To add a no-brainer when to use an overload instead of optionals:</p>\n\n<p>Whenever you have a number of parameters that only make sense together, do not introduce optionals on them. </p>\n\n<p>Or more generally, whenever your method signatures enable usage patterns which don't make sense, restrict the number of permutations of possible calls. E.g., by using overloads instead of optionals (this rule also holds true when you have several parameters of the same datatype, by the way; here, devices like factory methods or custom data types can help).</p>\n\n<p>Example:</p>\n\n<pre><code>enum Match {\n Regex,\n Wildcard,\n ContainsString,\n}\n\n// Don't: This way, Enumerate() can be called in a way\n// which does not make sense:\nIEnumerable&lt;string&gt; Enumerate(string searchPattern = null,\n Match match = Match.Regex,\n SearchOption searchOption = SearchOption.TopDirectoryOnly);\n\n// Better: Provide only overloads which cannot be mis-used:\nIEnumerable&lt;string&gt; Enumerate(SearchOption searchOption = SearchOption.TopDirectoryOnly);\nIEnumerable&lt;string&gt; Enumerate(string searchPattern, Match match,\n SearchOption searchOption = SearchOption.TopDirectoryOnly);\n</code></pre>\n" }, { "answer_id": 49162660, "author": "Zach", "author_id": 5478219, "author_profile": "https://Stackoverflow.com/users/5478219", "pm_score": 2, "selected": false, "text": "<p>One caveat of optional parameters is versioning, where a refactor has unintended consequences. An example:</p>\n\n<p><strong>Initial code</strong></p>\n\n<pre><code>public string HandleError(string message, bool silent=true, bool isCritical=true)\n{\n ...\n}\n</code></pre>\n\n<p>Assume this is one of many callers of the above method:</p>\n\n<pre><code>HandleError(\"Disk is full\", false);\n</code></pre>\n\n<p>Here the event is not silent and is treated as critical.</p>\n\n<p>Now let's say after a refactor we find that all errors prompt the user anyway, so we no longer need the silent flag. So we remove it.</p>\n\n<p><strong>After refactor</strong></p>\n\n<p>The former call still compiles, and let's say it slips through the refactor unchanged:</p>\n\n<pre><code>public string HandleError(string message, /*bool silent=true,*/ bool isCritical=true)\n{\n ...\n}\n\n...\n\n// Some other distant code file:\nHandleError(\"Disk is full\", false);\n</code></pre>\n\n<p>Now <code>false</code> will have an unintended effect, the event will no longer be treated as critical. </p>\n\n<p>This could result in a subtle defect, since there will be no compile or runtime error (unlike some other caveats of optionals, such as <a href=\"https://haacked.com/archive/2010/08/10/versioning-issues-with-optional-arguments.aspx/\" rel=\"nofollow noreferrer\">this</a> or <a href=\"https://lostechies.com/jimmybogard/2010/05/18/caveats-of-c-4-0-optional-parameters/\" rel=\"nofollow noreferrer\">this</a>).</p>\n\n<p>Note that there are many forms of this same problem. One other form is outlined <a href=\"https://haacked.com/archive/2010/08/12/more-optional-versioning-fun.aspx/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Note also that strictly using named parameters when calling the method will avoid the issue, such as like this: <code>HandleError(\"Disk is full\", silent:false)</code>. However, it may not be practical to assume that all other developers (or users of a public API) will do so.</p>\n\n<p>For these reasons I would avoid using optional parameters in a public API (or even a public method if it might be used widely) unless there are other compelling considerations.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552/" ]
I was watching [Anders' talk about C# 4.0 and sneak preview of C# 5.0](http://channel9.msdn.com/pdc2008/TL16/), and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified? For example something like the `FileStream` class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an `IntPtr` and the ones from a `SafeFileHandle`. ``` FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool); ``` It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation]. What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?
I'd consider the following: * Do you need your code to be used from languages which don't support optional parameters? If so, consider including the overloads. * Do you have any members on your team who violently oppose optional parameters? (Sometimes it's easier to live with a decision you don't like than to argue the case.) * Are you confident that your defaults won't change between builds of your code, or if they might, will your callers be okay with that? I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to `const` fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.
251,890
<p>I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test?</p> <p>I want to test my service method when it returns a System.GUID and an empty System.GUID</p> <pre><code>[TestMethod] public void GetGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasGuid"; System.GUID guid = proxy.GetGUID(name); } [TestMethod] public void GetEmptyGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasEmptyGuid"; System.GUID guid = proxy.GetGUID(name); } </code></pre>
[ { "answer_id": 251895, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<p>I used this for a few months last year, IIRC isn't there an <code>Assert</code> class? <code>Assert.IsTrue(...)</code>?</p>\n\n<p>I've dropped VS test stuff in favor of other unit test frameworks (better IMO) so my memory is likely clouded.</p>\n" }, { "answer_id": 251991, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 4, "selected": true, "text": "<p>For GetGUID()...</p>\n\n<pre><code>Assert.IsFalse(guid == Guid.Empty);\n</code></pre>\n\n<p>Similarly for GetEmptyGUID()...</p>\n\n<pre><code>Assert.IsTrue(guid == Guid.Empty);\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test? I want to test my service method when it returns a System.GUID and an empty System.GUID ``` [TestMethod] public void GetGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasGuid"; System.GUID guid = proxy.GetGUID(name); } [TestMethod] public void GetEmptyGUID() { MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient(); string name = "HasEmptyGuid"; System.GUID guid = proxy.GetGUID(name); } ```
For GetGUID()... ``` Assert.IsFalse(guid == Guid.Empty); ``` Similarly for GetEmptyGUID()... ``` Assert.IsTrue(guid == Guid.Empty); ```
251,902
<p>I would like to search through all of my procedures packages and functions for a certain phrase.</p> <p>Since it is possible to retrieve the code for compiled procedures using toad I assume that the full text is stored in some data dictionary table. Does anyone know where that would be?</p> <p>Thanks a lot</p>
[ { "answer_id": 251907, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 1, "selected": false, "text": "<p>Do you mean using PL/SQL? Or just using TOAD? I know that you can use the \"Find Objects\" (or something like that) feature to manually search through all objects like procs, tables, etc...</p>\n" }, { "answer_id": 251914, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 8, "selected": true, "text": "<p>You can do something like</p>\n\n<pre><code>SELECT name, line, text\n FROM dba_source\n WHERE upper(text) like upper('%&lt;&lt;your_phrase&gt;&gt;%') escape '\\' \n</code></pre>\n" }, { "answer_id": 253861, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 2, "selected": false, "text": "<p>Toad's \"object search\" routine will look through ALL_SOURCE (and other parts of the data dictionary). Of course, this will be limited to the objects the connected user is allowed to see. If you have access to the DBA version, great. If not, you won't be searching everything.</p>\n\n<p>Also, if you're way back on Oracle 7, or your database was migrated up from Oracle 7 to 8i or 9i (not sure about 10 or 11), then trigger source may not appear in the user_source or all_source views. Best to check. The easiest way I've found to get it to appear is to do an actual modification -- add a space, for example -- and recompile the trigger. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I would like to search through all of my procedures packages and functions for a certain phrase. Since it is possible to retrieve the code for compiled procedures using toad I assume that the full text is stored in some data dictionary table. Does anyone know where that would be? Thanks a lot
You can do something like ``` SELECT name, line, text FROM dba_source WHERE upper(text) like upper('%<<your_phrase>>%') escape '\' ```
251,908
<p>What commands in Emacs can I use to insert into the text buffer of a file the current date and time?</p> <p><em>(For example, the equivalent in Notepad is simply pressing F5 which is about the only useful feature for Notepad!)</em></p>
[ { "answer_id": 251922, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "<p>Put in your .emacs file:</p>\n\n<pre><code>;; ====================\n;; insert date and time\n\n(defvar current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"\n \"Format of date to insert with `insert-current-date-time' func\nSee help of `format-time-string' for possible replacements\")\n\n(defvar current-time-format \"%a %H:%M:%S\"\n \"Format of date to insert with `insert-current-time' func.\nNote the weekly scope of the command's precision.\")\n\n(defun insert-current-date-time ()\n \"insert the current date and time into current buffer.\nUses `current-date-time-format' for the formatting the date/time.\"\n (interactive)\n (insert \"==========\\n\")\n; (insert (let () (comment-start)))\n (insert (format-time-string current-date-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(defun insert-current-time ()\n \"insert the current time (1-week scope) into the current buffer.\"\n (interactive)\n (insert (format-time-string current-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(global-set-key \"\\C-c\\C-d\" 'insert-current-date-time)\n(global-set-key \"\\C-c\\C-t\" 'insert-current-time)\n</code></pre>\n\n<p><a href=\"http://301south.net/works/plaza.emacs\" rel=\"noreferrer\">Reference</a></p>\n" }, { "answer_id": 251935, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "<p>Here's a package I wrote a while ago that does what you're asking for.</p>\n\n<p><a href=\"http://github.com/rmm5t/insert-time.el/tree/master/insert-time.el\" rel=\"nofollow noreferrer\">http://github.com/rmm5t/insert-time.el/tree/master/insert-time.el</a></p>\n\n<pre><code>(require 'insert-time)\n(define-key global-map [(control c)(d)] 'insert-date-time)\n(define-key global-map [(control c)(control v)(d)] 'insert-personal-time-stamp)\n</code></pre>\n" }, { "answer_id": 252088, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": false, "text": "<p>You can install <a href=\"http://code.google.com/p/yasnippet/\" rel=\"noreferrer\">yasnippet</a>, which will let you type \"time\" and the tab key, and does a whole lot more besides. It just calls <code>current-time-string</code> behind the scenes, so you can control the formatting using <code>format-time-string</code>.</p>\n" }, { "answer_id": 275849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<pre><code>C-u M-! date\n</code></pre>\n" }, { "answer_id": 619525, "author": "Michael Paulukonis", "author_id": 41153, "author_profile": "https://Stackoverflow.com/users/41153", "pm_score": 5, "selected": false, "text": "<p>I've used these short snippets:</p>\n\n<pre><code>(defun now ()\n \"Insert string for the current time formatted like '2:34 PM'.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%D %-I:%M %p\")))\n\n(defun today ()\n \"Insert string for today's date nicely formatted in American style,\ne.g. Sunday, September 17, 2000.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%A, %B %e, %Y\")))\n</code></pre>\n\n<p>They originally came from <a href=\"http://www.emacswiki.org/cgi-bin/wiki/Journal\" rel=\"noreferrer\">journal.el</a></p>\n" }, { "answer_id": 2361880, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>M-1 M-! date</p>\n\n<p>this causes the shell command you run to be inserted into the buffer you are currently editing rather than a new buffer. </p>\n" }, { "answer_id": 3509321, "author": "bjkeefe", "author_id": 165727, "author_profile": "https://Stackoverflow.com/users/165727", "pm_score": 2, "selected": false, "text": "<p>Thanks, CMS! My variation, for what it's worth -- makes me happy enough:</p>\n\n<pre><code>(defvar bjk-timestamp-format \"%Y-%m-%d %H:%M\"\n \"Format of date to insert with `bjk-timestamp' function\n%Y-%m-%d %H:%M will produce something of the form YYYY-MM-DD HH:MM\nDo C-h f on `format-time-string' for more info\")\n\n\n(defun bjk-timestamp ()\n \"Insert a timestamp at the current point.\nNote no attempt to go to beginning of line and no added carriage return.\nUses `bjk-timestamp-format' for formatting the date/time.\"\n (interactive)\n (insert (format-time-string bjk-timestamp-format (current-time)))\n )\n</code></pre>\n\n<p>I put this in a file that is called by my .emacs using:</p>\n\n<pre><code>(load \"c:/bjk/elisp/bjk-timestamp.el\")\n</code></pre>\n\n<p>which both makes it easier to modify without risking breaking something else in my .emacs, and allowed me an easy entry point into maybe someday actually learning what this Emacs Lisp programming is all about. </p>\n\n<p>P.S. Critiques regarding my n00b technique most welcome.</p>\n" }, { "answer_id": 17078689, "author": "tangxinfa", "author_id": 802708, "author_profile": "https://Stackoverflow.com/users/802708", "pm_score": 5, "selected": false, "text": "<p>For insert date:</p>\n\n<pre><code>M-x org-time-stamp\n</code></pre>\n\n<p>For insert date time:</p>\n\n<pre><code>C-u M-x org-time-stamp\n</code></pre>\n\n<p>You may bind a global key for this command.</p>\n\n<p><code>org-mode</code>'s method is very user friendly, you can select any date from calendar.</p>\n" }, { "answer_id": 29374896, "author": "Kaushal Modi", "author_id": 1219634, "author_profile": "https://Stackoverflow.com/users/1219634", "pm_score": 0, "selected": false, "text": "<p>Here's my take on it. </p>\n\n<pre class=\"lang-el prettyprint-override\"><code>(defun modi/insert-time-stamp (option)\n \"Insert date, time, user name - DWIM.\n\nIf the point is NOT in a comment/string, the time stamp is inserted prefixed\nwith `comment-start' characters.\n\nIf the point is IN a comment/string, the time stamp is inserted without the\n`comment-start' characters. If the time stamp is not being inserted immediately\nafter the `comment-start' characters (followed by optional space),\nthe time stamp is inserted with “--” prefix.\n\nIf the buffer is in a major mode where `comment-start' var is nil, no prefix is\nadded regardless.\n\nAdditional control:\n\n C-u -&gt; Only `comment-start'/`--' prefixes are NOT inserted\n C-u C-u -&gt; Only user name is NOT inserted\nC-u C-u C-u -&gt; Both prefix and user name are not inserted.\"\n (interactive \"P\")\n (let ((current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n ;; Insert prefix only if `comment-start' is defined for the major mode\n (when (stringp comment-start)\n (if (or (nth 3 (syntax-ppss)) ; string\n (nth 4 (syntax-ppss))) ; comment\n ;; If the point is already in a comment/string\n (progn\n ;; If the point is not immediately after `comment-start' chars\n ;; (followed by optional space)\n (when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (not (looking-back (concat comment-start \" *\")))\n (not (looking-back \"^ *\")))\n (insert \"--\")))\n ;; If the point is NOT in a comment\n (progn\n (when (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (insert comment-start)))))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n (insert (format-time-string current-date-time-format (current-time)))\n (when (not (equal option '(16))) ; C-u C-u\n (insert (concat \" - \" (getenv \"USER\"))))\n ;; Insert a space after the time stamp if not at the end of the line\n (when (not (looking-at \" *$\"))\n (insert \" \"))))\n</code></pre>\n\n<p>I prefer to bind this to <code>C-c d</code>.</p>\n" }, { "answer_id": 61418573, "author": "Dino Dini", "author_id": 4089000, "author_profile": "https://Stackoverflow.com/users/4089000", "pm_score": 2, "selected": false, "text": "<p>The simplest way without shelling out to 'date' is probably:</p>\n\n<p>(insert (current-time-string))</p>\n" }, { "answer_id": 68185786, "author": "Misho M. Petkovic", "author_id": 3358597, "author_profile": "https://Stackoverflow.com/users/3358597", "pm_score": 1, "selected": false, "text": "<p>To insert date:</p>\n<pre><code>C-c . RET \n</code></pre>\n<p>For select date Shift left/right/up/down - RET (enter)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
What commands in Emacs can I use to insert into the text buffer of a file the current date and time? *(For example, the equivalent in Notepad is simply pressing F5 which is about the only useful feature for Notepad!)*
``` C-u M-! date ```
251,909
<p>I'm using <code>Microsoft's DSOFramer</code> control to allow me to embed an Excel file in my dialog so the user can choose his sheet, then select his range of cells; it's used with an import button on my dialog.</p> <p>The problem is that when I call the <code>DSOFramer's OPEN</code> function, if I have Excel open in another window, it closes the Excel document (but leaves Excel running). If the document it tries to close has unsaved data, I get a dialog boxclosing Excel doc in another window. If unsaved data in file, <code>dsoframer</code> fails to open with a messagebox: <code>Attempt to access invalid address</code>. </p> <p>I built the source, and stepped through, and its making a call in its <code>CDsoDocObject::CreateFromFile</code> function, calling <code>BindToObject</code> on an object of class IMoniker. The <code>HR</code> is <code>0x8001010a</code> <code>The message filter indicated that the application is busy</code>. On that failure, it tries to <code>InstantiateDocObjectServer</code> by <code>classid</code> of <code>CLSID</code> Microsoft Excel Worksheet... this fails with an <code>HRESULT</code> of <code>0x80040154</code> <code>Class not registered</code>. The <code>InstantiateDocObjectServer</code> just calls <code>CoCreateInstance</code> on the <code>classid</code>, first with <code>CLSCTX_LOCAL_SERVER</code>, then (if that fails) with <code>CLSCTX_INPROC_SERVER</code>.</p> <p>I know <code>DSOFramer</code> is a popular sample project for embedding Office apps in various dialog and forms. I'm hoping someone else has had this problem and might have some insight on how I can solve this. I really don't want it to close any other open Excel documents, and I really don't want it to error-out if it can't close the document due to unsaved data.</p> <p>Update 1: I've tried changing the <code>classid</code> that's passed in to <code>Excel.Application</code> (I know that class will resolve), but that didn't work. In <code>CDsoDocObject</code>, it tries to open key <code>HKEY_CLASSES_ROOT\CLSID\{00024500-0000-0000-C000-000000000046}\DocObject</code>, but fails. I've visually confirmed that the key is not present in my registry; The key is present for the guide, but there's no <code>DocObject</code> subkey. It then produces an error message box: <code>The associated COM server does not support ActiveX document embedding</code>. I get similar (different key, of course) results when I try to use the <code>Excel.Workbook programid</code>.</p> <p><strong>Update 2: I tried starting a 2nd instance of Excel, hoping that my automation would bind to it (being the most recently invoked) instead of the problem Excel instance, but it didn't seem to do that. Results were the same. My problem seems to have boiled down to this: I'm calling the <code>BindToObject</code> on an object of class <code>IMoniker</code>, and receiving <code>0x8001010A (RPC_E_SERVERCALL_RETRYLATER)</code> <code>The message filter indicated that the application is busy</code>. I've tried playing with the flags passed to the <code>BindToObject</code> (via the <code>SetBindOptions</code>), but nothing seems to make any difference.</strong></p> <p><strong>Update 3: It first tries to bind using an IMoniker class. If that fails, it calls <code>CoCreateInstance</code> for the <code>clsid</code> as a <code>fallback</code> method. This may work for other MS Office objects, but when it's Excel, the class is for the Worksheet. I modified the sample to <code>CoCreateInstance _Application</code>, then got the workbooks, then called the <code>Workbooks::Open</code> for the target file, which returns a Worksheet object. I then returned that pointer and merged back with the original sample code path. All working now.</strong></p>
[ { "answer_id": 251922, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "<p>Put in your .emacs file:</p>\n\n<pre><code>;; ====================\n;; insert date and time\n\n(defvar current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"\n \"Format of date to insert with `insert-current-date-time' func\nSee help of `format-time-string' for possible replacements\")\n\n(defvar current-time-format \"%a %H:%M:%S\"\n \"Format of date to insert with `insert-current-time' func.\nNote the weekly scope of the command's precision.\")\n\n(defun insert-current-date-time ()\n \"insert the current date and time into current buffer.\nUses `current-date-time-format' for the formatting the date/time.\"\n (interactive)\n (insert \"==========\\n\")\n; (insert (let () (comment-start)))\n (insert (format-time-string current-date-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(defun insert-current-time ()\n \"insert the current time (1-week scope) into the current buffer.\"\n (interactive)\n (insert (format-time-string current-time-format (current-time)))\n (insert \"\\n\")\n )\n\n(global-set-key \"\\C-c\\C-d\" 'insert-current-date-time)\n(global-set-key \"\\C-c\\C-t\" 'insert-current-time)\n</code></pre>\n\n<p><a href=\"http://301south.net/works/plaza.emacs\" rel=\"noreferrer\">Reference</a></p>\n" }, { "answer_id": 251935, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "<p>Here's a package I wrote a while ago that does what you're asking for.</p>\n\n<p><a href=\"http://github.com/rmm5t/insert-time.el/tree/master/insert-time.el\" rel=\"nofollow noreferrer\">http://github.com/rmm5t/insert-time.el/tree/master/insert-time.el</a></p>\n\n<pre><code>(require 'insert-time)\n(define-key global-map [(control c)(d)] 'insert-date-time)\n(define-key global-map [(control c)(control v)(d)] 'insert-personal-time-stamp)\n</code></pre>\n" }, { "answer_id": 252088, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": false, "text": "<p>You can install <a href=\"http://code.google.com/p/yasnippet/\" rel=\"noreferrer\">yasnippet</a>, which will let you type \"time\" and the tab key, and does a whole lot more besides. It just calls <code>current-time-string</code> behind the scenes, so you can control the formatting using <code>format-time-string</code>.</p>\n" }, { "answer_id": 275849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<pre><code>C-u M-! date\n</code></pre>\n" }, { "answer_id": 619525, "author": "Michael Paulukonis", "author_id": 41153, "author_profile": "https://Stackoverflow.com/users/41153", "pm_score": 5, "selected": false, "text": "<p>I've used these short snippets:</p>\n\n<pre><code>(defun now ()\n \"Insert string for the current time formatted like '2:34 PM'.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%D %-I:%M %p\")))\n\n(defun today ()\n \"Insert string for today's date nicely formatted in American style,\ne.g. Sunday, September 17, 2000.\"\n (interactive) ; permit invocation in minibuffer\n (insert (format-time-string \"%A, %B %e, %Y\")))\n</code></pre>\n\n<p>They originally came from <a href=\"http://www.emacswiki.org/cgi-bin/wiki/Journal\" rel=\"noreferrer\">journal.el</a></p>\n" }, { "answer_id": 2361880, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>M-1 M-! date</p>\n\n<p>this causes the shell command you run to be inserted into the buffer you are currently editing rather than a new buffer. </p>\n" }, { "answer_id": 3509321, "author": "bjkeefe", "author_id": 165727, "author_profile": "https://Stackoverflow.com/users/165727", "pm_score": 2, "selected": false, "text": "<p>Thanks, CMS! My variation, for what it's worth -- makes me happy enough:</p>\n\n<pre><code>(defvar bjk-timestamp-format \"%Y-%m-%d %H:%M\"\n \"Format of date to insert with `bjk-timestamp' function\n%Y-%m-%d %H:%M will produce something of the form YYYY-MM-DD HH:MM\nDo C-h f on `format-time-string' for more info\")\n\n\n(defun bjk-timestamp ()\n \"Insert a timestamp at the current point.\nNote no attempt to go to beginning of line and no added carriage return.\nUses `bjk-timestamp-format' for formatting the date/time.\"\n (interactive)\n (insert (format-time-string bjk-timestamp-format (current-time)))\n )\n</code></pre>\n\n<p>I put this in a file that is called by my .emacs using:</p>\n\n<pre><code>(load \"c:/bjk/elisp/bjk-timestamp.el\")\n</code></pre>\n\n<p>which both makes it easier to modify without risking breaking something else in my .emacs, and allowed me an easy entry point into maybe someday actually learning what this Emacs Lisp programming is all about. </p>\n\n<p>P.S. Critiques regarding my n00b technique most welcome.</p>\n" }, { "answer_id": 17078689, "author": "tangxinfa", "author_id": 802708, "author_profile": "https://Stackoverflow.com/users/802708", "pm_score": 5, "selected": false, "text": "<p>For insert date:</p>\n\n<pre><code>M-x org-time-stamp\n</code></pre>\n\n<p>For insert date time:</p>\n\n<pre><code>C-u M-x org-time-stamp\n</code></pre>\n\n<p>You may bind a global key for this command.</p>\n\n<p><code>org-mode</code>'s method is very user friendly, you can select any date from calendar.</p>\n" }, { "answer_id": 29374896, "author": "Kaushal Modi", "author_id": 1219634, "author_profile": "https://Stackoverflow.com/users/1219634", "pm_score": 0, "selected": false, "text": "<p>Here's my take on it. </p>\n\n<pre class=\"lang-el prettyprint-override\"><code>(defun modi/insert-time-stamp (option)\n \"Insert date, time, user name - DWIM.\n\nIf the point is NOT in a comment/string, the time stamp is inserted prefixed\nwith `comment-start' characters.\n\nIf the point is IN a comment/string, the time stamp is inserted without the\n`comment-start' characters. If the time stamp is not being inserted immediately\nafter the `comment-start' characters (followed by optional space),\nthe time stamp is inserted with “--” prefix.\n\nIf the buffer is in a major mode where `comment-start' var is nil, no prefix is\nadded regardless.\n\nAdditional control:\n\n C-u -&gt; Only `comment-start'/`--' prefixes are NOT inserted\n C-u C-u -&gt; Only user name is NOT inserted\nC-u C-u C-u -&gt; Both prefix and user name are not inserted.\"\n (interactive \"P\")\n (let ((current-date-time-format \"%a %b %d %H:%M:%S %Z %Y\"))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n ;; Insert prefix only if `comment-start' is defined for the major mode\n (when (stringp comment-start)\n (if (or (nth 3 (syntax-ppss)) ; string\n (nth 4 (syntax-ppss))) ; comment\n ;; If the point is already in a comment/string\n (progn\n ;; If the point is not immediately after `comment-start' chars\n ;; (followed by optional space)\n (when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (not (looking-back (concat comment-start \" *\")))\n (not (looking-back \"^ *\")))\n (insert \"--\")))\n ;; If the point is NOT in a comment\n (progn\n (when (not (or (equal option '(4)) ; C-u or C-u C-u C-u\n (equal option '(64))))\n (insert comment-start)))))\n ;; Insert a space if there is no space to the left of the current point\n ;; and it's not at the beginning of a line\n (when (and (not (looking-back \"^ *\"))\n (not (looking-back \" \")))\n (insert \" \"))\n (insert (format-time-string current-date-time-format (current-time)))\n (when (not (equal option '(16))) ; C-u C-u\n (insert (concat \" - \" (getenv \"USER\"))))\n ;; Insert a space after the time stamp if not at the end of the line\n (when (not (looking-at \" *$\"))\n (insert \" \"))))\n</code></pre>\n\n<p>I prefer to bind this to <code>C-c d</code>.</p>\n" }, { "answer_id": 61418573, "author": "Dino Dini", "author_id": 4089000, "author_profile": "https://Stackoverflow.com/users/4089000", "pm_score": 2, "selected": false, "text": "<p>The simplest way without shelling out to 'date' is probably:</p>\n\n<p>(insert (current-time-string))</p>\n" }, { "answer_id": 68185786, "author": "Misho M. Petkovic", "author_id": 3358597, "author_profile": "https://Stackoverflow.com/users/3358597", "pm_score": 1, "selected": false, "text": "<p>To insert date:</p>\n<pre><code>C-c . RET \n</code></pre>\n<p>For select date Shift left/right/up/down - RET (enter)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
I'm using `Microsoft's DSOFramer` control to allow me to embed an Excel file in my dialog so the user can choose his sheet, then select his range of cells; it's used with an import button on my dialog. The problem is that when I call the `DSOFramer's OPEN` function, if I have Excel open in another window, it closes the Excel document (but leaves Excel running). If the document it tries to close has unsaved data, I get a dialog boxclosing Excel doc in another window. If unsaved data in file, `dsoframer` fails to open with a messagebox: `Attempt to access invalid address`. I built the source, and stepped through, and its making a call in its `CDsoDocObject::CreateFromFile` function, calling `BindToObject` on an object of class IMoniker. The `HR` is `0x8001010a` `The message filter indicated that the application is busy`. On that failure, it tries to `InstantiateDocObjectServer` by `classid` of `CLSID` Microsoft Excel Worksheet... this fails with an `HRESULT` of `0x80040154` `Class not registered`. The `InstantiateDocObjectServer` just calls `CoCreateInstance` on the `classid`, first with `CLSCTX_LOCAL_SERVER`, then (if that fails) with `CLSCTX_INPROC_SERVER`. I know `DSOFramer` is a popular sample project for embedding Office apps in various dialog and forms. I'm hoping someone else has had this problem and might have some insight on how I can solve this. I really don't want it to close any other open Excel documents, and I really don't want it to error-out if it can't close the document due to unsaved data. Update 1: I've tried changing the `classid` that's passed in to `Excel.Application` (I know that class will resolve), but that didn't work. In `CDsoDocObject`, it tries to open key `HKEY_CLASSES_ROOT\CLSID\{00024500-0000-0000-C000-000000000046}\DocObject`, but fails. I've visually confirmed that the key is not present in my registry; The key is present for the guide, but there's no `DocObject` subkey. It then produces an error message box: `The associated COM server does not support ActiveX document embedding`. I get similar (different key, of course) results when I try to use the `Excel.Workbook programid`. **Update 2: I tried starting a 2nd instance of Excel, hoping that my automation would bind to it (being the most recently invoked) instead of the problem Excel instance, but it didn't seem to do that. Results were the same. My problem seems to have boiled down to this: I'm calling the `BindToObject` on an object of class `IMoniker`, and receiving `0x8001010A (RPC_E_SERVERCALL_RETRYLATER)` `The message filter indicated that the application is busy`. I've tried playing with the flags passed to the `BindToObject` (via the `SetBindOptions`), but nothing seems to make any difference.** **Update 3: It first tries to bind using an IMoniker class. If that fails, it calls `CoCreateInstance` for the `clsid` as a `fallback` method. This may work for other MS Office objects, but when it's Excel, the class is for the Worksheet. I modified the sample to `CoCreateInstance _Application`, then got the workbooks, then called the `Workbooks::Open` for the target file, which returns a Worksheet object. I then returned that pointer and merged back with the original sample code path. All working now.**
``` C-u M-! date ```
251,924
<p>Lists in C# have the <code>.ToArray()</code> method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.</p> <p>I am using the <code>String.Split</code> method in the .NET 2.0 environment, so LINQ, etc. is not available to me.</p>
[ { "answer_id": 251928, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 3, "selected": false, "text": "<pre><code>return new List&lt;string&gt;(stringArray);\n</code></pre>\n" }, { "answer_id": 251929, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 7, "selected": true, "text": "<pre><code>string s = ...\nnew List&lt;string&gt;(s.Split(....));\n</code></pre>\n" }, { "answer_id": 251979, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 4, "selected": false, "text": "<p>In .Net 3.5, the <code>System.Linq</code> namespace includes an extension method called <code>ToList&lt;&gt;()</code>.</p>\n" }, { "answer_id": 252795, "author": "heijp06", "author_id": 1793417, "author_profile": "https://Stackoverflow.com/users/1793417", "pm_score": 2, "selected": false, "text": "<p>If all you need is an object that implements the IList interface and you do not need to add new items you might also do it like this:</p>\n\n<pre><code>IList&lt;string&gt; list = myString.Split(' ');\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
Lists in C# have the `.ToArray()` method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back. I am using the `String.Split` method in the .NET 2.0 environment, so LINQ, etc. is not available to me.
``` string s = ... new List<string>(s.Split(....)); ```
251,941
<p>I'm in javascript, running this in the console </p> <pre><code>d = new Date(); d.setMonth(1); d.setFullYear(2009); d.setDate(15); d.toString(); </code></pre> <p>outputs this:</p> <pre><code>"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)" </code></pre> <p>Why would this be happening? It seems like a browser bug.</p>
[ { "answer_id": 251962, "author": "Issac Kelly", "author_id": 144, "author_profile": "https://Stackoverflow.com/users/144", "pm_score": 1, "selected": false, "text": "<pre><code>d = new Date();\nd.setDate(15); \nd.setMonth(1);\nd.setFullYear(2009); \nd.toString();\n</code></pre>\n\n<p>This works.</p>\n" }, { "answer_id": 251975, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "<p>That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year:</p>\n\n<pre><code>d = new Date();\nd.setDate(15); \nd.setMonth(1);\nd.setFullYear(2009); \n</code></pre>\n\n<p>But as <a href=\"https://stackoverflow.com/questions/251941/the-fifteenth-of-february-isnt-found#251976\">@Jason W</a>, says it's better to use the Date constructor:</p>\n\n<pre><code>new Date(year, month, date [, hour, minute, second, millisecond ]);\n</code></pre>\n" }, { "answer_id": 251976, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 5, "selected": false, "text": "<p>It's probably best to construct a Date object in one step to avoid the Date object being in an ambiguous or invalid state:</p>\n\n<pre><code>d = new Date(2009, 1, 15);\n</code></pre>\n" }, { "answer_id": 252009, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>After a bunch of testing in FF3 on XP with Firebug, here are the things I can tell you</p>\n\n<ul>\n<li>Calling Date.setDate() <em>after</em> calling Date.setMonth() will generate this odd behavior.</li>\n<li>Date.setMonth() forces the timezone to be CST (or, some non DST-aware zone)</li>\n<li>Date.setDate() forces the timezone to be CDT (or, some DST-aware zone)</li>\n</ul>\n\n<p>So, there's definitely something wonky going on with setMonth() and setDate() in respect to the timezone.</p>\n\n<p>The only solution I can offer is this: Set the date before you set the month.</p>\n" }, { "answer_id": 9113409, "author": "Alexander Klimetschek", "author_id": 2709, "author_profile": "https://Stackoverflow.com/users/2709", "pm_score": 0, "selected": false, "text": "<p>This will work generally to avoid the <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/setMonth\" rel=\"nofollow\">rollover behavior</a> of the javascript Date API:</p>\n\n<pre><code>d.setDate(1);\nd.setFullYear(year);\nd.setMonth(month);\nd.setDate(day);\n</code></pre>\n\n<p>Given that year + month + day are in a \"valid\" combination, e.g. taken from another Date object using getFullYear(), getMonth(), getDate().</p>\n\n<p>The important parts are:</p>\n\n<ul>\n<li>starting with <code>setDate(1)</code> to avoid possible rollover when the current date value is 29, 30 or 31</li>\n<li>call <code>setMonth(month)</code> before <code>setDate(day)</code> to avoid the same rollover in case the current month value is \"problematic\" (because then the initial <code>setDate(1)</code> would be without effect)</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
I'm in javascript, running this in the console ``` d = new Date(); d.setMonth(1); d.setFullYear(2009); d.setDate(15); d.toString(); ``` outputs this: ``` "Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)" ``` Why would this be happening? It seems like a browser bug.
That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year: ``` d = new Date(); d.setDate(15); d.setMonth(1); d.setFullYear(2009); ``` But as [@Jason W](https://stackoverflow.com/questions/251941/the-fifteenth-of-february-isnt-found#251976), says it's better to use the Date constructor: ``` new Date(year, month, date [, hour, minute, second, millisecond ]); ```
251,945
<p>I have a site that creates images for some bit of content after the content is created. I'm trying to figure out what to do in between the time the content is created and the image is created. My thought is that I might be able to set a custom image to display on a 404 error on the original image. However, I'm not sure how to do this with lighttpd. Any ideas or alternatives?</p> <p>EDIT: The issue is the user isn't the one creating the content, it's being created by a process. Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider. However, I don't want a slow server on the provider end to slow down the addition of new products. So a separate process goes through and creates the image later, where available. I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.</p>
[ { "answer_id": 251977, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "<p>Use the <code>&lt;object&gt;</code> tag in HTML with a fallback to the default image.</p>\n\n<pre><code>&lt;P&gt; &lt;!-- First, try the Python applet --&gt;\n&lt;OBJECT title=\"The Earth as seen from space\" \n classid=\"http://www.observer.mars/TheEarth.py\"&gt;\n &lt;!-- Else, try the MPEG video --&gt;\n &lt;OBJECT data=\"TheEarth.mpeg\" type=\"application/mpeg\"&gt;\n &lt;!-- Else, try the GIF image --&gt;\n &lt;OBJECT data=\"TheEarth.gif\" type=\"image/gif\"&gt;\n &lt;!-- Else render the text --&gt;\n The &lt;STRONG&gt;Earth&lt;/STRONG&gt; as seen from space.\n &lt;/OBJECT&gt;\n &lt;/OBJECT&gt;\n&lt;/OBJECT&gt;\n&lt;/P&gt;\n</code></pre>\n\n<p>(Example from w3.org)</p>\n" }, { "answer_id": 252018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As I understand your problem: You want to show an intermediate image until the <em>real</em> image has been generated?</p>\n\n<p>You could display a <em>loading image</em> and use AJAX to change that DOM node into the <em>real</em> image when it's been created. You could write it from scratch or use any of the well known and stable AJAX libraries out there, if you have no preference of your own take a look at <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>.</p>\n" }, { "answer_id": 252105, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 0, "selected": false, "text": "<p>Further to @kentlarsson - if you want to do it via Javascript, I recently found this code:\n<a href=\"http://jquery.com/plugins/project/Preload\" rel=\"nofollow noreferrer\">http://jquery.com/plugins/project/Preload</a> and the demo at <a href=\"http://demos.flesler.com/jquery/preload/placeholder/\" rel=\"nofollow noreferrer\">http://demos.flesler.com/jquery/preload/placeholder/</a> which does as he suggests - with its 'notFound' option.</p>\n\n<p>I don't know enough about lighttpd to tell you about setting up a custom image with one or more subdirectories in a site though.</p>\n" }, { "answer_id": 305420, "author": "EoghanM", "author_id": 6691, "author_profile": "https://Stackoverflow.com/users/6691", "pm_score": 0, "selected": false, "text": "<p>I think you could probably solve this on the client side alone.</p>\n\n<p>Based on Jaspers' answer, you could do:</p>\n\n<pre><code>&lt;OBJECT data=\"/images/generated_image_xyz.png\" type=\"image/png\"&gt;\n Loading..&lt;blink&gt;.&lt;/blink&gt;\n&lt;/OBJECT&gt;\n</code></pre>\n\n<p>Also layering backgrounds using CSS you could do:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n .content_image { width:100px; height: 100px; \n background: transparent url('/images/default_image.png') no-repeat }\n .content_image div { width:100px; height: 100px; }\n&lt;/style&gt;\n\n&lt;div class=\"content_image\"&gt;\n &lt;div style=\"background: \n transparent url('/images/generated_image_xyz.png') no-repeat\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The latter solution assumes you don't have any transparency in your generated image.</p>\n" }, { "answer_id": 333768, "author": "EoghanM", "author_id": 6691, "author_profile": "https://Stackoverflow.com/users/6691", "pm_score": 2, "selected": false, "text": "<p>Another alternative on the client side is to do:</p>\n\n<pre><code>&lt;img src=\"/images/generated_image_xyz.png\" \n onerror=\"this.src='/images/default_image.png'; this.title='Loading...';\" /&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31240/" ]
I have a site that creates images for some bit of content after the content is created. I'm trying to figure out what to do in between the time the content is created and the image is created. My thought is that I might be able to set a custom image to display on a 404 error on the original image. However, I'm not sure how to do this with lighttpd. Any ideas or alternatives? EDIT: The issue is the user isn't the one creating the content, it's being created by a process. Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider. However, I don't want a slow server on the provider end to slow down the addition of new products. So a separate process goes through and creates the image later, where available. I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.
Another alternative on the client side is to do: ``` <img src="/images/generated_image_xyz.png" onerror="this.src='/images/default_image.png'; this.title='Loading...';" /> ```
251,957
<p>I have a simple table in SQL Server 2005, I wish to convert this to XML (using the "FOR XML" clause). I'm having trouble getting my XML to look like the required output.</p> <p>I've tried looking through various tutorials on the web, but I am struggling. Can someone help?</p> <p>The table I have looks like this</p> <pre><code>TYPE,GROUP,VALUE Books,Hardback,56 Books,Softcover,34 CDs,Singles,45 CDS,Multis,78 </code></pre> <p>The output style I need is:</p> <pre><code>&lt;data&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;/data&gt; </code></pre> <p><strong>Edit:</strong> As far as I can tell I require the multiple values. I'm generating XML for use with Xcelsius (<a href="http://xcelsius.files.wordpress.com/2008/05/xml_data_button.pdf" rel="nofollow noreferrer">Linking XML and Xcelsius</a>) so have no control over in the formatting of the XML. I can generate the XML using ASP as per the linked tutorial, but I was hoping to get it straight from SQL Server.</p> <p><strong>Edit 2:</strong> I was hoping for something elegant and tidy... but Godeke's example got the closest. Some fiddling with the SQL and I've come up with:</p> <pre><code>select "type" as '@name', "group" as 'row/column', null as 'row/tmp', "value" as 'row/column' from tableName for xml path('variable'), root('data') </code></pre> <p>Outputs almost in the exact way I wanted. The null/tmp line doesn't even output; it is just preventing the concatenation. Still the tag <code>&lt;variable name="TYPE"&gt;</code> repeats for each row, which I can't have.</p>
[ { "answer_id": 252021, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": "<p>I prefer using for XML PATH, it provides a nicer way to control your elements etc.</p>\n\n<p><a href=\"http://theengineroom.provoke.co.nz/archive/2007/04/27/using-for-xml-path-a-primer.aspx\" rel=\"nofollow noreferrer\">See</a></p>\n\n<p>But this is quite tricky </p>\n\n<pre><code> /*\ncreate table #tablename\n(\n[type] varchar(20),\n[group] varchar(20),\n[value] varchar(20)\n)\n\ninsert into #tablename select 'type1','group11','value111'\ninsert into #tablename select 'type1','group11','value112'\ninsert into #tablename select 'type1','group12','value121'\ninsert into #tablename select 'type1','group12','value122'\ninsert into #tablename select 'type2','group21','value211'\ninsert into #tablename select 'type2','group21','value212'\ninsert into #tablename select 'type2','group22','value221'\ninsert into #tablename select 'type2','group22','value222'\n\nalter table #tablename add id uniqueidentifier\n\nupdate #tablename set id = newid()\n*/\n\nselect [type] as '@name',\n (select \n (select [column] from\n (\n select [group] as 'column', tbn1.type, tbn2.[group]\n from #tablename tbn3 WHERE tbn3.type = tbn1.type and tbn2.[group] = tbn3.[group]\n union\n select [value], tbn1.type, tbn2.[group]\n from #tablename tbn3 WHERE tbn3.type = tbn1.type and tbn2.[group] = tbn3.[group]\n ) as s\n for xml path(''),type \n )\n from #tablename tbn2 \n where tbn2.type = tbn1.type\n for xml path('row3'), type\n)\n\nfrom #tableName tbn1 \nGROUP BY [type]\nfor xml path('variable'), root('data') \n</code></pre>\n\n<p>gives you what you are asking for I, but elegant and tidy it is not.</p>\n" }, { "answer_id": 252061, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 2, "selected": false, "text": "<p>As close as I can get is this:</p>\n\n<pre><code>select \"type\" as '@name', \"group\" as 'row/column1', \"value\" as 'row/column2'\nfrom tableName\nfor xml path('variable'), root('data')\n</code></pre>\n\n<p>Naming two items the same (\"column\" and \"column\") isn't something I know how to do in one pass, but on the other hand it is an odd XML schema choice; normally elements have unique names if they contain distinct data. The obvious choice (name them both 'row/column') simply concatenates them in the output into one value.</p>\n\n<p>Also note that each returned row will be a \"variable\" element distinct from the others. To get the nesting without redundant records will require a subquery:</p>\n\n<pre><code>select distinct \"type\" as '@name'\nfrom Agent\nfor xml path('variable'), root('data')\n</code></pre>\n\n<p>was my first thought, but the distinct prevents nesting.</p>\n\n<p>All this makes me think that to get the <em>exact</em> output you need you might have to use EXPLICIT mode. Perhaps my problem is for something like this I punt and use a DOMDocument in code :).</p>\n" }, { "answer_id": 252378, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 0, "selected": false, "text": "<p><b>The script below produces the desired format </b></p>\n\n<blockquote>\n<br/>&lt;DATA&gt;\n<br/>&nbsp; &nbsp; &lt;VARIABLE TYPE=\"Books\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE=\"Books\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Hardback&lt;/GROUP&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;56&lt;/VALUE&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE=\"Books\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Softcover&lt;/GROUP&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;34&lt;/VALUE&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt;\n<br/>&nbsp; &nbsp; &lt;/VARIABLE&gt;\n<br/>&nbsp; &nbsp; &lt;VARIABLE TYPE=\"CDs\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE=\"CDs\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Singles&lt;/GROUP&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;45&lt;/VALUE&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE=\"CDS\"&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Multis&lt;/GROUP&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;78&lt;/VALUE&gt;\n<br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt;\n<br/>&nbsp; &nbsp; &lt;/VARIABLE&gt;\n<br/>&lt;/DATA&gt;\n</blockquote>\n\n<p><b>Invoke</b></p>\n\n<blockquote>\n<code>\n<br/>DECLARE @tblItems table (\n<br/>&nbsp; &nbsp; [TYPE] varchar(50)\n<br/>&nbsp; &nbsp; ,[GROUP] varchar(50)\n<br/>&nbsp; &nbsp; ,[VALUE] int\n<br/>)\n<br/>\n<br/>DECLARE @tblShredded table (\n<br/>&nbsp; &nbsp; [TYPE] varchar(50)\n<br/>&nbsp; &nbsp; ,[XmlItem] xml\n<br/>)\n<br/>\n<br/>DECLARE @xmlGroupValueTuples xml\n<br/>\n<br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Hardback',56)\n<br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Softcover',34)\n<br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDs','Singles',45)\n<br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDS','Multis',78)\n<br/>\n<br/>SET @xmlGroupValueTuples =\n<br/>&nbsp; (\n<br/>&nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; \"@TYPE\" = [TYPE]\n<br/>&nbsp; &nbsp; &nbsp; ,[GROUP]\n<br/>&nbsp; &nbsp; &nbsp; ,[VALUE]\n<br/>&nbsp; &nbsp; FROM @tblItems\n<br/>&nbsp; &nbsp; FOR XML PATH('row'), root('Root')\n<br/>&nbsp; )\n<br/>\n<br/>INSERT @tblShredded([TYPE], XmlItem)\n<br/>SELECT\n<br/>&nbsp; &nbsp; [TYPE] = XmlItem.value('./row[1]/@TYPE', 'varchar(50)')\n<br/>&nbsp; &nbsp; ,XmlItem\n<br/>FROM dbo.tvfShredGetOneColumnedTableOfXmlItems(@xmlGroupValueTuples)\n<br/>\n<br/>\n<br/>SELECT \n<br/>&nbsp; (\n<br/>&nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; VARIABLE =\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; (\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"@TYPE\" = t.[TYPE]\n<br/> \n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ,(\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tInner.XmlItem.query('./child::*')\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FROM @tblShredded tInner\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WHERE tInner.[TYPE] = t.[TYPE]\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FOR XML PATH(''), ELEMENTS, type\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FOR XML PATH('VARIABLE'),type\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; )\n<br/>&nbsp; )\n<br/>FROM @tblShredded t\n<br/>GROUP BY \n<br/>&nbsp; &nbsp; t.[TYPE]\n<br/>FOR XML PATH(''), ROOT('DATA')\n\n</code>\n</blockquote>\n\n<p><b>where</b></p>\n\n<blockquote>\n<code>\n<br/>-- Example Inputs \n<br/>/*\n<br/>DECLARE @xmlListFormat xml\n<br/>SET @xmlListFormat =\n<br/>&nbsp; &nbsp; '\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;XmlListRoot&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;004421UB7&lt;/Item&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;59020UH24&lt;/Item&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;542514NA8&lt;/Item&gt;\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/XmlListRoot&gt;\n<br/>&nbsp; &nbsp; '\n<br/>*/\n<br/>\n<br/>-- =============================================\n<br/>-- Author: 6eorge Jetson\n<br/>-- Create date: 01/22/3003\n<br/>-- Description: Shreds an input XML list conforming to the expected list schema \n<br/>-- =============================================\n<br/>CREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlListFormat xml)\n<br/>RETURNS \n<br/>@tblResults TABLE (XmlItem xml)\n<br/>AS\n<br/>BEGIN\n<br/>\n<br/>&nbsp; &nbsp; INSERT @tblResults\n<br/>&nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; tblShredded.colXmlItem.query('.') as XmlItem\n<br/>&nbsp; &nbsp; FROM\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem)\n<br/>\n<br/>&nbsp; &nbsp; RETURN \n<br/>END\n\n\n</code>\n</blockquote>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15144/" ]
I have a simple table in SQL Server 2005, I wish to convert this to XML (using the "FOR XML" clause). I'm having trouble getting my XML to look like the required output. I've tried looking through various tutorials on the web, but I am struggling. Can someone help? The table I have looks like this ``` TYPE,GROUP,VALUE Books,Hardback,56 Books,Softcover,34 CDs,Singles,45 CDS,Multis,78 ``` The output style I need is: ``` <data> <variable name="TYPE"> <row> <column>GROUP</column> <column>VALUE</column> </row> <row> <column>GROUP</column> <column>VALUE</column> </row> </variable> <variable name="TYPE"> <row> <column>GROUP</column> <column>VALUE</column> </row> <row> <column>GROUP</column> <column>VALUE</column> </row> </variable> </data> ``` **Edit:** As far as I can tell I require the multiple values. I'm generating XML for use with Xcelsius ([Linking XML and Xcelsius](http://xcelsius.files.wordpress.com/2008/05/xml_data_button.pdf)) so have no control over in the formatting of the XML. I can generate the XML using ASP as per the linked tutorial, but I was hoping to get it straight from SQL Server. **Edit 2:** I was hoping for something elegant and tidy... but Godeke's example got the closest. Some fiddling with the SQL and I've come up with: ``` select "type" as '@name', "group" as 'row/column', null as 'row/tmp', "value" as 'row/column' from tableName for xml path('variable'), root('data') ``` Outputs almost in the exact way I wanted. The null/tmp line doesn't even output; it is just preventing the concatenation. Still the tag `<variable name="TYPE">` repeats for each row, which I can't have.
As close as I can get is this: ``` select "type" as '@name', "group" as 'row/column1', "value" as 'row/column2' from tableName for xml path('variable'), root('data') ``` Naming two items the same ("column" and "column") isn't something I know how to do in one pass, but on the other hand it is an odd XML schema choice; normally elements have unique names if they contain distinct data. The obvious choice (name them both 'row/column') simply concatenates them in the output into one value. Also note that each returned row will be a "variable" element distinct from the others. To get the nesting without redundant records will require a subquery: ``` select distinct "type" as '@name' from Agent for xml path('variable'), root('data') ``` was my first thought, but the distinct prevents nesting. All this makes me think that to get the *exact* output you need you might have to use EXPLICIT mode. Perhaps my problem is for something like this I punt and use a DOMDocument in code :).
251,960
<p>I have a long running insert transaction that inserts data into several related tables. </p> <p>When this insert is running, I cannot perform a select * from MainTable. The select just spins its wheels until the insert is done. </p> <p>I will be performing several of these inserts at the same/overlapping time. To check that the information is not inserted twice, I query the MainTable first to see if an entry is there and that its processed bit is not set. </p> <p>During the insert transaction, it flips the MainTable processed bit for that row.</p> <p>So I need to be able to read the table and also be able to tell if the specific row is currently being updated.</p> <p>Any ideas on how to set this up in Microsoft SQL 2005? I am looking through the <a href="http://msdn.microsoft.com/en-us/library/ms173763.aspx" rel="nofollow noreferrer">SET TRANSACTION ISOLATION LEVEL</a> documentation.</p> <p>Thank you,<br> Keith</p> <p><b>EDIT:</b> I do not think that the same insert batch will happen at the same time. These are binary files that are being processed and their data inserted into the database. I check that the file has not been processed before I parse and insert the data. When I do the check, if the file has not been seen before I do a quick insert into the MainTable with the processed bit set false. </p> <p>Is there a way to lock the row being updated instead of the entire table? </p>
[ { "answer_id": 252005, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>The only isolation level that allows one transaction to read changes executed by another transaction in progress (before it commits) is:</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n</code></pre>\n" }, { "answer_id": 252025, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "<p>You may want to rethink your process before you use READ UNCOMMITTED. There are many good reasons for isolated transactions. If you use READ UNCOMMITTED you may still get duplicates because there is a chance both of the inserts will check for updates at the same time and both not finding them creating duplicates. Try breaking it up into smaller batches or issue periodic COMMITS</p>\n\n<p>EDIT</p>\n\n<p>You can wrap the MainTable update in a transaction that will free up that table quicker but you still may get conflicts with the other tables.</p>\n\n<p>ie</p>\n\n<pre><code>BEGIN TRANSACTION\n\nSELECT @ProcessedBit = ProcessedBit FROM MainTable WHERE ID = XXX\n\nIF @ProcessedBit = False\n UPDATE MainTable SET ProcessedBit = True WHERE ID = XXX\n\nCOMMIT TRANSACTION\n\nIF @ProcessedBit = False\nBEGIN\n BEGIN TRANSACTION\n -- start long running process\n ...\n COMMIT TRANSACTION\nEND\n</code></pre>\n\n<p>EDIT to enable error recovery</p>\n\n<pre><code>BEGIN TRANSACTION\n\nSELECT @ProcessedStatus = ProcessedStatus FROM MainTable WHERE ID = XXX\n\nIF @ProcessedStatus = 'Not Processed'\n UPDATE MainTable SET ProcessedBit = 'Processing' WHERE ID = XXX\n\nCOMMIT TRANSACTION\n\nIF @ProcessedStatus = 'Not Processed'\nBEGIN\n BEGIN TRANSACTION\n -- start long running process\n ...\n\n IF No Errors\n BEGIN\n UPDATE MainTable SET ProcessedStatus = 'Processed' WHERE ID = XXX\n COMMIT TRANSACTION\n ELSE\n ROLLBACK TRANSACTION\n\nEND\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
I have a long running insert transaction that inserts data into several related tables. When this insert is running, I cannot perform a select \* from MainTable. The select just spins its wheels until the insert is done. I will be performing several of these inserts at the same/overlapping time. To check that the information is not inserted twice, I query the MainTable first to see if an entry is there and that its processed bit is not set. During the insert transaction, it flips the MainTable processed bit for that row. So I need to be able to read the table and also be able to tell if the specific row is currently being updated. Any ideas on how to set this up in Microsoft SQL 2005? I am looking through the [SET TRANSACTION ISOLATION LEVEL](http://msdn.microsoft.com/en-us/library/ms173763.aspx) documentation. Thank you, Keith **EDIT:** I do not think that the same insert batch will happen at the same time. These are binary files that are being processed and their data inserted into the database. I check that the file has not been processed before I parse and insert the data. When I do the check, if the file has not been seen before I do a quick insert into the MainTable with the processed bit set false. Is there a way to lock the row being updated instead of the entire table?
You may want to rethink your process before you use READ UNCOMMITTED. There are many good reasons for isolated transactions. If you use READ UNCOMMITTED you may still get duplicates because there is a chance both of the inserts will check for updates at the same time and both not finding them creating duplicates. Try breaking it up into smaller batches or issue periodic COMMITS EDIT You can wrap the MainTable update in a transaction that will free up that table quicker but you still may get conflicts with the other tables. ie ``` BEGIN TRANSACTION SELECT @ProcessedBit = ProcessedBit FROM MainTable WHERE ID = XXX IF @ProcessedBit = False UPDATE MainTable SET ProcessedBit = True WHERE ID = XXX COMMIT TRANSACTION IF @ProcessedBit = False BEGIN BEGIN TRANSACTION -- start long running process ... COMMIT TRANSACTION END ``` EDIT to enable error recovery ``` BEGIN TRANSACTION SELECT @ProcessedStatus = ProcessedStatus FROM MainTable WHERE ID = XXX IF @ProcessedStatus = 'Not Processed' UPDATE MainTable SET ProcessedBit = 'Processing' WHERE ID = XXX COMMIT TRANSACTION IF @ProcessedStatus = 'Not Processed' BEGIN BEGIN TRANSACTION -- start long running process ... IF No Errors BEGIN UPDATE MainTable SET ProcessedStatus = 'Processed' WHERE ID = XXX COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION END ```
251,964
<p>I often accidentally create a branch that contains more code than it needs to. When that happens, I delete the branch files, the branch tag, and then start over. The thing that stinks is having to sync the huge pile of data just so I can delete it.</p> <p>Is there a way to delete server-side?</p>
[ { "answer_id": 252038, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 4, "selected": false, "text": "<p>Yes, use sync -k.</p>\n\n<p>Add the path you want to delete to your client, e.g.</p>\n\n<pre><code>//depot/oops/... //your-client/oops/...\n</code></pre>\n\n<p>Then sync that location using the -k option:</p>\n\n<pre><code>p4 sync -k oops/...\n</code></pre>\n\n<p>This will tell Perforce that your client has the files without actually transferring them. Then you can do:</p>\n\n<pre><code>p4 delete oops/...\np4 submit oops/...\n</code></pre>\n\n<p>etc.</p>\n" }, { "answer_id": 2974331, "author": "din", "author_id": 358463, "author_profile": "https://Stackoverflow.com/users/358463", "pm_score": 3, "selected": false, "text": "<p>Use delete -v:</p>\n\n<pre><code>p4 delete -v oops/...\n</code></pre>\n\n<p>This will delete files without syncing into workspace. It is faster than sync -k and then delete.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116/" ]
I often accidentally create a branch that contains more code than it needs to. When that happens, I delete the branch files, the branch tag, and then start over. The thing that stinks is having to sync the huge pile of data just so I can delete it. Is there a way to delete server-side?
Yes, use sync -k. Add the path you want to delete to your client, e.g. ``` //depot/oops/... //your-client/oops/... ``` Then sync that location using the -k option: ``` p4 sync -k oops/... ``` This will tell Perforce that your client has the files without actually transferring them. Then you can do: ``` p4 delete oops/... p4 submit oops/... ``` etc.
251,985
<p>I am binding the dropdown with db entity. </p> <pre><code>ddlCustomer.DataSource = Customer.GetAll(); ddlCustomer.DataTextField = "CustomerName"; ddlCustomer.DataBind(); </code></pre> <p>I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?</p>
[ { "answer_id": 251997, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": 0, "selected": false, "text": "<p>I don't know if there is a one line solution to this, but what i was doing before is, not using DataBind , and first create the ListItem object that will have \"Select\" as the text, then loop through the collection returned from Customer.GetAll() and create a ListItem object for each item in the collection and add it to the drop down list using \"DropDownList.Iems.Add(MyItem)\" , i know it doesn't look very brilliant but it does the job , after all this is what DataBind is doing in behind.</p>\n" }, { "answer_id": 251998, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 3, "selected": true, "text": "<p>Add: </p>\n\n<pre><code>ddlCustomer.Items.Insert(0, \"SELECT\");\n</code></pre>\n\n<p>After ddlCustomer.DataBind();</p>\n\n<p>The item must be inserted after the data bind because the data bind clears the items.</p>\n" }, { "answer_id": 255711, "author": "Stefan", "author_id": 30604, "author_profile": "https://Stackoverflow.com/users/30604", "pm_score": 0, "selected": false, "text": "<p>I know there is an answer already, but you can also do this:</p>\n\n<pre><code>&lt;asp:DropDownList AppendDataBoundItems=\"true\" ID=\"ddlCustomer\" runat=\"server\"&gt;\n &lt;asp:ListItem Value=\"0\" Text=\"Select\"/&gt;\n&lt;/asp:DropDownList&gt;\n</code></pre>\n\n<p>That way, you won't have to worry about when you call Databind and when you add the select-item.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I am binding the dropdown with db entity. ``` ddlCustomer.DataSource = Customer.GetAll(); ddlCustomer.DataTextField = "CustomerName"; ddlCustomer.DataBind(); ``` I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?
Add: ``` ddlCustomer.Items.Insert(0, "SELECT"); ``` After ddlCustomer.DataBind(); The item must be inserted after the data bind because the data bind clears the items.
251,987
<p>Imagine I have a property defined in global.asax. </p> <pre><code>public List&lt;string&gt; Roles { get { ... } set { ... } } </code></pre> <p>I want to use the value in another page. how to I refer to it?</p>
[ { "answer_id": 252004, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>It looks to me like that only depends on the session - so why not make it a pair of static methods which take the session as a parameter? Then you can pass in the value of the \"Session\" property from the page. (Anything which <em>does</em> have access to the HttpApplication can just reference its Session property, of course.)</p>\n" }, { "answer_id": 252013, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "<p>If this is a property you need to access in all pages, you might be better defining a base page which all your other pages extend...</p>\n\n<p>e.g. by default</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page \n{\n}\n</code></pre>\n\n<p>What you could do is add a BasePage.cs to your App_Code folder</p>\n\n<pre><code>public class BasePage : System.Web.UI.Page \n{\n public List&lt;string&gt; Roles\n {\n get { ... }\n set { ... }\n }\n}\n</code></pre>\n\n<p>And then have your pages extend this.</p>\n\n<pre><code>public partial class _Default : BasePage\n{\n}\n</code></pre>\n" }, { "answer_id": 252015, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 5, "selected": true, "text": "<p>You can access the class like this:</p>\n\n<pre><code>((Global)this.Context.ApplicationInstance).Roles\n</code></pre>\n" }, { "answer_id": 252032, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 0, "selected": false, "text": "<p>If the values are dependent on the Session then this is actually simple using the HttpContext.Items Dictionary:</p>\n\n<p>Place this code in the Global.asax to store the value:</p>\n\n<pre><code>Dim someValue As Integer = 5\nContext.Items.Add(\"dataKey\", someValue)\n</code></pre>\n\n<p>Let retreive it in a Page with this code:</p>\n\n<pre><code>Dim someValue As Integer = CType(HttpContext.Current.Items(\"dataKey\"), Integer)\n</code></pre>\n\n<p>Here's a link that describes it in further detail: <a href=\"https://web.archive.org/web/20210608183011/http://aspnet.4guysfromrolla.com/articles/060904-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210608183011/http://aspnet.4guysfromrolla.com/articles/060904-1.aspx</a></p>\n" }, { "answer_id": 252041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Hey, I'm popping my stackoverflow.com cherry! My first answer after lurking for a month.</p>\n\n<p>To access a property defined in your Global class, use either of the following:</p>\n\n<ul>\n<li><p>the Application property defined in both the HttpApplication and Page classes (e.g. Page.Application[\"TestItem\"])</p></li>\n<li><p>the HttpContext.ApplicationInstance property (e.g. HttpContext.Current.ApplicationInstance)</p></li>\n</ul>\n\n<p>With either of these, you can cast the result to your Global type and access the property you need.</p>\n" }, { "answer_id": 1835094, "author": "Marc", "author_id": 110897, "author_profile": "https://Stackoverflow.com/users/110897", "pm_score": 0, "selected": false, "text": "<p>On the global.asax itself for .net 3.5 I used typeof(global_asax) and that worked fine. And, what actually lead me here was implementing the DotNet OpenID examples. I changed some of it to use the Application cache like Will suggested.</p>\n" }, { "answer_id": 4460925, "author": "B Faley", "author_id": 69537, "author_profile": "https://Stackoverflow.com/users/69537", "pm_score": 1, "selected": false, "text": "<p>You can also use the following syntax:</p>\n\n<pre><code>((Global)HttpContext.Current.ApplicationInstance).Roles\n</code></pre>\n" }, { "answer_id": 17617651, "author": "Daniel B", "author_id": 336511, "author_profile": "https://Stackoverflow.com/users/336511", "pm_score": 0, "selected": false, "text": "<p>For other layers of project which it is not possible to have Global as a class:</p>\n\n<pre><code>dynamic roles= ((dynamic)System.Web.HttpContext.Current.ApplicationInstance).Roles;\nif (roles!= null){\n // my codes\n}\n</code></pre>\n\n<p>Just I have to be sure the Roles property in Global class never changes.\nand another way is by reflection.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
Imagine I have a property defined in global.asax. ``` public List<string> Roles { get { ... } set { ... } } ``` I want to use the value in another page. how to I refer to it?
You can access the class like this: ``` ((Global)this.Context.ApplicationInstance).Roles ```
252,028
<p>I have a very strange bug cropping up right now in a fairly massive C++ application at work (massive in terms of CPU and RAM usage as well as code length - in excess of 100,000 lines). This is running on a dual-core Sun Solaris 10 machine. The program subscribes to stock price feeds and displays them on "pages" configured by the user (a page is a window construct customized by the user - the program allows the user to configure such pages). This program used to work without issue until one of the underlying libraries became multi-threaded. The parts of the program affected by this have been changed accordingly. On to my problem. </p> <p>Roughly once in every three executions the program will segfault on startup. This is not necessarily a hard rule - sometimes it'll crash three times in a row then work five times in a row. It's the segfault that's interesting (read: painful). It may manifest itself in a number of ways, but most commonly what will happen is function A calls function B and upon entering function B the frame pointer will suddenly be set to 0x000002. Function A:</p> <pre><code> result_type emit(typename type_trait&lt;T_arg1&gt;::take _A_a1) const { return emitter_type::emit(impl_, _A_a1); } </code></pre> <p>This is a simple signal implementation. impl_ and _A_a1 are well-defined within their frame at the crash. On actual execution of that instruction, we end up at program counter 0x000002. </p> <p>This doesn't always happen on that function. In fact it happens in quite a few places, but this is one of the simpler cases that doesn't leave that much room for error. Sometimes what will happen is a stack-allocated variable will suddenly be sitting on junk memory (always on 0x000002) for no reason whatsoever. Other times, that same code will run just fine. So, my question is, what can mangle the stack so badly? What can actually change the value of the frame pointer? I've certainly never heard of such a thing. About the only thing I can think of is writing out of bounds on an array, but I've built it with a stack protector which should come up with any instances of that happening. I'm also well within the bounds of my stack here. I also don't see how another thread could overwrite the variable on the stack of the first thread since each thread has it's own stack (this is all pthreads). I've tried building this on a linux machine and while I don't get segfaults there, roughly one out of three times it will freeze up on me. </p>
[ { "answer_id": 252059, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>That sounds like a stack overflow problem - something is writing beyond the bounds of an array and trampling over the stack frame (and probably the return address too) on the stack. There's a large literature on the subject. \"The Shell Programmer's Guide\" (2nd Edition) has SPARC examples that may help you.</p>\n" }, { "answer_id": 252063, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 0, "selected": false, "text": "<p>Is something meaning to assign a value of 2 to a variable but instead is assigning its address to 2?</p>\n\n<p>The other details are lost on me but \"2\" is the recurring theme in your problem description. ;)</p>\n" }, { "answer_id": 252070, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>I had that exact problem today and was knee-deep in <code>gdb</code> mud and debugging for a straight hour before occurred to me that I simply wrote over array boundaries (where I didn't expect it the least) of a C array.</p>\n\n<p>So, if possible, use <code>vector</code>s instead because any decend STL implementation will give good compiler messages if you try that in debug mode (whereas C arrays punish you with segfaults).</p>\n" }, { "answer_id": 252085, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>I would second that this definitely sounds like a stack corruption due to out of bound array or buffer writing. Stack protector would be good as long as the writing is sequential, not random.</p>\n" }, { "answer_id": 252097, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what you're calling a \"frame pointer\", as you say:</p>\n\n<blockquote>\n <p>On actual execution of that\n instruction, we end up at program\n counter 0x000002</p>\n</blockquote>\n\n<p>Which makes it sound like the return address is being corrupted. The frame pointer is a pointer that points to the location on the stack of the current function call's context. It may well point to the return address (this is an implementation detail), but the frame pointer itself is not the return address.</p>\n\n<p>I don't think there's enough information here to really give you a good answer, but some things that might be culprits are:</p>\n\n<ul>\n<li><p>incorrect calling convention. If you're calling a function using a calling convention different from how the function was compiled, the stack may become corrupted.</p></li>\n<li><p>RAM hit. Anything writing through a bad pointer can cause garbage to end up on the stack. I'm not familiar with Solaris, but most thread implementations have the threads in the same process address space, so any thread can access any other thread's stack. One way a thread can get a pointer into another thread's stack is if the address of a local variable is passed to an API that ultimately deals with the pointer on a different thread. unless you synchronize things properly, this will end up with the pointer accessing invalid data. Given that you're dealing with a \"simple signal implementation\", it seems like it's possible that one thread is sending a signal to another. Maybe one of the parameters in that signal has a pointer to a local?</p></li>\n</ul>\n" }, { "answer_id": 252124, "author": "Steve Fallows", "author_id": 18882, "author_profile": "https://Stackoverflow.com/users/18882", "pm_score": 0, "selected": false, "text": "<p>I second the notion that it is likely stack corruption. I'll add that the switch to a multi-threaded library makes me suspicious that what has happened is a lurking bug has been exposed. Possibly the sequencing the buffer overflow was occurring on unused memory. Now it's hitting another thread's stack. There are many other possible scenarios.</p>\n\n<p>Sorry if that doesn't give much of a hint at how to find it.</p>\n" }, { "answer_id": 252153, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 3, "selected": false, "text": "<p>Stack corruption, 99.9% definitely.</p>\n\n<p>The smells you should be looking carefully for are:-</p>\n\n<ul>\n<li>Use of 'C' arrays</li>\n<li>Use of 'C' strcpy-style functions</li>\n<li>memcpy</li>\n<li>malloc and free</li>\n<li>thread-safety of anything using pointers</li>\n<li>Uninitialised POD variables.</li>\n<li>Pointer Arithmetic</li>\n<li>Functions trying to return local variables by reference</li>\n</ul>\n" }, { "answer_id": 252157, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 1, "selected": false, "text": "<p>With C++ unitialized variables and race conditions are likely suspects for intermittent crashes.</p>\n" }, { "answer_id": 252195, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 1, "selected": false, "text": "<p>Is it possible to run the thing through Valgrind? Perhaps Sun provides a similar tool. Intel VTune (Actually I was thinking of Thread Checker) also has some very nice tools for thread debugging and such.</p>\n\n<p>If your employer can spring for the cost of the more expensive tools, they can really make these sorts of problems a lot easier to solve.</p>\n" }, { "answer_id": 252273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I tried Valgrind on it, but unfortunately it doesn't detect stack errors:</p>\n\n<p>\"In addition to the performance penalty an important limitation of Valgrind is its inability to detect bounds errors in the use of static or stack allocated data.\"</p>\n\n<p>I tend to agree that this is a stack overflow problem. The tricky thing is tracking it down. Like I said, there's over 100,000 lines of code to this thing (including custom libraries developed in-house - some of it going as far back as 1992) so if anyone has any good tricks for catching that sort of thing, I'd be grateful. There's arrays being worked on all over the place and the app uses OI for its GUI (if you haven't heard of OI, be grateful) so just looking for a logical fallacy is a mammoth task and my time is short. </p>\n\n<p>Also agreed that the 0x000002 is suspect. It is about the only constant between crashes. Even weirder is the fact that this only cropped up with the multi-threaded switch. I think that the smaller stack as a result of the multiple-threads is what's making this crop up now, but that's pure supposition on my part. </p>\n\n<p>No one asked this, but I built with gcc-4.2. Also, I can guarantee ABI safety here so that's also not the issue. As for the \"garbage at the end of the stack\" on the RAM hit, the fact that it is universally 2 (though in different places in the code) makes me doubt that as garbage tends to be random. </p>\n" }, { "answer_id": 252360, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": "<p>It's not hard to mangle the frame pointer - if you look at the disassembly of a routine you will see that it is pushed at the start of a routine and pulled at the end - so if anything overwrites the stack it can get lost. The stack pointer is where the stack is currently at - and the frame pointer is where it started at (for the current routine).</p>\n\n<p>Firstly I would verify that all of the libraries and related objects have been rebuilt clean and all of the compiler options are consistent - I've had a similar problem before (Solaris 2.5) that was caused by an object file that hadn't been rebuilt. </p>\n\n<p>It sounds exactly like an overwrite - and putting guard blocks around memory isn't going to help if it is simply a bad offset.</p>\n\n<p>After each core dump examine the core file to learn as much as you can about the similarities between the faults. Then try to identify what is getting overwritten. As I remember the frame pointer is the last stack pointer - so anything logically before the frame pointer shouldn't be modified in the current stack frame - so maybe record this and copy it elsewhere and compare upon return.</p>\n" }, { "answer_id": 254262, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>There's some confusion here between <strong><em>stack overflow</em></strong> and <strong><em>stack corruption.</em></strong></p>\n\n<p><strong>Stack Overflow</strong> is a very specific issue cause by try to use using more stack than the operating system has allocated to your thread. The three normal causes are like this.</p>\n\n<pre><code>void foo()\n{\n foo(); // endless recursion - whoops!\n}\n\nvoid foo2()\n{\n char myBuffer[A_VERY_BIG_NUMBER]; // The stack can't hold that much.\n}\n\nclass bigObj\n{\n char myBuffer[A_VERY_BIG_NUMBER]; \n}\n\nvoid foo2( bigObj big1) // pass by value of a big object - whoops!\n{\n}\n</code></pre>\n\n<p>In embedded systems, thread stack size may be measured in bytes and even a simple calling sequence can cause problems. By default on windows, each thread gets 1 Meg of stack, so causing stack overflow is much less of a common problem. Unless you have endless recursion, stack overflows can always be mitigated by increasing the stack size, even though this usually is NOT the best answer.</p>\n\n<p><strong>Stack Corruption</strong> simply means writing outside the bounds of the current stack frame, thus potentially corrupting other data - or return addresses on the stack.</p>\n\n<p>At it's simplest:-</p>\n\n<pre><code>void foo()\n{ \n char message[10];\n\n message[10] = '!'; // whoops! beyond end of array\n}\n</code></pre>\n" }, { "answer_id": 254923, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Also agreed that the 0x000002 is suspect. It is about the only constant between crashes. Even weirder is the fact that this only cropped up with the multi-threaded switch. I think that the smaller stack as a result of the multiple-threads is what's making this crop up now, but that's pure supposition on my part. </p>\n</blockquote>\n\n<p>If you pass anything on the stack by reference or by address, this would most certainly happen if another thread tried to use it after the first thread returned from a function.</p>\n\n<p>You might be able to repro this by forcing the app onto a single processor. I don't know how you do that with Sparc.</p>\n" }, { "answer_id": 742773, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": 0, "selected": false, "text": "<p>It is impossible to know, but here are some hints that I can come up with.</p>\n\n<ul>\n<li>In pthreads you must allocate the stack and pass it to the thread. Did you allocate enough? There is no automatic stack growth like in a single threaded process.</li>\n<li>If you are sure that you don't corrupt the stack by writing past stack allocated data check for rouge pointers (mostly uninitialized pointers).</li>\n<li>One of the threads could overwrite some data that others depend on (check your data synchronisation).</li>\n<li>Debugging is usually not very helpful here. I would try to create lots of log output (traces for entry and exit of every function/method call) and then analyze the log.</li>\n<li>The fact that the error manifest itself differently on Linux may help. What thread mapping are you using on Solaris? Make sure you map every thread to it's own LWP to ease the debugging.</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a very strange bug cropping up right now in a fairly massive C++ application at work (massive in terms of CPU and RAM usage as well as code length - in excess of 100,000 lines). This is running on a dual-core Sun Solaris 10 machine. The program subscribes to stock price feeds and displays them on "pages" configured by the user (a page is a window construct customized by the user - the program allows the user to configure such pages). This program used to work without issue until one of the underlying libraries became multi-threaded. The parts of the program affected by this have been changed accordingly. On to my problem. Roughly once in every three executions the program will segfault on startup. This is not necessarily a hard rule - sometimes it'll crash three times in a row then work five times in a row. It's the segfault that's interesting (read: painful). It may manifest itself in a number of ways, but most commonly what will happen is function A calls function B and upon entering function B the frame pointer will suddenly be set to 0x000002. Function A: ``` result_type emit(typename type_trait<T_arg1>::take _A_a1) const { return emitter_type::emit(impl_, _A_a1); } ``` This is a simple signal implementation. impl\_ and \_A\_a1 are well-defined within their frame at the crash. On actual execution of that instruction, we end up at program counter 0x000002. This doesn't always happen on that function. In fact it happens in quite a few places, but this is one of the simpler cases that doesn't leave that much room for error. Sometimes what will happen is a stack-allocated variable will suddenly be sitting on junk memory (always on 0x000002) for no reason whatsoever. Other times, that same code will run just fine. So, my question is, what can mangle the stack so badly? What can actually change the value of the frame pointer? I've certainly never heard of such a thing. About the only thing I can think of is writing out of bounds on an array, but I've built it with a stack protector which should come up with any instances of that happening. I'm also well within the bounds of my stack here. I also don't see how another thread could overwrite the variable on the stack of the first thread since each thread has it's own stack (this is all pthreads). I've tried building this on a linux machine and while I don't get segfaults there, roughly one out of three times it will freeze up on me.
Stack corruption, 99.9% definitely. The smells you should be looking carefully for are:- * Use of 'C' arrays * Use of 'C' strcpy-style functions * memcpy * malloc and free * thread-safety of anything using pointers * Uninitialised POD variables. * Pointer Arithmetic * Functions trying to return local variables by reference
252,066
<p>Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?</p>
[ { "answer_id": 252075, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 2, "selected": false, "text": "<p>You need to pass a <a href=\"http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx\" rel=\"nofollow noreferrer\">IComparer</a> object or <a href=\"http://msdn.microsoft.com/en-us/library/tfakywbh.aspx\" rel=\"nofollow noreferrer\">Comparison</a> delegate to the Sort function.<br/></p>\n\n<p>Here is a sample code from C# 2.0</p>\n\n<pre><code> Array.Sort(array,delegate(string a, string b)\n {\n return b.CompareTo(a);\n });\n</code></pre>\n\n<p>EDIT: missed the array bit.</p>\n" }, { "answer_id": 252080, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>Provide an appropriate element comparer. What C# version do you use? 3 lets you do this:</p>\n\n<pre><code>Array.Sort(myarray, (a, b) =&gt; b.CompareTo(a));\n</code></pre>\n" }, { "answer_id": 252090, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": 1, "selected": false, "text": "<p>if you use a different comparitor that is the reverse of the standard that would do it.</p>\n\n<p>Alternatively sort it normally and then reverse it...</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?
Provide an appropriate element comparer. What C# version do you use? 3 lets you do this: ``` Array.Sort(myarray, (a, b) => b.CompareTo(a)); ```
252,149
<p>The following is code I've used to create a <code>memory mapped file</code>:</p> <pre><code>fid = open(filename, O_CREAT | O_RDWR, 0660); if ( 0 &gt; fid ) { throw error; } /* mapped offset pointer to data file */ offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP); /* Initialize table */ memset(offset_table_p, 0x00, (table_size + 1) * 2); </code></pre> <p>say table_size is around 2XXXXXXXX bytes.</p> <p>During debug, I've noticed it fails while attempt to initializing the 'offset table pointer',</p> <p>Can anyone provide me some inputs on why it's failing during intilalization? is there any possibilities that my memory map file was not created with required table size?</p>
[ { "answer_id": 252261, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>First things first:</p>\n\n<p>Examine the file both before and after the open() call. If on Linux, you can use the code:</p>\n\n<pre><code>char paxbuff[1000]; // at start of function\nsprintf (paxbuff,\"ls -al %s\",filename);\nsystem (paxbuff);\nfid = open(filename, O_CREAT | O_RDWR, 0660); // this line already exists.\nsystem (paxbuff);\n</code></pre>\n\n<p>Then, after you call shmat(), check the return values and size thus:</p>\n\n<pre><code>offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP); // already exists.\nprintf (\"ret = %p, errno = %d\\n\",offset_table_p,errno);\nprintf (\"sz = %d\\n\",table_size);\n</code></pre>\n\n<p>That should be enough to work out the problem.</p>\n" }, { "answer_id": 252328, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>As far as I can tell from reading documentation, you are doing it completely wrong. </p>\n\n<p>Either use open() and mmap() or use shmget() and shmat().</p>\n\n<p>If you use open() you will need to make the file long enough first. Use ftruncate() for that.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The following is code I've used to create a `memory mapped file`: ``` fid = open(filename, O_CREAT | O_RDWR, 0660); if ( 0 > fid ) { throw error; } /* mapped offset pointer to data file */ offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP); /* Initialize table */ memset(offset_table_p, 0x00, (table_size + 1) * 2); ``` say table\_size is around 2XXXXXXXX bytes. During debug, I've noticed it fails while attempt to initializing the 'offset table pointer', Can anyone provide me some inputs on why it's failing during intilalization? is there any possibilities that my memory map file was not created with required table size?
As far as I can tell from reading documentation, you are doing it completely wrong. Either use open() and mmap() or use shmget() and shmat(). If you use open() you will need to make the file long enough first. Use ftruncate() for that.
252,179
<p>What is the best way to check if a given url points to a valid file (i.e. not return a 404/301/etc.)? I've got a script that will load certain .js files on a page, but I need a way to verify each URL it receives points to a valid file.</p> <p>I'm still poking around the PHP manual to see which file functions (if any) will actually work with remote URLs. I'll edit my post as I find more details, but if anyone has already been down this path feel free to chime in.</p>
[ { "answer_id": 252183, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 0, "selected": false, "text": "<p>one such way would be to request the url and get a response with a status code of 200 back, aside from that, there's really no good way because the server has the option of handling the request however it likes (including giving you other status codes for files that exist, but you don't have access to for a number of reasons).</p>\n" }, { "answer_id": 252335, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "<p>If your server doesn't have fopen wrappers enabled (any server with decent security won't), then you'll have to use the <a href=\"http://us2.php.net/curl\" rel=\"nofollow noreferrer\">CURL functions</a>.</p>\n" }, { "answer_id": 252418, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 4, "selected": true, "text": "<p>The file_get_contents is a bit overshooting the purpose as it is enough to have the HTTP header to make the decision, so you'll need to use curl to do so:</p>\n\n<pre><code>&lt;?php\n// create a new cURL resource\n$ch = curl_init();\n\n// set URL and other appropriate options\ncurl_setopt($ch, CURLOPT_URL, \"http://www.example.com/\");\ncurl_setopt($ch, CURLOPT_HEADER, 1);\ncurl_setopt($ch, CURLOPT_NOBODY, 1);\n\n// grab URL and pass it to the browser\ncurl_exec($ch);\n\n// close cURL resource, and free up system resources\ncurl_close($ch);\n?&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
What is the best way to check if a given url points to a valid file (i.e. not return a 404/301/etc.)? I've got a script that will load certain .js files on a page, but I need a way to verify each URL it receives points to a valid file. I'm still poking around the PHP manual to see which file functions (if any) will actually work with remote URLs. I'll edit my post as I find more details, but if anyone has already been down this path feel free to chime in.
The file\_get\_contents is a bit overshooting the purpose as it is enough to have the HTTP header to make the decision, so you'll need to use curl to do so: ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ?> ```
252,202
<p>In my database I have tables that define types for example</p> <p>Table: Publication Types</p> <pre> ID | Type ---------- 1 | Article 2 | Abstract 3 | Book .... </pre> <p>Which is related through the ID key to a publication tables which has the field <em>TypeID</em>.</p> <p>I then create a PublicationTable data table my .NET application which I want to filter based on the publication type. For example the following function gives me the number of publications for a specific author and publication type.</p> <pre> Public Function countPublications(ByVal authorID As Integer, _ ByVal publicationType As Integer) As Integer Dim authPubs As New PublicationsDataSet.tblPublicationsDataTable authPubs = Me.getAuthorsPublications(authorID) Dim dv As New DataView(authPubs) dv.RowFilter = "status='published' AND type='" + _ publicationType.ToString + "'" Return dv.Count End Function </pre> <p>To call this function to get a count of articles by an author of a specific type, I could</p> <ol> <li><p>call the function with two integers</p> <p>countPublications(authorID, 1)</p></li> <li><p>setup an enum so that I can write</p> <p>countPublications(authorID, pubType.Article)</p> <p>or </p></li> <li><p>somehow use the publication type table to filter the publication data set but I haven't got my head around how to do this.</p></li> </ol> <p>What other approaches should I consider.</p> <p>Thanks</p>
[ { "answer_id": 252212, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "<p>if publication types are essentially static, enums are fine</p>\n\n<p>there is arguably little difference between embedding </p>\n\n<pre><code>inner join lookuptable lt on lt.id = (int)myenum.sometype \n</code></pre>\n\n<p>in a query and adding </p>\n\n<pre><code>inner join lookuptable lt on lt.name = \"somehardcodeddescription\"\n</code></pre>\n\n<p>they're both embedded constants, the former just has a well-defined type behind it</p>\n\n<p>alternately you could use</p>\n\n<pre><code>inner join lookuptable lt on lt.name = myenum.sometype.ToString\n</code></pre>\n\n<p>i prefer the former</p>\n\n<p>if, on the other hand, new lookup types may be added after the code is deployed, then an enum will quickly become outdated; </p>\n\n<p>but if there is core set of static enum values that the code needs and the rest don't matter then the former solution is still fine</p>\n\n<p>as usual, \"it depends\" ;-)</p>\n" }, { "answer_id": 252278, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "<p>Having maintained this sort of thing in a previous life, I agree with Steven that an <code>enum</code> is quite reasonable. Your code is clear, and an <code>enum</code> means you need to update only a single file if you add data types.</p>\n\n<p>I'd also suggest commenting the <code>enum</code>, making it clear that the values need to match those in the <code>Publication Types</code> table in your database.</p>\n\n<p>Good question, by the way! +1 for explaining the question so clearly and taking the time to brainstorm solutions before posting.</p>\n" }, { "answer_id": 252368, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>I think it depends on how often your list of publication types will be changing in the future, and on how easily you can push out an update of your application. If the list won't change often, or if updating your app in the field is easy, then an enum makes sense. If the list is likely to change frequently, or if updating your app is particularly difficult, then keeping the list in a table in the database is sensible.</p>\n" }, { "answer_id": 254091, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 0, "selected": false, "text": "<p>For various reasons it would be nice to keep lists such as my publication type list and others in one place; the database. Then there is only one place for them to change. However, it seems to me that this adds some complexity to the code and I would still need to have some hard coded elements in the code if I wanted to refer to a specific publication type such as Journal Articles. Therefore, having an enumerated type that reflects the data in the table gives me the possibility of calling my count function in a readable manner</p>\n\n<pre><code>countPublications(authorID, publicationType.JournalArticle)\n</code></pre>\n\n<p>If the data in the table changes which is unlikely, I can have a comment in the database to remind the maintainer (probably me) to update the enumerated type in the code and vice versa. </p>\n\n<p>Thank you all for your answers. I can now proceed with my mind at ease.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4612/" ]
In my database I have tables that define types for example Table: Publication Types ``` ID | Type ---------- 1 | Article 2 | Abstract 3 | Book .... ``` Which is related through the ID key to a publication tables which has the field *TypeID*. I then create a PublicationTable data table my .NET application which I want to filter based on the publication type. For example the following function gives me the number of publications for a specific author and publication type. ``` Public Function countPublications(ByVal authorID As Integer, _ ByVal publicationType As Integer) As Integer Dim authPubs As New PublicationsDataSet.tblPublicationsDataTable authPubs = Me.getAuthorsPublications(authorID) Dim dv As New DataView(authPubs) dv.RowFilter = "status='published' AND type='" + _ publicationType.ToString + "'" Return dv.Count End Function ``` To call this function to get a count of articles by an author of a specific type, I could 1. call the function with two integers countPublications(authorID, 1) 2. setup an enum so that I can write countPublications(authorID, pubType.Article) or 3. somehow use the publication type table to filter the publication data set but I haven't got my head around how to do this. What other approaches should I consider. Thanks
if publication types are essentially static, enums are fine there is arguably little difference between embedding ``` inner join lookuptable lt on lt.id = (int)myenum.sometype ``` in a query and adding ``` inner join lookuptable lt on lt.name = "somehardcodeddescription" ``` they're both embedded constants, the former just has a well-defined type behind it alternately you could use ``` inner join lookuptable lt on lt.name = myenum.sometype.ToString ``` i prefer the former if, on the other hand, new lookup types may be added after the code is deployed, then an enum will quickly become outdated; but if there is core set of static enum values that the code needs and the rest don't matter then the former solution is still fine as usual, "it depends" ;-)
252,203
<p>I am using the following code to check if a variable is not nil and not zero</p> <pre><code>if(discount != nil &amp;&amp; discount != 0) ... end </code></pre> <p>Is there a better way to do this?</p>
[ { "answer_id": 252214, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 0, "selected": false, "text": "<p>You could initialize discount to 0 as long as your code is guaranteed not to try and use it before it is initialized. That would remove one check I suppose, I can't think of anything else.</p>\n" }, { "answer_id": 252220, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": false, "text": "<p>You could do this:</p>\n\n<pre><code>if (!discount.nil? &amp;&amp; !discount.zero?)\n</code></pre>\n\n<p>The order is important here, because if <code>discount</code> is <code>nil</code>, then it will not have a <code>zero?</code> method. Ruby's short-circuit evaluation should prevent it from trying to evaluate <code>discount.zero?</code>, however, if <code>discount</code> is <code>nil</code>.</p>\n" }, { "answer_id": 252253, "author": "Dejan Simic", "author_id": 32720, "author_profile": "https://Stackoverflow.com/users/32720", "pm_score": 10, "selected": true, "text": "<pre>\nunless discount.nil? || discount == 0\n # ...\nend\n</pre>\n" }, { "answer_id": 252272, "author": "Dejan Simic", "author_id": 32720, "author_profile": "https://Stackoverflow.com/users/32720", "pm_score": 5, "selected": false, "text": "<pre>\nunless [nil, 0].include?(discount) \n # ...\nend\n</pre>\n" }, { "answer_id": 252330, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 5, "selected": false, "text": "<pre><code>class Object\n def nil_zero?\n self.nil? || self == 0\n end\nend\n\n# which lets you do\nnil.nil_zero? # returns true\n0.nil_zero? # returns true\n1.nil_zero? # returns false\n\"a\".nil_zero? # returns false\n\nunless discount.nil_zero?\n # do stuff...\nend\n</code></pre>\n\n<p>Beware of the usual disclaimers... great power/responsibility, monkey patching leading to the dark side etc.</p>\n" }, { "answer_id": 253366, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 4, "selected": false, "text": "<pre><code>if (discount||0) != 0\n #...\nend\n</code></pre>\n" }, { "answer_id": 255215, "author": "Jeff Waltzer", "author_id": 23513, "author_profile": "https://Stackoverflow.com/users/23513", "pm_score": -1, "selected": false, "text": "<p>I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.</p>\n\n<pre><code>if discount != 0\nend\n</code></pre>\n" }, { "answer_id": 5321351, "author": "rubyprince", "author_id": 584440, "author_profile": "https://Stackoverflow.com/users/584440", "pm_score": 2, "selected": false, "text": "<pre><code>if discount and discount != 0\n ..\nend\n</code></pre>\n\n<p>update, it will <code>false</code> for <code>discount = false</code></p>\n" }, { "answer_id": 12599075, "author": "oivoodoo", "author_id": 171350, "author_profile": "https://Stackoverflow.com/users/171350", "pm_score": 4, "selected": false, "text": "<p>You can convert your empty row to integer value and check zero?.</p>\n\n<pre><code>\"\".to_i.zero? =&gt; true\nnil.to_i.zero? =&gt; true\n</code></pre>\n" }, { "answer_id": 20012233, "author": "rewritten", "author_id": 384417, "author_profile": "https://Stackoverflow.com/users/384417", "pm_score": 5, "selected": false, "text": "<p>ok, after 5 years have passed....</p>\n\n<pre><code>if discount.try :nonzero?\n ...\nend\n</code></pre>\n\n<p>It's important to note that <code>try</code> is defined in the ActiveSupport gem, so it is not available in plain ruby.</p>\n" }, { "answer_id": 30522783, "author": "Dave G-W", "author_id": 3614669, "author_profile": "https://Stackoverflow.com/users/3614669", "pm_score": 2, "selected": false, "text": "<p>You can take advantage of the <code>NilClass</code> provided <code>#to_i</code> method, which will return zero for <code>nil</code> values:</p>\n\n<pre><code>unless discount.to_i.zero?\n # Code here\nend\n</code></pre>\n\n<p>If <code>discount</code> can be fractional numbers, you can use <code>#to_f</code> instead, to prevent the number from being rounded to zero.</p>\n" }, { "answer_id": 32566847, "author": "pastullo", "author_id": 1490947, "author_profile": "https://Stackoverflow.com/users/1490947", "pm_score": 1, "selected": false, "text": "<p>When dealing with a <strong>database record</strong>, I like to initialize all empty values with 0, using the migration helper:</p>\n\n<pre><code>add_column :products, :price, :integer, default: 0\n</code></pre>\n" }, { "answer_id": 34819818, "author": "ndnenkov", "author_id": 2423164, "author_profile": "https://Stackoverflow.com/users/2423164", "pm_score": 5, "selected": false, "text": "<p>From Ruby 2.3.0 onward, you can combine the safe navigation operator (<code>&amp;.</code>) with <a href=\"http://ruby-doc.org/core-2.3.0/Numeric.html#method-i-nonzero-3F\" rel=\"noreferrer\"><code>Numeric#nonzero?</code></a>. <code>&amp;.</code> returns <code>nil</code> if the instance was <code>nil</code> and <code>nonzero?</code> - if the number was <code>0</code>:</p>\n\n<pre><code>if discount&amp;.nonzero?\n # ...\nend\n</code></pre>\n\n<p>Or postfix:</p>\n\n<pre><code>do_something if discount&amp;.nonzero?\n</code></pre>\n" }, { "answer_id": 36447296, "author": "Saroj", "author_id": 5293076, "author_profile": "https://Stackoverflow.com/users/5293076", "pm_score": 2, "selected": false, "text": "<pre><code>def is_nil_and_zero(data)\n data.blank? || data == 0 \nend \n</code></pre>\n\n<p>If we pass \"\" it will return false whereas blank? returns true.\nSame is the case when data = false\nblank? returns true for nil, false, empty, or a whitespace string.\nSo it's better to use blank? method to avoid empty string as well.</p>\n" }, { "answer_id": 38489061, "author": "Abhinay Reddy Keesara", "author_id": 6495570, "author_profile": "https://Stackoverflow.com/users/6495570", "pm_score": 1, "selected": false, "text": "<pre><code>if discount.nil? || discount == 0\n [do something]\nend\n</code></pre>\n" }, { "answer_id": 52403584, "author": "RichOrElse", "author_id": 6913691, "author_profile": "https://Stackoverflow.com/users/6913691", "pm_score": -1, "selected": false, "text": "<p>Alternative solution is to use Refinements, like so:</p>\n\n<pre><code>module Nothingness\n refine Numeric do\n alias_method :nothing?, :zero?\n end\n\n refine NilClass do\n alias_method :nothing?, :nil?\n end\nend\n\nusing Nothingness\n\nif discount.nothing?\n # do something\nend\n</code></pre>\n" }, { "answer_id": 62130247, "author": "Ozesh", "author_id": 3436775, "author_profile": "https://Stackoverflow.com/users/3436775", "pm_score": 2, "selected": false, "text": "<p>I prefer using a more cleaner approach : </p>\n\n<pre><code>val.to_i.zero?\n</code></pre>\n\n<p><code>val.to_i</code> will return a <code>0</code> if <strong>val</strong> is a <code>nil</code>,</p>\n\n<p>after that, all we need to do is check whether the final value is a <strong>zero</strong>.</p>\n" }, { "answer_id": 64062974, "author": "NIshank", "author_id": 6014558, "author_profile": "https://Stackoverflow.com/users/6014558", "pm_score": 2, "selected": false, "text": "<p>Yes, we do have a clean way in ruby.</p>\n<pre><code>discount.to_f.zero?\n</code></pre>\n<p>This check handles good amount of cases i.e. discount may be nil, discount may be int 0, discount may be float 0.0, discount may be string &quot;0.0&quot;, &quot;0&quot;.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
I am using the following code to check if a variable is not nil and not zero ``` if(discount != nil && discount != 0) ... end ``` Is there a better way to do this?
``` unless discount.nil? || discount == 0 # ... end ```
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow noreferrer">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow noreferrer">t-shirt</a>.</p>
[ { "answer_id": 252296, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>What if it doesn't mean anything, what if it is just a neat design they came up with?</p>\n" }, { "answer_id": 252329, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 3, "selected": false, "text": "<p>I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.</p>\n\n<p>Which block do you like best?</p>\n" }, { "answer_id": 252344, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p>Well, I can't see an immediate pattern. But if you are testing IP, why not take two blocks of 4 as a single binary number.</p>\n" }, { "answer_id": 252345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I think it's <em>simply</em> a design, nothing secret, or mysterious.</p>\n" }, { "answer_id": 260580, "author": "Joseph", "author_id": 2209, "author_profile": "https://Stackoverflow.com/users/2209", "pm_score": 5, "selected": true, "text": "<p>I emailed the Website Optimizer Team, and they said \"There's no secret code, unless you find one. :)\"</p>\n" }, { "answer_id": 260595, "author": "F.D.Castel", "author_id": 33244, "author_profile": "https://Stackoverflow.com/users/33244", "pm_score": 1, "selected": false, "text": "<p>It says: \"You are getting closer\".</p>\n" }, { "answer_id": 483491, "author": "guerda", "author_id": 32043, "author_profile": "https://Stackoverflow.com/users/32043", "pm_score": 0, "selected": false, "text": "<p>Probably it's a base 4 notation?</p>\n\n<p>I would try that, but I don't have any approach to this.</p>\n" }, { "answer_id": 3260996, "author": "gnrfan", "author_id": 54187, "author_profile": "https://Stackoverflow.com/users/54187", "pm_score": 0, "selected": false, "text": "<p>It reminded me of cellular automata:</p>\n\n<p><a href=\"http://www.wolframalpha.com/input/?i=rule+110\" rel=\"nofollow noreferrer\">http://www.wolframalpha.com/input/?i=rule+110</a></p>\n\n<p>Anyone going that direction?</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28486/" ]
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg) So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. ``` #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print ``` [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg).
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
252,222
<p>What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.</p> <p>Here is my current source code:</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; function AccessMyHiddenField() { var HiddenValue = document.getElementById("&lt;%= MyHiddenField.ClientID %&gt;").value; //do my thing thing..... } &lt;/script&gt; &lt;asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false"&gt; &lt;asp:HiddenField ID="MyHiddenField" runat="server" /&gt; &lt;/asp:PlaceHolder&gt; </code></pre> <p><b>EDIT:</b> How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style</p> <p><b>UPDATE:</b> I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.</p> <p><b>UPDATE 2:</b> I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control. </p>
[ { "answer_id": 252228, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "<p>If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible=\"true\"</p>\n\n<p>Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.</p>\n" }, { "answer_id": 252231, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 4, "selected": true, "text": "<p>My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response.\nMy suggestion to solve your problem is</p>\n\n<ol>\n<li>Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.</li>\n<li><p>If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :</p>\n\n<p>placeholderId.Attributes[\"style\"] = \"display:none\";</p></li>\n</ol>\n\n<p>Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.</p>\n" }, { "answer_id": 252235, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": 1, "selected": false, "text": "<p>If the place holder visibility is set to false, it will never be rendered , and the hidden field value will be only stored in the ViewState of the page.</p>\n\n<p>just one question, why are you setting the visibility of the place holder to be false , if its containing a hidden field?</p>\n\n<p>Anyway one possible way to get over this issue, is adding a TextBox or Label object , and set the display CSS style of it to \"none\" , then in your code copy whatever you are putting in the hidden field into the textbox/lable text property, this way you can easily read the value using javascript , since the textbox/label will be rendered but not visible to others, though this might not be that safe thing to do.</p>\n" }, { "answer_id": 252236, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>Visible doesn't actually make it visible, you can leave it default. Just runat=\"server\" and use its .Value.</p>\n" }, { "answer_id": 252241, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 1, "selected": false, "text": "<p>Instead of making \".visible=false\", change the style to \"display: none;\". That will render your control but make it invisible.</p>\n" }, { "answer_id": 11045023, "author": "BinuAmitSanish", "author_id": 1457853, "author_profile": "https://Stackoverflow.com/users/1457853", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function popup(lid)\n{\n var linkid=lid.id.toString(); \n var lengthid=linkid.length-25; \n var idh=linkid.substring(0,parseInt(lengthid)); \n var hid=idh+\"hiddenfield1\";\n\n var gv = document.getElementById(\"&lt;%=GridViewComplaints.ClientID %&gt;\");\n var gvRowCount = gv.rows.length;\n var rwIndex = 1;\n var username=gv.rows[rwIndex].cells[1].childNodes[1].innerHTML;\n var prdid=gv.rows[rwIndex].cells[3].childNodes[1].innerHTML;\n var msg=document.getElementById(hid.toString()).value;\n alert(msg);\n\n\n document.getElementById('&lt;%= Labelcmpnme.ClientID %&gt;').innerHTML=username;\n document.getElementById('&lt;%= Labelprdid.ClientID %&gt;').innerHTML=prdid;\n document.getElementById('&lt;%= TextBoxviewmessage.ClientID %&gt;').value=msg;\n return false;\n}\n</code></pre>\n\n<p><br></p>\n\n<pre><code>&lt;ItemTemplate&gt;\n &lt;asp:LinkButton ID=\"LabelComplaintdisplayitem\" runat =\"server\" Text='&lt;%#Eval(\"ComplaintDisp\").ToString().Length&gt;5?Eval(\"ComplaintDisp\").ToString().Substring(0,5)+\"....\":Eval(\"ComplaintDisp\") %&gt;' CommandName =\"viewmessage\" CommandArgument ='&lt;%#Eval(\"username\")+\";\"+Eval(\"productId\")+\";\"+Eval(\"ComplaintDisp\") %&gt;' class='basic' OnClientClick =\" return popup(this)\"&gt;&lt;/asp:LinkButton&gt;\n &lt;asp:HiddenField ID=\"hiddenfield1\" runat =\"server\" Value='&lt;%#Eval(\"ComplaintDisp\")%&gt;'/&gt;\n&lt;/ItemTemplate&gt;\n</code></pre>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback. Here is my current source code: ``` <script language="javascript" type="text/javascript"> function AccessMyHiddenField() { var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value; //do my thing thing..... } </script> <asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false"> <asp:HiddenField ID="MyHiddenField" runat="server" /> </asp:PlaceHolder> ``` **EDIT:** How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style **UPDATE:** I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this. **UPDATE 2:** I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is 1. Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css. 2. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically : placeholderId.Attributes["style"] = "display:none"; Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
252,230
<p>First of all there is a <a href="https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder">partial question</a> regarding this, but it is not exactly what I'm asking, so, bear with me and go for it.</p> <p>My question is, after looking at what <a href="http://subsonicproject.com/" rel="nofollow noreferrer">SubSonic</a> does and the excellent videos from Rob Connery I need to ask: <strong>Shall we use a tool like this and do Inline queries or</strong> shall we do the queries <strong>using</strong> a call to the <strong>stored procedure?</strong></p> <p>I don't want to minimize any work from Rob (which I think it's amazing) but I just want your opinion on this cause I need to start a new project and I'm in the middle of the line; shall I use SubSonic (or other like tool, like NHibernate) or I just continue my method that is always call a stored procedure even if it's a simple as</p> <pre><code>Select this, that from myTable where myStuff = StackOverflow; </code></pre>
[ { "answer_id": 252232, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": true, "text": "<p>It doesn't need to be one or the other. If it's a simple query, use the SubSonic query tool. If it's more complex, use a stored procedure and load up a collection or create a dataset from the results.</p>\n\n<p>See here: <a href=\"https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code\">What are the pros and cons to keeping SQL in Stored Procs versus Code</a> and here <a href=\"https://stackoverflow.com/questions/228175/subsonic-and-stored-procedures\">SubSonic and Stored Procedures</a></p>\n" }, { "answer_id": 252234, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>See answers <a href=\"https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code\">here</a> and <a href=\"https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder\">here</a>. I use sprocs whenever I can, except when red tape means it takes a week to make it into the database.</p>\n" }, { "answer_id": 252243, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>I wouldn't personally follow rigid rules. Certainly during the development stages, you want to be able to quickly change your queries so I would inline them.</p>\n\n<p>Later on, I would move to stored procedures because they offer the following two advantages. I'm sure there are more but these two win me over.</p>\n\n<p>1/ Stored procedures group the data and the code for manipulating/extracting that data at one point. This makes the life of your DBA a lot easier (assuming your app is sizable enough to warrant a DBA) since they can optimize based on known factors.</p>\n\n<p>One of the big bugbears of a DBA is ad-hoc queries (especially by clowns who don't know what a full table scan is). DBAs prefer to have nice consistent queries that they can tune the database to.</p>\n\n<p>2/ Stored procedures can contain logic which is best left in the database. I've seen stored procs in DB2/z with many dozens of lines but all the client has to code is a single line like \"give me that list\".</p>\n\n<p>Because the logic for \"that list\" is stored in the database, the DBAs can modify how it's stored and extracted at will <strong>without</strong> compromising or changing the client code. This is similar to encapsulation that made object-orientd languages 'cleaner' than what came before.</p>\n" }, { "answer_id": 252325, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Stored procedures are gold when you have several applications that depend on the same database. It let's you define and maintain query logic once, rather than several places.</p>\n\n<p>On the other hand, it's pretty easy for stored procedures themselves to become a big jumbled mess in the database, since most systems don't have a good method for organizing them logically. And they can be more difficult to version and track changes.</p>\n" }, { "answer_id": 252354, "author": "Josh", "author_id": 32963, "author_profile": "https://Stackoverflow.com/users/32963", "pm_score": 1, "selected": false, "text": "<p>I've done a mix of inline queries and stored procedures. I prefer more of the stored procedure/view approach as it gains a nice spot for you to make a change if needed. When you have inline queries you always have to go and change the code to change an inline query and then re-roll the application. You also might have the inline query in multiple places so you would have to change a lot more code than with one stored procedure.</p>\n\n<p>Then again if you have to add a parameter to a stored procedure, your still changing a lot of code anyways. </p>\n\n<p>Another note is how often the data changes behind the stored procedure, where I work we have third party tables that may break up into normalized tables, or a table becomes obsolete. In that case a stored procedure/view may minimize the exposure you have to that change.</p>\n\n<p>I've also written a entire application without stored procedures. It had three classes and 10 pages, was not worth it at all. I think there comes a point when its overkill, or can be justified, but it also comes down to your personal opinion and preference. </p>\n" }, { "answer_id": 252416, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "<p>Are you going to only ever access your database from that one application?</p>\n\n<p>If not, then you are probably better off using stored procedures so that you can have a consistent interface to your database.</p>\n\n<p>Is there any significant cost to distributing your application if you need to make a change?</p>\n\n<p>If so, then you are probably better off using stored procedures which can be changed at the server and those changes won't need to be distributed.</p>\n\n<p>Are you at all concerned about the security of your database?</p>\n\n<p>If so, then you probably want to use stored procedures so that you don't have to grant direct access to tables to a user.</p>\n\n<p>If you're writing a small application, without a wide audience, for a system that won't be used or accessed outside of your application, then inline SQL might be ok.</p>\n" }, { "answer_id": 252595, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<p>I prefer inline sql unless the stored procedure has actual logic (variables, cursors, etc) involved. I have been using LINQ to SQL lately, and taking the generated classes and adding partial classes that have some predefined, common linq queries. I feel this makes for faster development.</p>\n\n<p><em>Edit: I know I'm going to get downmodded for this. If you ever talk down on foreign keys or stored procedures, you will get downmodded. DBAs need job security I guess...</em></p>\n" }, { "answer_id": 254098, "author": "Dwight T", "author_id": 2526, "author_profile": "https://Stackoverflow.com/users/2526", "pm_score": 0, "selected": false, "text": "<p>With Subsonic you will use inline, views and stored procedures. Subsonic makes data access easier, but you can't do everthing in a subsonic query. Though the latest version, 2.1 is getting better.</p>\n\n<p>For basic CRUD operations, inline SQL will be straight forward. For more complex data needs, a view will need to be made and then you will do a Subsonic query on the view.</p>\n\n<p>Stored procs are good for harder data computations and data retrieval. Set based retrieval is usually always faster then procedural processing.</p>\n\n<p>Current Subsonic application uses all three options with great results.</p>\n" }, { "answer_id": 7343325, "author": "Developer", "author_id": 934060, "author_profile": "https://Stackoverflow.com/users/934060", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>Stored procedures group the data and the code for manipulating/extracting that data at one point. This makes the life of your DBA a lot easier (assuming your app is sizable enough to warrant a DBA) since they can optimize based on known factors.</p></li>\n<li><p>Stored procedures can contain logic which is best left in the database. I've seen stored procs in DB2/z with many dozens of lines but all the client has to code is a single line like \"give me that list\".</p></li>\n<li><p>the best advantage of using stored procs i found is that when we want to change in the logic, in case of inline query we need to go to everyplace and change it and re- roll the every application but in the case of stored proc change is required only at one place.</p></li>\n</ol>\n\n<p>So use inline queries when you have clear logic; otherwise prefer stored procs.</p>\n" }, { "answer_id": 7354439, "author": "Ed Heal", "author_id": 892256, "author_profile": "https://Stackoverflow.com/users/892256", "pm_score": 0, "selected": false, "text": "<p>The advantages of stored procedure (to my mind)</p>\n\n<ol>\n<li>The SQL is in one place</li>\n<li>You are able to get query plans.</li>\n<li>You can modify the database structure if necessary to improve performance</li>\n<li>They are compiled and thus those query plans do not have to get constructed on the fly</li>\n<li>If you use permissions - you can be sure of the queries that the application will make.</li>\n</ol>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28004/" ]
First of all there is a [partial question](https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder) regarding this, but it is not exactly what I'm asking, so, bear with me and go for it. My question is, after looking at what [SubSonic](http://subsonicproject.com/) does and the excellent videos from Rob Connery I need to ask: **Shall we use a tool like this and do Inline queries or** shall we do the queries **using** a call to the **stored procedure?** I don't want to minimize any work from Rob (which I think it's amazing) but I just want your opinion on this cause I need to start a new project and I'm in the middle of the line; shall I use SubSonic (or other like tool, like NHibernate) or I just continue my method that is always call a stored procedure even if it's a simple as ``` Select this, that from myTable where myStuff = StackOverflow; ```
It doesn't need to be one or the other. If it's a simple query, use the SubSonic query tool. If it's more complex, use a stored procedure and load up a collection or create a dataset from the results. See here: [What are the pros and cons to keeping SQL in Stored Procs versus Code](https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code) and here [SubSonic and Stored Procedures](https://stackoverflow.com/questions/228175/subsonic-and-stored-procedures)
252,242
<p>Specifically, I have a model that has a field like this</p> <pre><code>pub_date = models.DateField("date published") </code></pre> <p>I want to be able to easily grab the object with the most recent <code>pub_date</code>. What is the easiest/best way to do this?</p> <p>Would something like the following do what I want?</p> <pre><code>Edition.objects.order_by('pub_date')[:-1] </code></pre>
[ { "answer_id": 252248, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": true, "text": "<pre><code>obj = Edition.objects.latest('pub_date')\n</code></pre>\n\n<p>You can also simplify things by putting <a href=\"http://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by\" rel=\"noreferrer\"><code>get_latest_by</code></a> in the model's Meta, then you'll be able to do</p>\n\n<pre><code>obj = Edition.objects.latest()\n</code></pre>\n\n<p>See <a href=\"http://docs.djangoproject.com/en/dev/ref/models/querysets/#latest-field-name-none\" rel=\"noreferrer\">the docs</a> for more info. You'll probably also want to set the <a href=\"http://docs.djangoproject.com/en/dev/ref/models/options/#ordering\" rel=\"noreferrer\"><code>ordering</code></a> Meta option.</p>\n" }, { "answer_id": 252414, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "<p>Harley's answer is the way to go for the case where you want the latest according to some ordering criteria for particular Models, as you do, but the general solution is to reverse the ordering and retrieve the first item:</p>\n\n<pre><code>Edition.objects.order_by('-pub_date')[0]\n</code></pre>\n" }, { "answer_id": 252496, "author": "Dan", "author_id": 444, "author_profile": "https://Stackoverflow.com/users/444", "pm_score": 2, "selected": false, "text": "<p><strong>Note:</strong></p>\n\n<p>Normal python lists accept negative indexes, which signify an offset from the end of the list, rather than the beginning like a positive number. However, QuerySet objects will raise <pre>AssertionError: Negative indexing is not supported.</pre> if you use a negative index, which is why you have to do what insin said: reverse the ordering and grab the <code>0th</code> element.</p>\n" }, { "answer_id": 257243, "author": "Yogi", "author_id": 32801, "author_profile": "https://Stackoverflow.com/users/32801", "pm_score": 2, "selected": false, "text": "<p>Be careful of using</p>\n\n<pre><code>Edition.objects.order_by('-pub_date')[0]\n</code></pre>\n\n<p>as you might be indexing an empty QuerySet. I'm not sure what the correct Pythonic approach is, but the simplest would be to wrap it in an if/else or try/catch:</p>\n\n<pre><code>try:\n last = Edition.objects.order_by('-pub_date')[0]\nexcept IndexError:\n # Didn't find anything...\n</code></pre>\n\n<p>But, as @Harley said, when you're ordering by date, <code>latest()</code> is the <em>djangonic</em> way to do it.</p>\n" }, { "answer_id": 17963568, "author": "Bharadwaj Srigiriraju", "author_id": 1076075, "author_profile": "https://Stackoverflow.com/users/1076075", "pm_score": 0, "selected": false, "text": "<p>This has already been answered, but for more reference, this is what <a href=\"http://www.djangobook.com/en/2.0/chapter05.html\" rel=\"nofollow\">Django Book</a> has to say about Slicing Data on QuerySets:</p>\n\n<blockquote>\n <p>Note that negative slicing is not supported:</p>\n\n<pre><code>&gt;&gt;&gt; Publisher.objects.order_by('name')[-1]\nTraceback (most recent call last):\n ...\nAssertionError: Negative indexing is not supported.\n</code></pre>\n \n <p>This is easy to get around, though. Just change the order_by()\n statement, like this:</p>\n\n<pre><code>&gt;&gt;&gt; Publisher.objects.order_by('-name')[0]\n</code></pre>\n</blockquote>\n\n<p>Refer the link for more such details. Hope that helps!</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
Specifically, I have a model that has a field like this ``` pub_date = models.DateField("date published") ``` I want to be able to easily grab the object with the most recent `pub_date`. What is the easiest/best way to do this? Would something like the following do what I want? ``` Edition.objects.order_by('pub_date')[:-1] ```
``` obj = Edition.objects.latest('pub_date') ``` You can also simplify things by putting [`get_latest_by`](http://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by) in the model's Meta, then you'll be able to do ``` obj = Edition.objects.latest() ``` See [the docs](http://docs.djangoproject.com/en/dev/ref/models/querysets/#latest-field-name-none) for more info. You'll probably also want to set the [`ordering`](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) Meta option.
252,249
<p>Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features).</p> <p>How do you get around this?</p>
[ { "answer_id": 252254, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 5, "selected": true, "text": "<p>One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using <a href=\"http://www.ikvm.net/\" rel=\"noreferrer\">IKVM</a> you can <a href=\"http://www.apache.org/dyn/closer.cgi/lucene/java/\" rel=\"noreferrer\">download Lucene</a>, get the .jar file, and run:</p>\n\n<pre><code>ikvmc -target:library &lt;path-to-lucene.jar&gt;\n</code></pre>\n\n<p>which generates a .NET dll like this: lucene-core-2.4.0.dll</p>\n\n<p>You can then just reference this DLL from your project and you're good to go! There are some java types you will need, so also reference IKVM.OpenJDK.ClassLibrary.dll. Your code might look a bit like this:</p>\n\n<pre><code>QueryParser parser = new QueryParser(\"field1\", analyzer);\njava.util.Map boosts = new java.util.HashMap();\nboosts.put(\"field1\", new java.lang.Float(1.0));\nboosts.put(\"field2\", new java.lang.Float(10.0));\n\nMultiFieldQueryParser multiParser = new MultiFieldQueryParser\n (new string[] { \"field1\", \"field2\" }, analyzer, boosts);\nmultiParser.setDefaultOperator(QueryParser.Operator.OR);\n\nQuery query = multiParser.parse(\"ABC\");\nHits hits = isearcher.search(query);\n</code></pre>\n\n<p>I never knew you could have Java to .NET interoperability so easily. The best part is that C# and Java is \"almost\" source code compatible (where Lucene examples are concerned). Just replace <code>System.Out</code> with <code>Console.Writeln</code> :).</p>\n\n<p>=======</p>\n\n<p>Update: When building libraries like the Lucene highlighter, make sure you reference the core assembly (else you'll get warnings about missing classes). So the highlighter is built like this:</p>\n\n<pre><code>ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll\n</code></pre>\n" }, { "answer_id": 252270, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>Download the source and build it. I did this just last weekend and it was easy. No problem at all. The source is at version 2.3.1. </p>\n\n<p>I'm subscribed to the mailing list and judging from it, Lucene.Net is being developed actively.</p>\n" }, { "answer_id": 301690, "author": "user32016", "author_id": 32016, "author_profile": "https://Stackoverflow.com/users/32016", "pm_score": 1, "selected": false, "text": "<p>Lucene.net is under development and now has three committers</p>\n" }, { "answer_id": 847069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I converted the Lucene 2.4 from jar to dll through this way but now it gives me an error that 'Type or namespace Lucene could not be found'. I removed the old dll from the project and added reference for the new one. I really want to get rid of the old version as it took around 2 days and in the end during optimization it gave some error and now the index is not updateable :S. I read somewhere that Lucene 2.4 indexing speed is many times faster than the old versions, if I use 2.3.1 from SVN will that be faster too?</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features). How do you get around this?
One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using [IKVM](http://www.ikvm.net/) you can [download Lucene](http://www.apache.org/dyn/closer.cgi/lucene/java/), get the .jar file, and run: ``` ikvmc -target:library <path-to-lucene.jar> ``` which generates a .NET dll like this: lucene-core-2.4.0.dll You can then just reference this DLL from your project and you're good to go! There are some java types you will need, so also reference IKVM.OpenJDK.ClassLibrary.dll. Your code might look a bit like this: ``` QueryParser parser = new QueryParser("field1", analyzer); java.util.Map boosts = new java.util.HashMap(); boosts.put("field1", new java.lang.Float(1.0)); boosts.put("field2", new java.lang.Float(10.0)); MultiFieldQueryParser multiParser = new MultiFieldQueryParser (new string[] { "field1", "field2" }, analyzer, boosts); multiParser.setDefaultOperator(QueryParser.Operator.OR); Query query = multiParser.parse("ABC"); Hits hits = isearcher.search(query); ``` I never knew you could have Java to .NET interoperability so easily. The best part is that C# and Java is "almost" source code compatible (where Lucene examples are concerned). Just replace `System.Out` with `Console.Writeln` :). ======= Update: When building libraries like the Lucene highlighter, make sure you reference the core assembly (else you'll get warnings about missing classes). So the highlighter is built like this: ``` ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll ```
252,252
<p>Given the following markup:</p> <pre><code>&lt;ul&gt; &lt;li&gt;apple&lt;/li&gt; &lt;li class="highlight"&gt;orange&lt;/li&gt; &lt;li&gt;pear&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Both the <code>ul</code>s and the <code>li</code>s widths appear to be 100%. If I apply a <code>background-color</code> to the list item, the highlight stretches the full width of the page.</p> <p>I only want the background highlight to stretch as wide as the widest item (with maybe some padding). How do I constrain the <code>li</code>s (or perhaps the <code>ul</code>s) width to the width of the widest item?</p>
[ { "answer_id": 252259, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>Can you do it like this?</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;apple&lt;/li&gt;\n &lt;li&gt;&lt;span class=\"highlight\"&gt;orange&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;pear&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 252290, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 6, "selected": true, "text": "<p>Adding <code>ul {float: left; }</code> style will force your list into preferred width, which is what you want.</p>\n\n<p>Problem is, you should make sure next element goes below the list, as it did before. Clearing should take care of that.</p>\n" }, { "answer_id": 252334, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Exactly as BoltBait said, wrap your text in an inline element, such as <code>span</code> and give that the class.</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;apple&lt;/li&gt;\n &lt;li&gt;&lt;span class=\"highlight\"&gt;orange&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;pear&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>My extra 2 cents is that if you don't have access to change the HTML, you can do it using Javascript. In jQuery:</p>\n\n<pre><code>$('li.highlight').wrapInner(\"&lt;span&gt;&lt;/span&gt;\");\n</code></pre>\n\n<p>and use the CSS:</p>\n\n<pre><code>li.highlight span { background-color: #f0f; }\n</code></pre>\n\n<hr>\n\n<p>edit: after re-reading your question, can you clarify: do you want the highlight to only go as wide as the element which is highlighted, or as wide as the widest element in the list? eg:</p>\n\n<pre>\n - short\n - items ********************\n - here\n - and then a really long one\n</pre>\n\n<p>...where the asterisks represent the highlighting. If so, then buti-oxa's answer is the easiest way. just be careful with clearing your floats.</p>\n" }, { "answer_id": 29753670, "author": "Nathan", "author_id": 294317, "author_profile": "https://Stackoverflow.com/users/294317", "pm_score": 0, "selected": false, "text": "<p>Adding <code>style=\"float: left;\"</code> to <code>ul</code> will cause the <code>ul</code> to only stretch as wide as the widest item. However, the next element will be placed to the right of it. Adding <code>style=\"clear: left;\"</code> to the next element will place the next element after the <code>ul</code>.</p>\n\n<p><a href=\"http://jsfiddle.net/w07hn13s/\" rel=\"nofollow\">Try it out</a></p>\n\n<p>See <a href=\"http://www.w3schools.com/css/css_float.asp\" rel=\"nofollow\">documentation</a> on <code>float</code> and <code>clear</code>.</p>\n" }, { "answer_id": 32468792, "author": "redress", "author_id": 4167140, "author_profile": "https://Stackoverflow.com/users/4167140", "pm_score": 0, "selected": false, "text": "<p>The best way of going about solving this without messing up the style of your existing layout, is by wrapping the <code>ul</code> and <code>li</code> in a <code>div</code> with <code>display: inline-block</code> </p>\n\n<pre><code> &lt;div id='dropdown_tab' style='display: inline-block'&gt;dropdown\n &lt;ul id='dropdown_menu' style='display: none'&gt;\n &lt;li&gt;optoin 1&lt;/li&gt;\n &lt;li&gt;optoin 2&lt;/li&gt;\n &lt;li id='option_3'&gt;optoin 3\n &lt;ul id='dropdown_menu2' style='display: none'&gt;\n &lt;li&gt;second 1&lt;/li&gt;\n &lt;li&gt;second 2&lt;/li&gt;\n &lt;li&gt;second 3&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 59270684, "author": "TylerH", "author_id": 2756409, "author_profile": "https://Stackoverflow.com/users/2756409", "pm_score": -1, "selected": false, "text": "<p>None of the existing answers provide the correct solution, unfortunately. They range from abusing the <code>float</code> property to totally restructuring your HTML, something which often isn't feasible.</p>\n<p>The <a href=\"https://www.w3.org/TR/2011/WD-html-markup-20110113/ul.html#ul-display\" rel=\"nofollow noreferrer\"><code>&lt;ul&gt;</code></a> element has <code>display: block;</code> as its default <a href=\"https://www.w3.org/TR/css-display-3/#valdef-display-block\" rel=\"nofollow noreferrer\"><code>display</code></a> property, causing the width to fill 100% of its container.</p>\n<p>To change this aspect and still retain all the other default properties of how a <code>&lt;ul&gt;</code> is displayed (e.g. avoid issues with <code>float</code> from other answers), apply <code>display: inline-block;</code> to the list:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\n display: inline-block;\n background-color: green;\n}\n.highlight {\n background-color: orange; /* for demonstration */\n padding: 15px; /* for demonstration */\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;ul&gt;\n &lt;li&gt;apple&lt;/li&gt;\n &lt;li class=\"highlight\"&gt;orange&lt;/li&gt;\n &lt;li&gt;pear&lt;/li&gt;\n &lt;li&gt;banana&lt;/li&gt;\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26627/" ]
Given the following markup: ``` <ul> <li>apple</li> <li class="highlight">orange</li> <li>pear</li> </ul> ``` Both the `ul`s and the `li`s widths appear to be 100%. If I apply a `background-color` to the list item, the highlight stretches the full width of the page. I only want the background highlight to stretch as wide as the widest item (with maybe some padding). How do I constrain the `li`s (or perhaps the `ul`s) width to the width of the widest item?
Adding `ul {float: left; }` style will force your list into preferred width, which is what you want. Problem is, you should make sure next element goes below the list, as it did before. Clearing should take care of that.
252,257
<p>I was just wondering, since the <strong>sealed</strong> keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible?</p> <p>I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword.</p> <p>There's a large chance that I haven't thought this through properly, though, so please be humane!</p>
[ { "answer_id": 252266, "author": "Cory House", "author_id": 26180, "author_profile": "https://Stackoverflow.com/users/26180", "pm_score": 4, "selected": false, "text": "<p>Inheritance is a foundational principle of OO, so arguably, disallowing it by default wouldn't be intuitive.</p>\n" }, { "answer_id": 252271, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>I can't recall having heard a rationale for the decision to have classes not sealed by default. However, there are certainly quite a few people who believe that C# should have been spec'ed to have sealed be the default:</p>\n\n<p><a href=\"http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx</a></p>\n" }, { "answer_id": 252281, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>sealed classes <em>prevent inheritance</em> and therefore are an OO abombination. see <a href=\"https://stackoverflow.com/questions/2134/do-sealed-classes-really-offer-performance-benefits#202584\">this rant</a> for details ;-)</p>\n" }, { "answer_id": 252461, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "<p>You could probably make just as many arguments in favor of sealed-by-default as you could against it. If it were the other way around, someone would be posting the opposite question.</p>\n" }, { "answer_id": 252490, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>Merely deriving from an unsealed class doesn't change the class's behavior. The worst that can happen is that a new version of the base class will add a member with the same name as the deriving class (in which case there will just be a compiler warning saying you should use the <em>new</em> or <em>override</em> modifier) or the base class is sealed (which is a design no-no if the class has already been released into the wild). Arbitrary sublassing still complies with the <a href=\"http://www.eventhelix.com/RealtimeMantra/Object_Oriented/liskov_substitution_principle.htm\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a>.</p>\n\n<p>The reason that members are not overridable by default in C# is that because overriding a method can change the base class's behaviour in a way that the base class's author didn't anticipate. By making it explicitly abstract or virtual, it's saying that the author is aware that that it can change or is otherwise beyond their control and the author should have taken this into account.</p>\n" }, { "answer_id": 252738, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.)</p>\n\n<p>For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...</p>\n" }, { "answer_id": 252745, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 6, "selected": true, "text": "<p><strong>In my opinion</strong> there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more.</p>\n\n<p>If you want a class to be inheritable then you write</p>\n\n<pre><code>public extensible class MyClass\n</code></pre>\n\n<p>otherwise</p>\n\n<pre><code>public sealed class MyClass\n</code></pre>\n\n<p>BTW I think the same should go with access modifiers, disallow default access modifiers.</p>\n" }, { "answer_id": 252776, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 2, "selected": false, "text": "<p>80% of the features of Word go unused. 80% of classes don't get inherited from. In both cases, once in a while, someone comes along and wants to use or reuse a feature. Why should the original designer prohibit reuse? Let the reuser decide what they want to reuse.</p>\n" }, { "answer_id": 252837, "author": "blizpasta", "author_id": 20646, "author_profile": "https://Stackoverflow.com/users/20646", "pm_score": 0, "selected": false, "text": "<p>For the same reason why objects are not private by default</p>\n\n<p>or</p>\n\n<p>to be consistent with the object analogue, which is objects are not private by default</p>\n\n<p>Just guessing, coz at the end of the day it's a language's design decision and what the creators say is the canon material.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
I was just wondering, since the **sealed** keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible? I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword. There's a large chance that I haven't thought this through properly, though, so please be humane!
**In my opinion** there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more. If you want a class to be inheritable then you write ``` public extensible class MyClass ``` otherwise ``` public sealed class MyClass ``` BTW I think the same should go with access modifiers, disallow default access modifiers.
252,258
<p>I have a MySQL database behind a firewall which can only be accessed via an SSH connection. Does anyone know of an implementation of java.sql.Connection which would allow me to make an SSH connection to this database?</p>
[ { "answer_id": 252370, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 5, "selected": true, "text": "<p>You can use SSH's port forwarding to do this. While not a pure java.sql.Connection, it will allow you to tunnel the connection through ssh.</p>\n\n<pre>ssh -L 3306:localhost:3306 remote.mysql.host.com</pre>\n\n<p>This will forward port 3306 on your local machine to port 3306 on remote.mysql.host.com. This will allow you to connect to port 3306 on your local machine, and it will be tunnelled to remote.mysql.host.com.</p>\n\n<p>If you're looking to do it all in Java, create the ssh connection with <a href=\"http://www.jcraft.com/jsch/\" rel=\"noreferrer\">JSch</a>.</p>\n" }, { "answer_id": 29043799, "author": "James Newman", "author_id": 4047673, "author_profile": "https://Stackoverflow.com/users/4047673", "pm_score": 0, "selected": false, "text": "<p>Here is an <a href=\"https://github.com/newjam/mysql_ssh_tunnel_example/blob/master/src/main/java/com/github/newjam/test/tunnel/Tunnel.java#L54\" rel=\"nofollow\">example</a> using the library <a href=\"https://github.com/hierynomus/sshj\" rel=\"nofollow\">sshj</a>.</p>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
I have a MySQL database behind a firewall which can only be accessed via an SSH connection. Does anyone know of an implementation of java.sql.Connection which would allow me to make an SSH connection to this database?
You can use SSH's port forwarding to do this. While not a pure java.sql.Connection, it will allow you to tunnel the connection through ssh. ``` ssh -L 3306:localhost:3306 remote.mysql.host.com ``` This will forward port 3306 on your local machine to port 3306 on remote.mysql.host.com. This will allow you to connect to port 3306 on your local machine, and it will be tunnelled to remote.mysql.host.com. If you're looking to do it all in Java, create the ssh connection with [JSch](http://www.jcraft.com/jsch/).