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
37,731
<p>I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:</p> <pre><code>$draw = new Draw; $nav = $draw-&gt;wideHeaderBox(). $draw-&gt;left(). $draw-&gt;image(). Image::get($image,60,array('id'=&gt;'header_image')). $draw-&gt;imageEnd(). $draw-&gt;leftEnd(). $draw-&gt;left(10). '&lt;div id="header_text"&gt;'. self::defaultSectionText(). '&lt;/div&gt;'. $draw-&gt;leftEnd(). </code></pre> <p>and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.</p>
[ { "answer_id": 37733, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "<p>The argument he uses is the argument you need to <em>have</em> views. Both result in only changing it in one place. Howe...
2008/09/01
[ "https://Stackoverflow.com/questions/37731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2594/" ]
I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this: ``` $draw = new Draw; $nav = $draw->wideHeaderBox(). $draw->left(). $draw->image(). Image::get($image,60,array('id'=>'header_image')). $draw->imageEnd(). $draw->leftEnd(). $draw->left(10). '<div id="header_text">'. self::defaultSectionText(). '</div>'. $draw->leftEnd(). ``` and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.
HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a `new Draw` just doesn't sound very natural. Furthermore, `wideHeaderBox` and `left` will only have significance to someone who intimately knows the system. And what if there *is* a redesign, like your co-worker muses? What if the `wideHeaderBox` becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code? If you guys just *have* to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this: ``` HTML::link("Wikipedia", "http://en.wikipedia.org"); HTML::bulleted_list(array( HTML::list_item("Dogs"), HTML::list_item("Cats"), HTML::list_item("Armadillos") )); ``` In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing.
37,732
<p>What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?</p> <p>I get this error:</p> <blockquote> <p>No ending delimiter '^' found</p> </blockquote> <p>Using:</p> <pre><code>preg_match('(?n:^(?=\d)((?&lt;day&gt;31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?&lt;sep&gt;[/.-])(?&lt;month&gt;0?[1-9]|1[012])\2(?&lt;year&gt;(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?&lt;time&gt;((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); </code></pre> <p>Gives this error: </p> <blockquote> <p>Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19</p> </blockquote>
[ { "answer_id": 37742, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=610\" rel=\"noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=...
2008/09/01
[ "https://Stackoverflow.com/questions/37732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ? I get this error: > > No ending delimiter '^' found > > > Using: ``` preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); ``` Gives this error: > > Warning: preg\_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19 > > >
@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed. It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed: ``` (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) ``` If you're using perl, then you can get the values out with something like this: ``` $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; ``` Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.
37,743
<p>I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. </p> <p>I'm making an example to clarify. Let's say that this is the Users table, with the points earned:</p> <pre><code>UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 6 - 25 </code></pre> <p>If I want the top 3 scores, the result will be:</p> <pre><code>UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 </code></pre> <p>This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.</p>
[ { "answer_id": 37750, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "<p>Untested, but should work:</p>\n\n<pre><code>select * from users where points in\n(select distinct top 3 points from users ord...
2008/09/01
[ "https://Stackoverflow.com/questions/37743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178/" ]
I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. I'm making an example to clarify. Let's say that this is the Users table, with the points earned: ``` UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 6 - 25 ``` If I want the top 3 scores, the result will be: ``` UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 ``` This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.
Untested, but should work: ``` select * from users where points in (select distinct top 3 points from users order by points desc) ```
37,759
<p>I have the following code in a web.config file of the default IIS site.</p> <pre><code>&lt;httpModules&gt; &lt;add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/&gt; &lt;/httpModules&gt; </code></pre> <p>Then when I setup and browse to a virtual directory I get this error</p> <p>Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified.</p> <p>The virtual directory is inheriting the modules from the default web.config.</p> <p>How do you stop this inheritance?</p>
[ { "answer_id": 37762, "author": "John Owen", "author_id": 2471, "author_profile": "https://Stackoverflow.com/users/2471", "pm_score": 5, "selected": true, "text": "<p>I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to ...
2008/09/01
[ "https://Stackoverflow.com/questions/37759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2471/" ]
I have the following code in a web.config file of the default IIS site. ``` <httpModules> <add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/> </httpModules> ``` Then when I setup and browse to a virtual directory I get this error Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified. The virtual directory is inheriting the modules from the default web.config. How do you stop this inheritance?
I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false. ``` <location path="." inheritInChildApplications="false"> <system.web> <httpModules> <add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/> </httpModules> </system.web> </location> ``` Now any virtual directories will not inherit the settings in this location section. @GateKiller This isn't another website, its a virtual directory so inheritance does occur. @petrich I've had hit and miss results using `<remove />`. I have to remember to add it to every virtual directory which is a pain.
37,791
<p>At the moment my code (PHP) has too many SQL queries in it. eg...</p> <pre><code>// not a real example, but you get the idea... $results = $db-&gt;GetResults("SELECT * FROM sometable WHERE iUser=$userid"); if ($results) { // Do something } </code></pre> <p>I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..</p> <p>I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?</p>
[ { "answer_id": 37795, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 2, "selected": false, "text": "<p>Use a ORM package, any half decent package will allow you to</p>\n\n<ol>\n<li>Get simple result sets</li>\n<li>Keep...
2008/09/01
[ "https://Stackoverflow.com/questions/37791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012/" ]
At the moment my code (PHP) has too many SQL queries in it. eg... ``` // not a real example, but you get the idea... $results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid"); if ($results) { // Do something } ``` I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns.. I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?
The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take: * Use stored procedures * Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier) * Use an ORM tool If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about [versioning databases](http://odetocode.com/blogs/scott/archive/2008/02/02/11737.aspx): > > Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don't need. In those applications stored procedures are more of a burden than a benefit. > > > I tend to lean towards not using stored procedures. I've worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have *all*, to varying degrees, used dynamically generated raw SQL in code to access the DB. Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you'd have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation. Conceptually, you should probably have your database versioned. Practically speaking, however, you're far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won't be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application. Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page's scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you're using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do. If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the 'user' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure. ``` // UserManager.php: class UserManager { function getUsers() { $pdo = new PDO(...); $stmt = $pdo->prepare(' SELECT u.userId as id, u.userName, g.groupId, g.groupName FROM user u INNER JOIN group g ON u.groupId = g.groupId ORDER BY u.userName, g.groupName '); // iterate over result and prepare return value } function getUser($id) { // db code here } } // index.php: require_once("UserManager.php"); $um = new UserManager; $users = $um->getUsers(); foreach ($users as $user) echo $user['name']; ``` However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated. If you decide to investigate ORM tools, you should look at [Propel](http://propel.phpdb.org/), the ActiveRecord component of [Yii](http://yiiframework.com), or the king-daddy PHP ORM, [Doctrine](http://www.doctrine-project.org/). Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the [Nested Set tree pattern](http://www.developersdex.com/gurus/articles/112.asp) out of the box. In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries. [Gary Richardson](https://stackoverflow.com/questions/37791/how-do-you-manage-sql-queries#38053) is absolutely right though, if you're going to continue to use SQL in your code you should always be using PDO's prepared statements to handle the parameters regardless of whether you're using a query or a stored procedure. The sanitisation of input is performed for you by PDO. ``` // optional $attrs = array(PDO::ATTR_PERSISTENT => true); // create the PDO object $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass", $attrs); // also optional, but it makes PDO raise exceptions instead of // PHP errors which are far more useful for debugging $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName, :regionId)'); $stmt->bindValue(":venueName", "test"); $stmt->bindValue(":regionId", 1); $stmt->execute(); $lastInsertId = $pdo->lastInsertId(); var_dump($lastInsertId); ``` Caveat: assuming that the ID is 1, the above script will output `string(1) "1"`. `PDO->lastInsertId()` returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically. The following will output `bool(true)`: ``` // regular equality test var_dump($lastInsertId == 1); ``` but if you have code that is expecting the value to be an integer, like [is\_int](http://php.net/manual/en/function.is-int.php) or PHP's ["is really, truly, 100% equal to"](http://au.php.net/manual/en/language.operators.comparison.php) operator: ``` var_dump(is_int($lastInsertId)); var_dump($lastInsertId === 1); ``` you could run into some issues. **Edit:** Some good discussion on stored procedures [here](https://stackoverflow.com/questions/83419/stored-procedures-a-no-go-in-the-phpmysql-world#84294)
37,805
<p>I have a <code>List&lt;int&gt;</code> and a <code>List&lt;customObject&gt;</code>. The customObject class has an ID property. How can I get a <code>List&lt;customObject&gt;</code> containing only the objects where the ID property is in the <code>List&lt;int&gt;</code> using LINQ?</p> <p><strong>Edit</strong>: I accepted Konrads answer because it is easier/more intuitive to read.</p>
[ { "answer_id": 37807, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>Untested, but it'll be something like this:</p>\n\n<pre><code>var matches = from o in objList \n join...
2008/09/01
[ "https://Stackoverflow.com/questions/37805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257/" ]
I have a `List<int>` and a `List<customObject>`. The customObject class has an ID property. How can I get a `List<customObject>` containing only the objects where the ID property is in the `List<int>` using LINQ? **Edit**: I accepted Konrads answer because it is easier/more intuitive to read.
``` var result = from o in objList where intList.Contains(o.ID) select o ```
37,809
<p>How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?</p> <p>For example how can I convert:</p> <blockquote> <p>How do I generate a Friendly URL in C#?</p> </blockquote> <p>Into</p> <blockquote> <p>how-do-i-generate-a-friendly-url-in-C</p> </blockquote>
[ { "answer_id": 37817, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 4, "selected": false, "text": "<p>Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..</p>\n\n<pre><code>...
2008/09/01
[ "https://Stackoverflow.com/questions/37809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow? For example how can I convert: > > How do I generate a Friendly URL in C#? > > > Into > > how-do-i-generate-a-friendly-url-in-C > > >
There are several things that could be improved in Jeff's solution, though. ``` if (String.IsNullOrEmpty(title)) return ""; ``` IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all. ``` // remove any leading or trailing spaces left over … muuuch later: // remove trailing dash, if there is one ``` Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue. ``` // replace spaces with single dash title = Regex.Replace(title, @"\s+", "-"); // if we end up with multiple dashes, collapse to single dash title = Regex.Replace(title, @"\-{2,}", "-"); ``` Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one. Off the top of my head, without any testing whatsoever, this would be an equivalent solution: ``` // make it all lower case title = title.ToLower(); // remove entities title = Regex.Replace(title, @"&\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^a-z0-9\-\s]", ""); // replace spaces title = title.Replace(' ', '-'); // collapse dashes title = Regex.Replace(title, @"-{2,}", "-"); // trim excessive dashes at the beginning title = title.TrimStart(new [] {'-'}); // if it's too long, clip it if (title.Length > 80) title = title.Substring(0, 79); // remove trailing dashes title = title.TrimEnd(new [] {'-'}); return title; ``` Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.
37,822
<p>I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang?</p> <p>I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine.</p> <p>It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store. </p>
[ { "answer_id": 38554, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 2, "selected": false, "text": "<p>The iPhone SDK is documented to require an Intel-based Mac. Even if some people may be able to have gotten it to run o...
2008/09/01
[ "https://Stackoverflow.com/questions/37822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2438/" ]
I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang? I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine. It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store.
As things have moved on since the original post on 3by9.com, here are the steps that I had to follow to get the environment working on my PowerBook G4. **BTW, I would like to say that I realise that this is not a supported environment and I share this for purely pedagogic rea**sons. 1. Download and install the iPhoneSDK (final version) 2. After the install finishes, navigate to the packages directory in the mounted DMG 3. Install all of the pkg's that start with iPhone 4. Copy the contents of `/Platforms` to `/Developer/Platforms` (should be two folders starting with iPhone) 5. Locate '`iPhone Simulator Architectures.xcspec`' in `/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications` and open in a text editor. 6. Change line 12 to: `Name = "Standard (iPhone Simulator: i386 ppc)";` 7. Change line 16 to: `RealArchitectures = ( i386, ppc );` 8. Add the following to line 40 onwards: ``` // PowerPC { Type = Architecture; Identifier = ppc; Name = "PowerPC"; Description = "32-bit PowerPC"; PerArchBuildSettingName = "PowerPC"; ByteOrder = big; ListInEnum = NO; SortNumber = 106; }, ``` 9. Save the file and start Xcode 10. You should see under the New Project Folder the ability to create iPhone applications. 11. To get an app to work in the simulator (and using the WhichWayIsUp example) open Edit Project Settings under the Project menu 12. On the Build tab change the Architectures to: Standard (iPhone Simulator:i386 ppc) 13. Change Base SDK to Simulator - iPhone OS 2.0 14. Build and go should now see the app build and run in the simulator
37,830
<p>I want to show a chromeless modal window with a close button in the upper right corner. Is this possible?</p>
[ { "answer_id": 37878, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowSt...
2008/09/01
[ "https://Stackoverflow.com/questions/37830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374/" ]
I want to show a chromeless modal window with a close button in the upper right corner. Is this possible?
You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this: ``` <Window WindowStyle="None"> ``` That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration.
37,920
<p>I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog.</p> <p>The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control.</p> <p>My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing.</p> <p>However, if I make a call to <code>::MessageBox()</code> immediately before <code>DoModal()</code> the dialog displays and behaves correctly after first showing the MessageBox.</p> <p>I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'.</p> <p>I have tried using both NULL and the return value from <code>::GetConsoleWindow()</code> as the dialog's parent, neither have worked.</p> <p>The dialog itself is an ATL/WTL CPropertySheetImpl.</p> <p>The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party.</p> <p>I do know that I can successfully call <code>::MessageBox()</code> or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog.</p> <p>Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface.</p>
[ { "answer_id": 37943, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "<p>Are you using a parent for the Dialog? e.g.</p>\n\n<pre><code>MyDialog dialog(pParent);\ndialog.DoModal();\n</code></pre...
2008/09/01
[ "https://Stackoverflow.com/questions/37920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3229/" ]
I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog. The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control. My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing. However, if I make a call to `::MessageBox()` immediately before `DoModal()` the dialog displays and behaves correctly after first showing the MessageBox. I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'. I have tried using both NULL and the return value from `::GetConsoleWindow()` as the dialog's parent, neither have worked. The dialog itself is an ATL/WTL CPropertySheetImpl. The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party. I do know that I can successfully call `::MessageBox()` or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog. Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface.
Are you using a parent for the Dialog? e.g. ``` MyDialog dialog(pParent); dialog.DoModal(); ``` If you are, try removing the parent. Especially if the parent is the desktop window.
37,956
<p>I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me.</p> <p>I've tried to use Direct Show with the SampleGrabber filter (using this sample <a href="http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx</a>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. </p> <p>I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected...</p> <pre><code>[...] hr = pGrabber-&gt;SetOneShot(TRUE); hr = pGrabber-&gt;SetBufferSamples(TRUE); pControl-&gt;Run(); // Run the graph. pEvent-&gt;WaitForCompletion(INFINITE, &amp;evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber-&gt;GetCurrentBuffer(&amp;cbBuffer, NULL); for( int i = 0 ; i &lt; 25 ; ++i ) { pControl-&gt;Run(); // Run the graph. pEvent-&gt;WaitForCompletion(INFINITE, &amp;evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber-&gt;GetCurrentBuffer(&amp;cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber-&gt;GetConnectedMediaType(&amp;mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] </code></pre> <p>Is there somebody, with video software experience, who can advise me about code or other simpler library?</p> <p>Thanks</p> <p>Edit: Msdn links seems not to work (<a href="http://stackoverflow.uservoice.com/pages/general/suggestions/19963" rel="noreferrer">see the bug</a>)</p>
[ { "answer_id": 37980, "author": "Chris de Vries", "author_id": 3836, "author_profile": "https://Stackoverflow.com/users/3836", "pm_score": 2, "selected": false, "text": "<p>I have used <a href=\"http://sourceforge.net/projects/opencvlibrary/\" rel=\"nofollow noreferrer\">OpenCV</a> to lo...
2008/09/01
[ "https://Stackoverflow.com/questions/37956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578/" ]
I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample <http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected... ``` [...] hr = pGrabber->SetOneShot(TRUE); hr = pGrabber->SetBufferSamples(TRUE); pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL); for( int i = 0 ; i < 25 ; ++i ) { pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber->GetConnectedMediaType(&mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] ``` Is there somebody, with video software experience, who can advise me about code or other simpler library? Thanks Edit: Msdn links seems not to work ([see the bug](http://stackoverflow.uservoice.com/pages/general/suggestions/19963))
Currently these are the most popular video frameworks available on Win32 platforms: 1. Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed. 2. DirectShow: standard WinXP framework, it can basically load all formats you can play with Windows Media Player. Rather difficult to use. 3. [Ffmpeg](http://ffmpeg.mplayerhq.hu/): more precisely libavcodec and libavformat that comes with Ffmpeg open- source multimedia utility. It is extremely powerful and can read a lot of formats (almost everything you can play with [VLC](http://www.videolan.org/vlc/)) even if you don't have the codec installed on the system. It's quite complicated to use but you can always get inspired by the code of ffplay that comes shipped with it or by other implementations in open-source software. Anyway I think it's still much easier to use than DS (and much faster). It needs to be comipled by MinGW on Windows, but all the steps are explained very well [here](http://arrozcru.no-ip.org/ffmpeg/) (in this moment the link is down, hope not dead). 4. [QuickTime](http://developer.apple.com/quicktime/download/): the Apple framework is not the best solution for Windows platform, since it needs QuickTime app to be installed and also the proper QuickTime codec for every format; it does not support many formats, but its quite common in professional field (so some codec are actually only for QuickTime). Shouldn't be too difficult to implement. 5. [Gstreamer](http://www.gstreamer.net/): latest open source framework. I don't know much about it, I guess it wraps over some of the other systems (but I'm not sure). All of this frameworks have been implemented as backend in OpenCv Highgui, except for DirectShow. The default framework for Win32 OpenCV is using VFW (and thus able only to open some AVI files), if you want to use the others you must download the CVS instead of the official release and still do some hacking on the code and it's anyway not too complete, for example FFMPEG backend doesn't allow to seek in the stream. If you want to use QuickTime with OpenCV [this](http://path.berkeley.edu/~zuwhan/QTforOpenCVWin/) can help you.
37,976
<p>By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?</p>
[ { "answer_id": 38224, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 5, "selected": true, "text": "<p>Sure there is. This is all you need to do:</p>\n\n<ul>\n<li>Go to</li>\n</ul>\n\n<pre>File -> Settings -> Global Code Style ...
2008/09/01
[ "https://Stackoverflow.com/questions/37976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113/" ]
By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?
Sure there is. This is all you need to do: * Go to ``` File -> Settings -> Global Code Style -> General ``` * Disable the checkbox next to 'Use same settings for all file types' * The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.
38,014
<p>I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using <code>System.Data.OracleClient</code> to connect to oracle database. Name of database is <code>myDB</code>. Below the the connection string I am using:</p> <pre><code>Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True </code></pre> <p>If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB):</p> <pre><code>SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) </code></pre> <p>But if I append the database name along with it the it is giving correct result:</p> <pre><code>SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) </code></pre> <p>My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.</p>
[ { "answer_id": 38022, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 0, "selected": false, "text": "<p>Try adding</p>\n\n<pre><code>CONNECT_DATA=(SID=myDB)(SERVICE_NAME=ORCL)\n</code></pre>\n\n<p>in the connection string.</p>...
2008/09/01
[ "https://Stackoverflow.com/questions/38014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using `System.Data.OracleClient` to connect to oracle database. Name of database is `myDB`. Below the the connection string I am using: ``` Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True ``` If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB): ``` SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) ``` But if I append the database name along with it the it is giving correct result: ``` SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) ``` My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.
This looks like an issue with name resolution, try creating a public synonym on the table: CREATE PUBLIC SYNONYM *MyTempTable* for *MyTempTable*; Also, what exactly do you mean by **wrong result**, incorrect data, error message? --- Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as.
38,021
<p>How can I find the origins of conflicting DNS records?</p>
[ { "answer_id": 38025, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "<p>An easy way is to use an online domain tool. My favorite is <a href=\"http://whois.domaintools.com/stackoverflow.com\" r...
2008/09/01
[ "https://Stackoverflow.com/questions/38021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
How can I find the origins of conflicting DNS records?
You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available **nslookup** command line tool: ``` command line> nslookup > set querytype=soa > stackoverflow.com Server: 217.30.180.230 Address: 217.30.180.230#53 Non-authoritative answer: stackoverflow.com origin = ns51.domaincontrol.com # ("primary name server" on Windows) mail addr = dns.jomax.net # ("responsible mail addr" on Windows) serial = 2008041300 refresh = 28800 retry = 7200 expire = 604800 minimum = 86400 Authoritative answers can be found from: stackoverflow.com nameserver = ns52.domaincontrol.com. stackoverflow.com nameserver = ns51.domaincontrol.com. ``` The **origin** (or **primary name server** on Windows) line tells you that **ns51.domaincontrol** is the main name server for **stackoverflow.com**. At the end of output all authoritative servers, including backup servers for the given domain, are listed.
38,035
<p>I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?</p>
[ { "answer_id": 38063, "author": "aryeh", "author_id": 3288, "author_profile": "https://Stackoverflow.com/users/3288", "pm_score": 0, "selected": false, "text": "<p>Use the INSTR() function to find the position of the word in the string, and then use SUBSTRING() function to select a porti...
2008/09/01
[ "https://Stackoverflow.com/questions/38035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393028/" ]
I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?
You can do it all in the query using SUBSTRING\_INDEX ``` CONCAT_WS( ' ', -- 20 words before TRIM( SUBSTRING_INDEX( SUBSTRING(field, 1, INSTR(field, 'word') - 1 ), ' ', -20 ) ), -- your word 'word', -- 20 words after TRIM( SUBSTRING_INDEX( SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ), ' ', 20 ) ) ``` )
38,037
<p>In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a <code>std::string</code>).<br> <a href="http://rapidxml.sourceforge.net/" rel="nofollow noreferrer">RapidXml</a> has been recommended to me, but I can't see how to retrieve the XML back as a text string.<br> (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)<br> Thank you.</p>
[ { "answer_id": 38127, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 0, "selected": false, "text": "<p>If you aren't yet committed to Rapid XML, I can recommend some alternative libraries:</p>\n\n<ul>\n<li><p>Xerces - This...
2008/09/01
[ "https://Stackoverflow.com/questions/38037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3590/" ]
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a `std::string`). [RapidXml](http://rapidxml.sourceforge.net/) has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.) Thank you.
Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml: ``` #include <iostream> #include <sstream> #include "rapidxml/rapidxml.hpp" #include "rapidxml/rapidxml_print.hpp" int main(int argc, char* argv[]) { char xml[] = "<?xml version=\"1.0\" encoding=\"latin-1\"?>" "<book>" "</book>"; //Parse the original document rapidxml::xml_document<> doc; doc.parse<0>(xml); std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n"; //Insert something rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe"); doc.first_node()->append_node(node); std::stringstream ss; ss <<*doc.first_node(); std::string result_xml = ss.str(); std::cout <<result_xml<<std::endl; return 0; } ```
38,039
<p>How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?</p> <p>Something like:</p> <pre><code>DateTime.Now.StartWeek(Monday); </code></pre>
[ { "answer_id": 38049, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": false, "text": "<p>This would give you the preceding Sunday (I think):</p>\n\n<pre><code>DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t...
2008/09/01
[ "https://Stackoverflow.com/questions/38039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#? Something like: ``` DateTime.Now.StartWeek(Monday); ```
Use an extension method: ``` public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } } ``` Which can be used as follows: ``` DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday); DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday); ```
38,056
<p>The only <em>nice</em> way I've found is:</p> <pre><code>import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" </code></pre> <p>(<a href="http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html" rel="noreferrer">Source</a>)<br> But is this reliable? Does it work with every process and every distribution?</p>
[ { "answer_id": 38071, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": false, "text": "<p>on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory e...
2008/09/01
[ "https://Stackoverflow.com/questions/38056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1531/" ]
The only *nice* way I've found is: ``` import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" ``` ([Source](http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html)) But is this reliable? Does it work with every process and every distribution?
Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable: ``` >>> import os.path >>> os.path.exists("/proc/0") False >>> os.path.exists("/proc/12") True ```
38,057
<pre><code>@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List&lt; UglyProblem &gt; problems; } </code></pre> <p>I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")".</p> <p>All I found is <a href="http://opensource.atlassian.com/projects/hibernate/browse/ANN-558" rel="noreferrer">this</a>. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. </p> <hr> <blockquote> <p>Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored."</p> </blockquote> <p>Well I think this means that if I have these two classes:</p> <pre><code>public class A { private int foo; } @Entity public class B extens A { } </code></pre> <p>then field <code>foo</code> will not be mapped for class B. Which makes sense. But if I have something like this:</p> <pre><code>@Entity public class Problem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class UglyProblem extends Problem { private int levelOfUgliness; public int getLevelOfUgliness() { return levelOfUgliness; } public void setLevelOfUgliness(int levelOfUgliness) { this.levelOfUgliness = levelOfUgliness; } } </code></pre> <p>I expect the class UglyProblem to have fileds <code>id</code> and <code>name</code> and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table:</p> <pre><code>CREATE TABLE "problem" ( "DTYPE" varchar(31) NOT NULL, "id" bigint(20) NOT NULL auto_increment, "name" varchar(255) default NULL, "levelOfUgliness" int(11) default NULL, PRIMARY KEY ("id") ) AUTO_INCREMENT=2; </code></pre> <p>Going back to my question:</p> <blockquote> <p>I expect @ManyToOne person to be inherited by UglyProblem class.</p> </blockquote> <p>I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships.</p> <hr> <p>Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked.</p> <p>I want to find out the motivation of this design decision.</p> <p>(if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)</p>
[ { "answer_id": 38096, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 1, "selected": false, "text": "<p>I think you need to annotate your <em>Problem</em> super-class with <em><a href=\"http://java.sun.com/javaee/5/docs/a...
2008/09/01
[ "https://Stackoverflow.com/questions/38057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4052/" ]
``` @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List< UglyProblem > problems; } ``` I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")". All I found is [this](http://opensource.atlassian.com/projects/hibernate/browse/ANN-558). I was not able to find the post by Emmanuel Bernard explaining reasons behind this. --- > > Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored." > > > Well I think this means that if I have these two classes: ``` public class A { private int foo; } @Entity public class B extens A { } ``` then field `foo` will not be mapped for class B. Which makes sense. But if I have something like this: ``` @Entity public class Problem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class UglyProblem extends Problem { private int levelOfUgliness; public int getLevelOfUgliness() { return levelOfUgliness; } public void setLevelOfUgliness(int levelOfUgliness) { this.levelOfUgliness = levelOfUgliness; } } ``` I expect the class UglyProblem to have fileds `id` and `name` and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table: ``` CREATE TABLE "problem" ( "DTYPE" varchar(31) NOT NULL, "id" bigint(20) NOT NULL auto_increment, "name" varchar(255) default NULL, "levelOfUgliness" int(11) default NULL, PRIMARY KEY ("id") ) AUTO_INCREMENT=2; ``` Going back to my question: > > I expect @ManyToOne person to be inherited by UglyProblem class. > > > I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships. --- Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked. I want to find out the motivation of this design decision. (if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)
I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works. :) Let's try to understand the problem. I think your concepts are "lying". First you say that many **Problem**s are associated to **People**. But, then you say that one **Person** have many **UglyProblem**s (and does not relate to other **Problem**s). Something is wrong with that design. Imagine how it's going to be mapped to the database. You have a single table inheritance, so: ``` _____________ |__PROBLEMS__| |__PEOPLE__| |id <PK> | | | |person <FK> | -------->| | |problemType | |_________ | -------------- ``` How is hibernate going to enforce the database to make **Problem** only relate to **People** if its **problemType** is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what `@MappedSuperclass` does. PS.: Sorry for the ugly drawing :D
38,068
<p>Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:</p> <pre><code>Typedef myGenDef = &lt; Object1, Object2 &gt;; HashMap&lt; myGenDef &gt; hm = new HashMap&lt; myGenDef &gt;(); for (Entry&lt; myGenDef &gt; ent : hm..entrySet()) { . . . } </code></pre>
[ { "answer_id": 38098, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 1, "selected": false, "text": "<p>No. Though, groovy, a JVM language, is dynamically typed and would let you write:</p>\n\n<pre><code>def map = new Ha...
2008/09/01
[ "https://Stackoverflow.com/questions/38068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible: ``` Typedef myGenDef = < Object1, Object2 >; HashMap< myGenDef > hm = new HashMap< myGenDef >(); for (Entry< myGenDef > ent : hm..entrySet()) { . . . } ```
There's the [pseudo-typedef antipattern](http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html)... ``` class StringList extends ArrayList<String> { } ``` Good stuff, drink up! ;-) As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.
38,074
<p>If you create an Oracle dblink you cannot directly access LOB columns in the target tables.</p> <p>For instance, you create a dblink with:</p> <pre><code>create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; </code></pre> <p>After this you can do stuff like:</p> <pre><code>select column_a, column_b from data_user.sample_table@TEST_LINK </code></pre> <p>Except if the column is a LOB, then you get the error:</p> <pre><code>ORA-22992: cannot use LOB locators selected from remote tables </code></pre> <p>This is <a href="http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328" rel="noreferrer">a documented restriction</a>.</p> <p>The same page suggests you fetch the values into a local table, but that is... kind of messy:</p> <pre><code>CREATE TABLE tmp_hello AS SELECT column_a from data_user.sample_table@TEST_LINK </code></pre> <p>Any other ideas?</p>
[ { "answer_id": 38142, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 0, "selected": false, "text": "<p>Do you have a specific scenario in mind?\nFor example, if the LOB holds files, and you are on a company intranet, perhap...
2008/09/01
[ "https://Stackoverflow.com/questions/38074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846/" ]
If you create an Oracle dblink you cannot directly access LOB columns in the target tables. For instance, you create a dblink with: ``` create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; ``` After this you can do stuff like: ``` select column_a, column_b from data_user.sample_table@TEST_LINK ``` Except if the column is a LOB, then you get the error: ``` ORA-22992: cannot use LOB locators selected from remote tables ``` This is [a documented restriction](http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328). The same page suggests you fetch the values into a local table, but that is... kind of messy: ``` CREATE TABLE tmp_hello AS SELECT column_a from data_user.sample_table@TEST_LINK ``` Any other ideas?
Yeah, it is messy, I can't think of a way to avoid it though. You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table) One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables.
38,160
<p>Lets say I have a loop in Bash:</p> <pre><code>for foo in `some-command` do do-something $foo done </code></pre> <p><code>do-something</code> is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 <code>do-something</code>'s at once.</p> <p>The naive approach seems to be:</p> <pre><code>for foo in `some-command` do do-something $foo &amp; done </code></pre> <p>This will run <em>all</em> <code>do-something</code>s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing <em>all</em> at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the <code>do-something</code>s are finished.</p> <p>How would you write this loop so there are always X <code>do-something</code>s running at once?</p>
[ { "answer_id": 38166, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 4, "selected": false, "text": "<p>Instead of a plain bash, use a Makefile, then specify number of simultaneous jobs with <code>make -jX</code> where X is th...
2008/09/01
[ "https://Stackoverflow.com/questions/38160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163/" ]
Lets say I have a loop in Bash: ``` for foo in `some-command` do do-something $foo done ``` `do-something` is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 `do-something`'s at once. The naive approach seems to be: ``` for foo in `some-command` do do-something $foo & done ``` This will run *all* `do-something`s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing *all* at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the `do-something`s are finished. How would you write this loop so there are always X `do-something`s running at once?
Depending on what you want to do xargs also can help (here: converting documents with pdf2ps): ``` cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w ) find . -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps ``` From the docs: ``` --max-procs=max-procs -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done. ```
38,288
<p>Specifically, what commands do I run from the terminal?</p>
[ { "answer_id": 38289, "author": "quackingduck", "author_id": 3624, "author_profile": "https://Stackoverflow.com/users/3624", "pm_score": 8, "selected": true, "text": "<p>Without a home directory</p>\n\n<pre><code>sudo useradd myuser\n</code></pre>\n\n<p>With home directory</p>\n\n<pre><c...
2008/09/01
[ "https://Stackoverflow.com/questions/38288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3624/" ]
Specifically, what commands do I run from the terminal?
Without a home directory ``` sudo useradd myuser ``` With home directory ``` sudo useradd -m myuser ``` Then set the password ``` sudo passwd myuser ``` Then set the shell ``` sudo usermod -s /bin/bash myuser ```
38,308
<p>Drawing a parallelgram is nicely supported with Graphics.DrawImage:</p> <pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); </code></pre> <p>How, do you do 4 points (obviously the following is not supported, but this is what is wanted):</p> <pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x3, y3), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); } </code></pre>
[ { "answer_id": 38403, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 1, "selected": false, "text": "<p>Normally you would do this with a 3x3 Matrix, but the Matrix class only lets you specify 6 values instead of 9. You mi...
2008/09/01
[ "https://Stackoverflow.com/questions/38308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
Drawing a parallelgram is nicely supported with Graphics.DrawImage: ``` Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); ``` How, do you do 4 points (obviously the following is not supported, but this is what is wanted): ``` Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height); using (Graphics gr = new Graphics.FromImage(destImage)) { Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2), new PointF(x3, y3), new PointF(x4, y4)}; gr.DrawImage(srcImage, destPts); } ```
Closest I can find is [this information](http://vckicks.110mb.com/image-distortion.html), which is extremely laggy.
38,345
<p>I recently "needed" a zip function in Perl 5 (while I was thinking about <a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">How do I calculate relative time?</a>), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements.</p> <p>(Pseudo)example: </p> <pre><code>@a=(1, 2, 3); @b=('apple', 'orange', 'grape'); zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape'); </code></pre> <p><a href="http://www.haskell.org/onlinereport/standard-prelude.html" rel="nofollow noreferrer">Haskell has zip in the Prelude</a> and <a href="http://ferreira.nfshost.com/perl6/zip.html" rel="nofollow noreferrer">Perl 6 has a zip operator</a> built in, but how do you do it in an elegant way in Perl 5?</p>
[ { "answer_id": 38365, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"http://search.cpan.org/perldoc?List::MoreUtils\" rel=\"noreferrer\">List::MoreUtils</a> module has a...
2008/09/01
[ "https://Stackoverflow.com/questions/38345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2905/" ]
I recently "needed" a zip function in Perl 5 (while I was thinking about [How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time)), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements. (Pseudo)example: ``` @a=(1, 2, 3); @b=('apple', 'orange', 'grape'); zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape'); ``` [Haskell has zip in the Prelude](http://www.haskell.org/onlinereport/standard-prelude.html) and [Perl 6 has a zip operator](http://ferreira.nfshost.com/perl6/zip.html) built in, but how do you do it in an elegant way in Perl 5?
Assuming you have exactly two lists and they are exactly the same length, here is a solution originally by merlyn (Randal Schwartz), who called it perversely perlish: ``` sub zip2 { my $p = @_ / 2; return @_[ map { $_, $_ + $p } 0 .. $p - 1 ]; } ``` What happens here is that for a 10-element list, first, we find the pivot point in the middle, in this case 5, and save it in `$p`. Then we make a list of indices up to that point, in this case 0 1 2 3 4. Next we use `map` to pair each index with another index that’s at the same distance from the pivot point as the first index is from the start, giving us (in this case) 0 5 1 6 2 7 3 8 4 9. Then we take a slice from `@_` using that as the list of indices. This means that if `'a', 'b', 'c', 1, 2, 3` is passed to `zip2`, it will return that list rearranged into `'a', 1, 'b', 2, 'c', 3`. This can be written in a single expression along ysth’s lines like so: ``` sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] } ``` Whether you’d want to use either variation depends on whether you can see yourself remembering how they work, but for me, it was a mind expander.
38,352
<p>I need to store contact information for users. I want to present this data on the page as an <a href="http://en.wikipedia.org/wiki/Hcard" rel="nofollow noreferrer">hCard</a> and downloadable as a <a href="http://en.wikipedia.org/wiki/VCard" rel="nofollow noreferrer">vCard</a>. I'd also like to be able to search the database by phone number, email, etc. </p> <p>What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info?</p> <p>I'm using SQL Server 2005, if that matters.</p>
[ { "answer_id": 38436, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 1, "selected": false, "text": "<p>I'm aware of SQLite, but that doesn't really help - I'm talking about figuring out the best schema (regardless of the databa...
2008/09/01
[ "https://Stackoverflow.com/questions/38352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521/" ]
I need to store contact information for users. I want to present this data on the page as an [hCard](http://en.wikipedia.org/wiki/Hcard) and downloadable as a [vCard](http://en.wikipedia.org/wiki/VCard). I'd also like to be able to search the database by phone number, email, etc. What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info? I'm using SQL Server 2005, if that matters.
Consider two tables for People and their addresses: ``` People (pid, prefix, firstName, lastName, suffix, DOB, ... primaryAddressTag ) AddressBook (pid, tag, address1, address2, city, stateProv, postalCode, ... ) ``` The Primary Key (that uniquely identifies each and every row) of People is `pid`. The PK of AddressBook is the composition of pid and tag `(pid, tag)`. Some example data: People ------ ``` 1, Kirk 2, Spock ``` AddressBook ----------- ``` 1, home, '123 Main Street', Iowa 1, work, 'USS Enterprise NCC-1701' 2, other, 'Mt. Selaya, Vulcan' ``` In this example, Kirk has two addresses: one 'home' and one 'work'. One of those two can (and should) be noted as a foreign key (like a cross-reference) in `People` in the primaryAddressTag column. Spock has a single address with the tag 'other'. Since that is Spock's only address, the value 'other' ought to go in the `primaryAddressTag` column for pid=2. This schema has the nice effect of preventing the same person from duplicating any of their own addresses by accidentally reusing tags while at the same time allowing all other people use any address tags they like. Further, with FK references in `primaryAddressTag`, the database system itself will enforce the validity of the primary address tag (via something we database geeks call referential integrity) so that your -- or any -- application need not worry about it.
38,370
<p>I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;www.mysmallwebsite.com&lt;/title&gt; &lt;/head&gt; &lt;frameset&gt; &lt;frame src="http://www.myIsv.com/myWebSite/" name="redir"&gt; &lt;noframes&gt; &lt;p&gt;Original location: &lt;a href="www.myIsv.com/myWebSite/"&gt;http://www.myIsv.com/myWebSite/&lt;/a&gt; &lt;/p&gt; &lt;/noframes&gt; &lt;/frameset&gt; &lt;/html&gt; </code></pre> <p>It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?</p> <p>Edit: This doesn't work both on IE and on Firefox (no plugins)</p> <p>Thanks</p>
[ { "answer_id": 38382, "author": "Alexandru Nedelcu", "author_id": 3280, "author_profile": "https://Stackoverflow.com/users/3280", "pm_score": 0, "selected": false, "text": "<p>What do you mean?\nAre you saying that when you go from www.mysmallwebsite.com to www.myIsv.com/myWebSite/ then ...
2008/09/01
[ "https://Stackoverflow.com/questions/38370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578/" ]
I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content: ``` <html> <head> <title>www.mysmallwebsite.com</title> </head> <frameset> <frame src="http://www.myIsv.com/myWebSite/" name="redir"> <noframes> <p>Original location: <a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a> </p> </noframes> </frameset> </html> ``` It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that? Edit: This doesn't work both on IE and on Firefox (no plugins) Thanks
Sessions are tied to the server **AND** the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do. Try using apache mod rewrite to create a "passthrough redirection", the "**proxy**" flag ([P]) in the rule is the magic flag that you need Documentation at <http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html>
38,409
<p>I would like to convert the following string into an array/nested array: </p> <pre><code>str = "[[this, is],[a, nested],[array]]" newarray = # this is what I need help with! newarray.inspect # =&gt; [['this','is'],['a','nested'],['array']] </code></pre>
[ { "answer_id": 38477, "author": "Ben Childs", "author_id": 2925, "author_profile": "https://Stackoverflow.com/users/2925", "pm_score": 0, "selected": false, "text": "<p>Looks like a basic parsing task. Generally the approach you are going to want to take is to create a recursive function...
2008/09/01
[ "https://Stackoverflow.com/questions/38409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
I would like to convert the following string into an array/nested array: ``` str = "[[this, is],[a, nested],[array]]" newarray = # this is what I need help with! newarray.inspect # => [['this','is'],['a','nested'],['array']] ```
You'll get what you want with YAML. But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this ``` str = "[[this, is], [a, nested], [array]]" ``` Code: ``` require 'yaml' str = "[[this, is],[a, nested],[array]]" ### transform your string in a valid YAML-String str.gsub!(/(\,)(\S)/, "\\1 \\2") YAML::load(str) # => [["this", "is"], ["a", "nested"], ["array"]] ```
38,431
<p>Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.</p> <p>Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.</p> <p>So my egg controller will look some thing like this:</p> <pre><code>public class EggController : Controller { public void Add() { //do stuff RenderView("CreateEgg", viewData); } public void Create() { //do stuff RenderView("ListEggs", viewData); } } </code></pre> <p>So my first page will have a url of something like <a href="http://localhost/egg/add" rel="nofollow noreferrer">http://localhost/egg/add</a> and the form on the page will have an action of:</p> <pre><code>using (Html.Form&lt;EggController&gt;(c =&gt; c.Create()) </code></pre> <p>Meaning the second page will have a url of <a href="http://localhost/Egg/Create" rel="nofollow noreferrer">http://localhost/Egg/Create</a>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <a href="http://localhost/Egg/List" rel="nofollow noreferrer">http://localhost/Egg/List</a> would make more scene. How do I achieve this without making my view or action names misleading?</p>
[ { "answer_id": 38452, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "<p>The problem is your action does two things, violating the Single Responsibility Principle.</p>\n\n<p>If your Create ac...
2008/09/01
[ "https://Stackoverflow.com/questions/38431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong. Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it. So my egg controller will look some thing like this: ``` public class EggController : Controller { public void Add() { //do stuff RenderView("CreateEgg", viewData); } public void Create() { //do stuff RenderView("ListEggs", viewData); } } ``` So my first page will have a url of something like <http://localhost/egg/add> and the form on the page will have an action of: ``` using (Html.Form<EggController>(c => c.Create()) ``` Meaning the second page will have a url of <http://localhost/Egg/Create>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <http://localhost/Egg/List> would make more scene. How do I achieve this without making my view or action names misleading?
The problem is your action does two things, violating the Single Responsibility Principle. If your Create action redirects to the List action when it's done creating the item, then this problem disappears.
38,435
<p>Given an Oracle table created using the following:</p> <pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); </code></pre> <p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow noreferrer">Win32 extensions</a> (from the win32all package), I tried the following:</p> <pre><code>import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() </code></pre> <p>When I run this, I get the following:</p> <pre><code>Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH </code></pre> <p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
[ { "answer_id": 38442, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 1, "selected": false, "text": "<p>My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a stri...
2008/09/01
[ "https://Stackoverflow.com/questions/38435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193/" ]
Given an Oracle table created using the following: ``` CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); ``` Using the Python ODBC module from its [Win32 extensions](http://www.python.org/download/windows/) (from the win32all package), I tried the following: ``` import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() ``` When I run this, I get the following: ``` Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH ``` The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?
I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the `TIMESTAMP WITH (LOCAL) TIME ZONE` data types, only the `TIMESTAMP` data type. As you have discovered, one workaround is in fact to use the `TO_CHAR` method. In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight `TIMESTAMP` column. If you don't have control over the table, another solution may be to create a view that converts from `TIMESTAMP WITH TIME ZONE` to `TIMESTAMP` via a string - sorry, I don't know if there is a way to convert directly from `TIMESTAMP WITH TIME ZONE` to `TIMESTAMP`.
38,501
<p>I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.</p> <p>The thread pool needs to execute a series of tasks. The tasks can be short running (&lt;1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.</p> <p>The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.</p> <p>Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).</p> <p>The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.</p> <p>In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.</p> <p>The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue:</p> <ul> <li>A - 1000 instances - low priority - max tasks 1</li> <li>B - 1000 instances - low priority - max tasks 1</li> <li>C - 1000 instances - low priority - max tasks 1</li> </ul> <p>A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time.</p> <p>It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).</p> <hr> <p>For reference, we might use the following interface:</p> <pre><code>namespace ThreadPool { class Task { public: Task(); void run(); }; class ThreadPool { public: ThreadPool(); ~ThreadPool(); void run(Task *inst); void stop(); }; } </code></pre>
[ { "answer_id": 38504, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).</p>\n</blockquot...
2008/09/01
[ "https://Stackoverflow.com/questions/38501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can. The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available. The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it. Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running). The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important. In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run. The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue: * A - 1000 instances - low priority - max tasks 1 * B - 1000 instances - low priority - max tasks 1 * C - 1000 instances - low priority - max tasks 1 A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time. It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs). --- For reference, we might use the following interface: ``` namespace ThreadPool { class Task { public: Task(); void run(); }; class ThreadPool { public: ThreadPool(); ~ThreadPool(); void run(Task *inst); void stop(); }; } ```
So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising :- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches). APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite "transparent". If the work item performs an alertable wait (::SleepEx, ::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely.
38,508
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
[ { "answer_id": 38513, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 3, "selected": false, "text": "<p>Returning a tuple is the usual way to do this in Python.</p>\n" }, { "answer_id": 38514, "author": "rmm...
2008/09/01
[ "https://Stackoverflow.com/questions/38508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3880/" ]
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: [Is it pythonic for a function to return multiple values?](https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values)
``` def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking ```
38,549
<p>Also, how do <code>LEFT OUTER JOIN</code>, <code>RIGHT OUTER JOIN</code>, and <code>FULL OUTER JOIN</code> fit in?</p>
[ { "answer_id": 38552, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 7, "selected": false, "text": "<p>A inner join only shows rows if there is a matching record on the other (right) side of the join.</p>\n\n<p>A (le...
2008/09/01
[ "https://Stackoverflow.com/questions/38549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836/" ]
Also, how do `LEFT OUTER JOIN`, `RIGHT OUTER JOIN`, and `FULL OUTER JOIN` fit in?
Assuming you're joining on columns with no duplicates, which is a very common case: * An inner join of A and B gives the result of A intersect B, i.e. the inner part of a [Venn diagram](http://en.wikipedia.org/wiki/Venn_diagram) intersection. * An outer join of A and B gives the results of A union B, i.e. the outer parts of a [Venn diagram](http://en.wikipedia.org/wiki/Venn_diagram) union. **Examples** Suppose you have two tables, with a single column each, and data as follows: ``` A B - - 1 3 2 4 3 5 4 6 ``` Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B. **Inner join** An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common. ``` select * from a INNER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b; a | b --+-- 3 | 3 4 | 4 ``` **Left outer join** A left outer join will give all rows in A, plus any common rows in B. ``` select * from a LEFT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b(+); a | b --+----- 1 | null 2 | null 3 | 3 4 | 4 ``` **Right outer join** A right outer join will give all rows in B, plus any common rows in A. ``` select * from a RIGHT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a(+) = b.b; a | b -----+---- 3 | 3 4 | 4 null | 5 null | 6 ``` **Full outer join** A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. ``` select * from a FULL OUTER JOIN b on a.a = b.b; a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4 null | 6 null | 5 ```
38,561
<p>The <code>printf</code> function takes an argument type, such as <code>%d</code> or <code>%i</code> for a <code>signed int</code>. However, I don't see anything for a <code>long</code> value.</p>
[ { "answer_id": 38566, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": false, "text": "<p><code>%ld</code> see <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"noreferrer\"><cod...
2008/09/01
[ "https://Stackoverflow.com/questions/38561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
The `printf` function takes an argument type, such as `%d` or `%i` for a `signed int`. However, I don't see anything for a `long` value.
Put an `l` (lowercased letter L) directly before the specifier. ``` unsigned long n; long m; printf("%lu %ld", n, m); ```
38,571
<p>I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel.</p> <p>Is there an existing function that will let me accomplish this same sort of thing more succinctly?</p> <pre><code>(defun remove-low-words (word-list) "Return a list with words of insufficient score removed." (let ((result nil)) (dolist (word word-list) (when (good-enough-score-p word) (push word result))) result)) </code></pre>
[ { "answer_id": 38594, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": -1, "selected": false, "text": "<p>There are a couple ways you can do this. First, and probably most easily, you can do it recursively.</p>\n\n<pre><cod...
2008/09/01
[ "https://Stackoverflow.com/questions/38571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56456/" ]
I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel. Is there an existing function that will let me accomplish this same sort of thing more succinctly? ``` (defun remove-low-words (word-list) "Return a list with words of insufficient score removed." (let ((result nil)) (dolist (word word-list) (when (good-enough-score-p word) (push word result))) result)) ```
There are several built-in ways of doing this. One way would be: ``` (remove-if-not 'good-enough-score-p word-list) ``` And another: ``` (loop for word in word-list when (good-enough-score-p word) collect word) ``` And yet another: ``` (mapcan (lambda (word) (when (good-enough-score-p word) (list word))) word-list) ``` Etc... There's also [SERIES](http://series.sourceforge.net/) and [Iterate](http://common-lisp.net/project/iterate/). The Iterate version is identical to the LOOP version, but the SERIES version is interesting: ``` (collect (choose-if 'good-enough-score-p (scan word-list)))) ``` So, yes, you're very likely to reinvent *some* wheel. :-)
38,592
<p>I'd like to be able to write a ruby program that can restart without dropping it's socket connections.</p>
[ { "answer_id": 38597, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 0, "selected": false, "text": "<p>You're talking about network sockets, not UNIX sockets I assume?</p>\n\n<p>I'm not sure this suits your needs, but the wa...
2008/09/01
[ "https://Stackoverflow.com/questions/38592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ]
I'd like to be able to write a ruby program that can restart without dropping it's socket connections.
This program gets Google's homepage and then when you pass it SIG\_INT via `Ctrl`-`C` it restarts the program and reads the output of the homepage from the open socket with Google. ``` #!/usr/bin/ruby #simple_connector.rb require 'socket' puts "Started." if ARGV[0] == "restart" sock = IO.open(ARGV[1].to_i) puts sock.read exit else sock = TCPSocket.new('google.com', 80) sock.write("GET /\n") end Signal.trap("INT") do puts "Restarting..." exec("ruby simple_connector.rb restart #{sock.fileno}") end while true sleep 1 end ```
38,601
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/" rel="noreferrer">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
[ { "answer_id": 38916, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 8, "selected": true, "text": "<p>The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doin...
2008/09/01
[ "https://Stackoverflow.com/questions/38601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. ``` <form action="." method="POST"> <table> {% for f in form %} <tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr> {% endfor %} </table> <input type="submit" name="submit" value="Add Product"> </form> ``` Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py: ``` (r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), ``` And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that. That said, here's what you have to do if you're determined to make this work: 1. Define your own `ModelForm` subclass for your model (best to put it in forms.py in your app), and tell it to use the `AdminDateWidget` / `AdminTimeWidget` / `AdminSplitDateTime` (replace 'mydate' etc with the proper field names from your model): ``` from django import forms from my_app.models import Product from django.contrib.admin import widgets class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() ``` 2. Change your URLconf to pass `'form_class': ProductForm` instead of `'model': Product` to the generic `create_object` view (that'll mean `from my_app.forms import ProductForm` instead of `from my_app.models import Product`, of course). 3. In the head of your template, include `{{ form.media }}` to output the links to the Javascript files. 4. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above `{{ form.media }}` you'll need: ``` <script type="text/javascript" src="/my_admin/jsi18n/"></script> <script type="text/javascript" src="/media/admin/js/core.js"></script> ``` You may also wish to use the following admin CSS (thanks [Alex](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583) for mentioning this): ``` <link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/> ``` This implies that Django's admin media (`ADMIN_MEDIA_PREFIX`) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question. This also requires that the URL /my\_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript\_catalog view (or null\_javascript\_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks [Jeremy](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230) for pointing this out). Sample code for your URLconf: ``` (r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), ``` Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media: ``` {% load adminmedia %} /* At the top of the template. */ /* In the head section of the template. */ <script type="text/javascript"> window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; </script> ``` Thanks [lupefiasco](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128) for this addition.
38,602
<p>I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00. In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00</p> <p>What would be the best way to do this? My code is below:</p> <pre><code>this.txtPayment.Text = dr["Payment"].ToString(); </code></pre>
[ { "answer_id": 38611, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 3, "selected": true, "text": "<pre><code>this.txtPayment.Text = string.Format(\"{0:c}\", dr[Payment\"].ToString());\n</code></pre>\n" }, { "answer_id...
2008/09/01
[ "https://Stackoverflow.com/questions/38602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00. In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00 What would be the best way to do this? My code is below: ``` this.txtPayment.Text = dr["Payment"].ToString(); ```
``` this.txtPayment.Text = string.Format("{0:c}", dr[Payment"].ToString()); ```
38,645
<p>I want to combine two structures with differing fields names.</p> <p>For example, starting with:</p> <pre><code>A.field1 = 1; A.field2 = 'a'; B.field3 = 2; B.field4 = 'b'; </code></pre> <p>I would like to have:</p> <pre><code>C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; </code></pre> <p>Is there a more efficient way than using "fieldnames" and a for loop?</p> <p><strong>EDIT:</strong> Let's assume that in the case of field name conflicts we give preference to <code>A</code>.</p>
[ { "answer_id": 38659, "author": "pbh101", "author_id": 1266, "author_profile": "https://Stackoverflow.com/users/1266", "pm_score": 2, "selected": false, "text": "<p>In C, a struct can have another struct as one of it's members. While this isn't exactly the same as what you're asking, yo...
2008/09/02
[ "https://Stackoverflow.com/questions/38645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4135/" ]
I want to combine two structures with differing fields names. For example, starting with: ``` A.field1 = 1; A.field2 = 'a'; B.field3 = 2; B.field4 = 'b'; ``` I would like to have: ``` C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; ``` Is there a more efficient way than using "fieldnames" and a for loop? **EDIT:** Let's assume that in the case of field name conflicts we give preference to `A`.
Without collisions, you can do ``` M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)']; C=struct(M{:}); ``` And this is reasonably efficient. However, `struct` errors on duplicate fieldnames, and pre-checking for them using `unique` kills performance to the point that a loop is better. But here's what it would look like: ``` M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)']; [tmp, rows] = unique(M(1,:), 'last'); M=M(:, rows); C=struct(M{:}); ``` You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to `struct` to gracefully degrade to the conflict handling case.
38,647
<p><strong>When using the Entity Framework, does ESQL perform better than Linq to Entities?</strong> </p> <p>I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.</p>
[ { "answer_id": 38689, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 1, "selected": false, "text": "<p>The more code you can cover with compile time checking for me is something that I'd place a higher premium on than performanc...
2008/09/02
[ "https://Stackoverflow.com/questions/38647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
**When using the Entity Framework, does ESQL perform better than Linq to Entities?** I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.
The most obvious differences are: Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you. Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation. The less obvious key difference is: Linq to Entities allows you to change the shape or "project" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this. Projection is not possible using Entity SQL as you must always return an ObjectQuery<T>. In some scenarios it is possible use ObjectQuery<object> however you must work around the fact that .Select always returns ObjectQuery<DbDataRecord>. See code below... ``` ObjectQuery<DbDataRecord> query = DynamicQuery(context, "Products", "it.ProductName = 'Chai'", "it.ProductName, it.QuantityPerUnit"); public static ObjectQuery<DbDataRecord> DynamicQuery(MyContext context, string root, string selection, string projection) { ObjectQuery<object> rootQuery = context.CreateQuery<object>(root); ObjectQuery<object> filteredQuery = rootQuery.Where(selection); ObjectQuery<DbDataRecord> result = filteredQuery.Select(projection); return result; } ``` There are other more subtle differences described by one of the team members in detail [here](http://blogs.msdn.com/diego/archive/2007/12/20/some-differences-between-esql-and-linq-to-entities-capabilities.aspx) and [here](http://blogs.msdn.com/diego/archive/2007/11/11/choosing-an-entity-framework-api.aspx).
38,651
<p>Is there any way to have a binary compiled from an ActionScript 3 project print stuff to <em>stdout</em> when executed?</p> <p>From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.</p> <p>Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?</p>
[ { "answer_id": 38936, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>As you say, there's no Adobe-created way to do this, but you might have better luck with <a href=\"http://www.multidmedia.com...
2008/09/02
[ "https://Stackoverflow.com/questions/38651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4111/" ]
Is there any way to have a binary compiled from an ActionScript 3 project print stuff to *stdout* when executed? From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe. Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?
With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev. For stdout, open `/dev/fd/1` or `/dev/stdout` as a `FileStream`, then write to that. Example: ``` var stdout : FileStream = new FileStream(); stdout.open(new File("/dev/fd/1"), FileMode.WRITE); stdout.writeUTFBytes("test\n"); stdout.close(); ``` **Note:** See [this answer](https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3) for the difference between `writeUTF()` and `writeUTFBytes()` - the latter will avoid garbled output on stdout.
38,661
<p>Is there any way in IIS to map requests to a particular URL with no extension to a given application.</p> <p>For example, in trying to port something from a Java servlet, you might have a URL like this...</p> <p><a href="http://[server]/MyApp/HomePage?some=parameter" rel="nofollow noreferrer">http://[server]/MyApp/HomePage?some=parameter</a></p> <p>Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful.</p>
[ { "answer_id": 38936, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>As you say, there's no Adobe-created way to do this, but you might have better luck with <a href=\"http://www.multidmedia.com...
2008/09/02
[ "https://Stackoverflow.com/questions/38661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
Is there any way in IIS to map requests to a particular URL with no extension to a given application. For example, in trying to port something from a Java servlet, you might have a URL like this... <http://[server]/MyApp/HomePage?some=parameter> Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful.
With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev. For stdout, open `/dev/fd/1` or `/dev/stdout` as a `FileStream`, then write to that. Example: ``` var stdout : FileStream = new FileStream(); stdout.open(new File("/dev/fd/1"), FileMode.WRITE); stdout.writeUTFBytes("test\n"); stdout.close(); ``` **Note:** See [this answer](https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3) for the difference between `writeUTF()` and `writeUTFBytes()` - the latter will avoid garbled output on stdout.
38,670
<p>Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. </p> <p>I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.</p> <p>After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. </p> <p>In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. </p> <p>I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. </p> <p>Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.</p> <p>I doubt anyone has run into this, but have you? </p> <p>Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. </p> <hr> <p><strong>Jon Limjap:</strong> I edited the title to both make it clear and descriptive <em>and</em> make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.</p>
[ { "answer_id": 38688, "author": "Sean Lynch", "author_id": 4043, "author_profile": "https://Stackoverflow.com/users/4043", "pm_score": 4, "selected": false, "text": "<p>Is the control that you are trying to reference inside of the repeater?</p>\n\n<p>If so then you need to look them up u...
2008/09/02
[ "https://Stackoverflow.com/questions/38670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls. After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy. I doubt anyone has run into this, but have you? Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. --- **Jon Limjap:** I edited the title to both make it clear and descriptive *and* make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.
try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well. here ``` %Temp%\VWDWebCache ``` and possibly here ``` %LocalAppData%\Microsoft\WebsiteCache ```
38,691
<p>Hey so what I want to do is snag the content for the first paragraph. The string <code>$blog_post</code> contains a lot of paragraphs in the following format:</p> <pre><code>&lt;p&gt;Paragraph 1&lt;/p&gt;&lt;p&gt;Paragraph 2&lt;/p&gt;&lt;p&gt;Paragraph 3&lt;/p&gt; </code></pre> <p>The problem I'm running into is that I am writing a regex to grab everything between the first <code>&lt;p&gt;</code> tag and the first closing <code>&lt;/p&gt;</code> tag. However, it is grabbing the first <code>&lt;p&gt;</code> tag and the <strong>last</strong> closing <code>&lt;/p&gt;</code> tag which results in me grabbing everything.</p> <p>Here is my current code:</p> <pre><code>if (preg_match("/[\\s]*&lt;p&gt;[\\s]*(?&lt;firstparagraph&gt;[\\s\\S]+)[\\s]*&lt;\\/p&gt;[\\s\\S]*/",$blog_post,$blog_paragraph)) echo "&lt;p&gt;" . $blog_paragraph["firstparagraph"] . "&lt;/p&gt;"; else echo $blog_post; </code></pre>
[ { "answer_id": 38696, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>It would probably be easier and faster to use <a href=\"http://php.net/strpos\" rel=\"nofollow noreferrer\">strpos()</a>...
2008/09/02
[ "https://Stackoverflow.com/questions/38691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
Hey so what I want to do is snag the content for the first paragraph. The string `$blog_post` contains a lot of paragraphs in the following format: ``` <p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p> ``` The problem I'm running into is that I am writing a regex to grab everything between the first `<p>` tag and the first closing `</p>` tag. However, it is grabbing the first `<p>` tag and the **last** closing `</p>` tag which results in me grabbing everything. Here is my current code: ``` if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph)) echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>"; else echo $blog_post; ```
Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this ``` <p>.*?</p> ``` Placing the `?` after your `*` makes it non-greedy, meaning it will only match as little text as necessary before matching the `</p>`.
38,713
<p>I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this:</p> <pre><code>use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later ... $opt_v &amp;&amp; print "something interesting\n"; </code></pre> <p>In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. </p> <p>In ruby,the more-or-less exact equivalent would be </p> <pre><code>require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end </code></pre> <p>where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this?</p> <ul> <li>Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with?</li> <li>Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing?</li> </ul> <p><em>updated:</em> Thanks for the answers suggesting optparse, but I should have been clearer that it's not <em>how</em> to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.</p>
[ { "answer_id": 38741, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.rubyinside.com/trollop-command-line-option-parser-for-ruby-944.html\" rel=\"nofollow noreferrer\">fi...
2008/09/02
[ "https://Stackoverflow.com/questions/38713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3979/" ]
I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this: ``` use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later ... $opt_v && print "something interesting\n"; ``` In perl, I kind of grit my teeth and let $opt\_v be (effectively) a global. In ruby,the more-or-less exact equivalent would be ``` require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end ``` where $opt\_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this? * Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with? * Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr\_writer sort of thing? *updated:* Thanks for the answers suggesting optparse, but I should have been clearer that it's not *how* to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.
A while back I ran across [this blog post](http://blog.toddwerth.com/entries/5) (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script. I would lean toward using this technique, where the options are contained in one object and use either attr\_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the `thingy` class if your options are set with a `thingy.verbose=true` attr\_writer or `thingy.process(true)` call.
38,729
<p>I decided to make a system for a client using <a href="https://web.archive.org/web/20080517021542/http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle ActiveRecord</a>, everything went well until I found that the transactions do not work, for instance;</p> <pre><code> TransactionScope t = new TransactionScope(); try { member.Save(); //This is just to see transaction working throw new Exception("Exception"); foreach (qfh.Beneficiary b1 in l) { b1.Create(); } } catch (Exception ex) { t.VoteRollBack(); MessageBox.Show(ex.Message); } finally { t.Dispose(); } </code></pre> <p>But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening?</p> <p>I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?</p>
[ { "answer_id": 38737, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": true, "text": "<p>Ben's got it. That doc is a little confusing. Refer to the last block <a href=\"https://web.archive.org/web/2008041701414...
2008/09/02
[ "https://Stackoverflow.com/questions/38729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
I decided to make a system for a client using [Castle ActiveRecord](https://web.archive.org/web/20080517021542/http://www.castleproject.org/activerecord/index.html), everything went well until I found that the transactions do not work, for instance; ``` TransactionScope t = new TransactionScope(); try { member.Save(); //This is just to see transaction working throw new Exception("Exception"); foreach (qfh.Beneficiary b1 in l) { b1.Create(); } } catch (Exception ex) { t.VoteRollBack(); MessageBox.Show(ex.Message); } finally { t.Dispose(); } ``` But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening? I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?
Ben's got it. That doc is a little confusing. Refer to the last block [on the page](https://web.archive.org/web/20080417014143/http://www.castleproject.org/ActiveRecord/documentation/v1rc1/usersguide/scopes.html), "Nested transactions".
38,746
<p>Over at <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion">Can you modify text files when committing to subversion?</a> <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion#38666">Grant</a> suggested that I block commits instead.</p> <p>However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?</p>
[ { "answer_id": 39162, "author": "bstark", "author_id": 4056, "author_profile": "https://Stackoverflow.com/users/4056", "pm_score": 2, "selected": false, "text": "<p>You could use something like this as your pre-commit script:</p>\n\n<pre>\n#! /usr/bin/perl\n\nwhile (&lt;&gt;) {\n $las...
2008/09/02
[ "https://Stackoverflow.com/questions/38746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
Over at [Can you modify text files when committing to subversion?](https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion) [Grant](https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion#38666) suggested that I block commits instead. However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?
**[@Konrad](https://stackoverflow.com/questions/38746/how-to-detect-file-ends-in-newline#39185)**: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail: ```none $ cat test_no_newline.txt this file doesn't end in newline$ $ cat test_with_newline.txt this file ends in newline $ ``` Though I found that tail has get last byte option. So I modified your script to: ``` #!/bin/sh c=`tail -c 1 $1` if [ "$c" != "" ]; then echo "no newline" fi ```
38,756
<p>I'm looking for a way of getting a <strong>concurrent collection</strong> in <strong>C#</strong> or at least a collection which supports a <strong>concurrent enumerator</strong>. Right now I'm getting an <code>InvalidOperationException</code> when the collection over which I'm iterating changes. </p> <p>I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way</p> <p>Code snippet:</p> <pre class="lang-cs prettyprint-override"><code>foreach (String s in (List&lt;String&gt;) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } </code></pre> <p>--edit--</p> <p>I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.</p> <pre class="lang-cs prettyprint-override"><code>private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } } </code></pre>
[ { "answer_id": 38765, "author": "Damian", "author_id": 3390, "author_profile": "https://Stackoverflow.com/users/3390", "pm_score": 4, "selected": true, "text": "<p>Other than doing a deep-copy your best bet might be to lock the collection:</p>\n\n<pre><code> List&lt;string&gt; theList ...
2008/09/02
[ "https://Stackoverflow.com/questions/38756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
I'm looking for a way of getting a **concurrent collection** in **C#** or at least a collection which supports a **concurrent enumerator**. Right now I'm getting an `InvalidOperationException` when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way Code snippet: ```cs foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } ``` --edit-- I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well. ```cs private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } } ```
Other than doing a deep-copy your best bet might be to lock the collection: ``` List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings); lock(theList.SyncRoot) { foreach(string s in theList) { // Do some Jazz } } ```
38,791
<p>Which Database table Schema is more efficient and why?</p> <pre><code>"Users (UserID, UserName, CompamyId)" "Companies (CompamyId, CompanyName)" </code></pre> <p>OR</p> <pre><code>"Users (UserID, UserName)" "Companies (CompamyId, CompanyName)" "UserCompanies (UserID, CompamyId)" </code></pre> <p>Given the fact that user and company have one-to-one relation.</p>
[ { "answer_id": 38793, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 4, "selected": true, "text": "<p>For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less numbe...
2008/09/02
[ "https://Stackoverflow.com/questions/38791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
Which Database table Schema is more efficient and why? ``` "Users (UserID, UserName, CompamyId)" "Companies (CompamyId, CompanyName)" ``` OR ``` "Users (UserID, UserName)" "Companies (CompamyId, CompanyName)" "UserCompanies (UserID, CompamyId)" ``` Given the fact that user and company have one-to-one relation.
For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries.
38,820
<p>Which class design is better and why?</p> <pre><code>public class User { public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee : User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member : User { public String MemberId; public String JoinDate; public String ExpiryDate; } </code></pre> <p>OR</p> <pre><code>public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; } </code></pre>
[ { "answer_id": 38827, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 4, "selected": false, "text": "<p>I don't like either one. What happens when someone is both a member and an employee?</p>\n" }, { "answer_id": ...
2008/09/02
[ "https://Stackoverflow.com/questions/38820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
Which class design is better and why? ``` public class User { public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee : User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member : User { public String MemberId; public String JoinDate; public String ExpiryDate; } ``` OR ``` public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; } ```
The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship. * An employee IS A user * An employee HAS A userinfo Which one is correct? This is your answer.
38,842
<p>I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?</p>
[ { "answer_id": 38976, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 2, "selected": false, "text": "<p>You should take a look at <strong><a href=\"http://api.openoffice.org\" rel=\"nofollow noreferrer\">Apache OpenOff...
2008/09/02
[ "https://Stackoverflow.com/questions/38842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?
I haven't come up with a solution I'm really happy with but here are some notes: * Q. What is the OO API for mail merge? A. <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html> * Q. What support groups? A. <http://user.services.openoffice.org/en/forum/viewforum.php?f=20> * Q. Sample code? A. <http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778> <http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017> * Q. Any more examples? A. file:///C:/Program%20Files/OpenOffice.org\_2.4\_SDK/examples/examples.html (comes with the SDK) <http://www.oooforum.org/forum/viewtopic.phtml?p=94970> * Q. How do I build the examples? A. e.g., for WriterDemo (C:\Program Files\OpenOffice.org\_2.4\_SDK\examples\CLI\VB.NET\WriterDemo) 1. Add references to everything in here: C:\Program Files\OpenOffice.org 2.4\program\assembly 2. That is cli\_basetypes, cli\_cppuhelper, cli\_types, cli\_ure * Q. Does OO use the same separate data/document file for mail merge? A. It allows for a range of data sources including csv files * Q. Does OO allow you to merge to all the different types (fax, email, new document printer)? A. You can merge to a new document, print and email * Q. Can you add custom fields? A. Yes * Q. How do you create a new document in VB.Net? A. ``` Dim xContext As XComponentContext xContext = Bootstrap.bootstrap() Dim xFactory As XMultiServiceFactory xFactory = DirectCast(xContext.getServiceManager(), _ XMultiServiceFactory) 'Create the Desktop Dim xDesktop As unoidl.com.sun.star.frame.XDesktop xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _ unoidl.com.sun.star.frame.XDesktop) 'Open a new empty writer document Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader) Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _ New unoidl.com.sun.star.beans.PropertyValue() {} Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "private:factory/swriter", "_blank", 0, arProps) Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument) ``` * Q. How do you save the document? A. ``` Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable) arProps = New unoidl.com.sun.star.beans.PropertyValue() {} storer.storeToURL("file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", arProps) ``` * Q. How do you Open the document? A. ``` Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", "_blank", 0, arProps) ``` * Q. How do you initiate a mail merge in VB.Net? A. 1. Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple. 2. In VBScript: Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager") 'Now set up a new MailMerge using the settings extracted from that doc Set oMailMerge = objServiceManager.createInstance("com.sun.star.text.MailMerge") oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType> oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType> oMailMerge.execute(Array()) 3. In VB.Net (Option Strict Off) ``` Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo) Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(New [Object]() {}) ``` 4. The same thing but with Option Strict On (doesn't work) ``` Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo) Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.GetType().InvokeMember("DocumentURL", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"}) oMailMerge.GetType().InvokeMember("DataSourceName", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("CommandType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0}) oMailMerge.GetType().InvokeMember("Command", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("OutputType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2}) oMailMerge.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error ```
38,875
<p>My website was recently attacked by, what seemed to me as, an innocent code:</p> <pre><code>&lt;?php if ( isset( $ _GET['page'] ) ) { include( $ _GET['page'] . ".php" ); } else { include("home.php"); } ?&gt; </code></pre> <p>There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.</p> <p>This website has an explanation and a few examples of avoiding code injection: <a href="http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html" rel="noreferrer">http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html</a></p> <p>How would you protect this code from code injection?</p>
[ { "answer_id": 38884, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>I'm assuming you deal with files in the same directory:</p>\n\n<pre><code>&lt;?php\nif (isset($_GET['page']) &amp;&amp; !empt...
2008/09/02
[ "https://Stackoverflow.com/questions/38875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
My website was recently attacked by, what seemed to me as, an innocent code: ``` <?php if ( isset( $ _GET['page'] ) ) { include( $ _GET['page'] . ".php" ); } else { include("home.php"); } ?> ``` There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection. This website has an explanation and a few examples of avoiding code injection: <http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html> How would you protect this code from code injection?
Use a whitelist and make sure the page is in the whitelist: ``` $whitelist = array('home', 'page'); if (in_array($_GET['page'], $whitelist)) { include($_GET['page'].'.php'); } else { include('home.php'); } ```
38,890
<p>Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?</p> <p>Update: I mean FK constraint.</p>
[ { "answer_id": 38892, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>I think your best bet is to remove the explicit constraint and add a <a href=\"http://msdn.microsoft.com/en-us/library/ms...
2008/09/02
[ "https://Stackoverflow.com/questions/38890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows? Update: I mean FK constraint.
You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through. ``` CREATE TRIGGER employee_insupd ON employee FOR INSERT AS /* Get the range of level for this job type from the jobs table. */ DECLARE @min_lvl tinyint, @max_lvl tinyint, @emp_lvl tinyint, @job_id smallint SELECT @min_lvl = min_lvl, @max_lvl = max_lvl, @emp_lvl = i.job_lvl, @job_id = i.job_id FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id JOIN jobs j ON j.job_id = i.job_id IF (@job_id = 1) and (@emp_lvl <> 10) BEGIN RAISERROR ('Job id 1 expects the default level of 10.', 16, 1) ROLLBACK TRANSACTION END ELSE IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl) BEGIN RAISERROR ('The level for job_id:%d should be between %d and %d.', 16, 1, @job_id, @min_lvl, @max_lvl) ROLLBACK TRANSACTION END ```
38,920
<p>I'm getting this problem:</p> <pre><code>PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 </code></pre> <p>from this script:</p> <pre><code>&lt;?php $to = "chris.mahan@gmail.com"; $subject = "test"; $body = "this is a test"; if (mail($to, $subject, $body)){ echo "mail sent"; } else { echo "problem"; } ?&gt; </code></pre> <p>section from php.ini on the server:</p> <pre><code>[mail function] ; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25 ; For Win32 only. sendmail_from = support@domain.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ;sendmail_path = </code></pre> <p>(note that "server" and "domain" refer accurately to the actual server and domain name)</p> <p>In IIS, SMTP is running. Under <code>"Access"</code> tab, <code>"Relay"</code> button, the Select which computers may relay through this virtual server is set to <code>checkbox "only the list below"</code> and on the list is <code>"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).</code></p> <p>Server is running <code>Windows Server 2003 Service Pack 2</code>, fully patched as of 5 PM Sept 1st 2008. I assume it is running <code>IIS7</code> (how to check?).</p> <p>Any ideas?</p> <p>In reponse to <a href="https://stackoverflow.com/users/2257/espo">Espo</a>: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.</p> <p>Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.</p> <p>Thanks to both Espo and Yaakov for helping me out.</p>
[ { "answer_id": 38923, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>You are using the wrong SMTP-server. If you you are only going to send emails to your gmail-account, have a look at my answer...
2008/09/02
[ "https://Stackoverflow.com/questions/38920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479/" ]
I'm getting this problem: ``` PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 ``` from this script: ``` <?php $to = "chris.mahan@gmail.com"; $subject = "test"; $body = "this is a test"; if (mail($to, $subject, $body)){ echo "mail sent"; } else { echo "problem"; } ?> ``` section from php.ini on the server: ``` [mail function] ; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25 ; For Win32 only. sendmail_from = support@domain.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ;sendmail_path = ``` (note that "server" and "domain" refer accurately to the actual server and domain name) In IIS, SMTP is running. Under `"Access"` tab, `"Relay"` button, the Select which computers may relay through this virtual server is set to `checkbox "only the list below"` and on the list is `"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).` Server is running `Windows Server 2003 Service Pack 2`, fully patched as of 5 PM Sept 1st 2008. I assume it is running `IIS7` (how to check?). Any ideas? In reponse to [Espo](https://stackoverflow.com/users/2257/espo): This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server. Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working. Thanks to both Espo and Yaakov for helping me out.
Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed.
38,922
<p>I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. </p> <p>What is the easiest way to do this? </p> <p>Maybe the db migration is not the best for this type of thing. Thanks!</p> <hr> <p>It would be nice if it could be a completely automated process. The following process would be ideal.</p> <ol> <li>A user signs up on our site to use this web app</li> <li>Migrations are run to create this users database and get tables setup correctly</li> </ol> <p>Is there a way of calling a rake task from a ruby application?</p>
[ { "answer_id": 38927, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 1, "selected": false, "text": "<p>We use seperate configuration files for each user. So in the config/ dir we would have roo.database.yml which would connect to m...
2008/09/02
[ "https://Stackoverflow.com/questions/38922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2737/" ]
I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. What is the easiest way to do this? Maybe the db migration is not the best for this type of thing. Thanks! --- It would be nice if it could be a completely automated process. The following process would be ideal. 1. A user signs up on our site to use this web app 2. Migrations are run to create this users database and get tables setup correctly Is there a way of calling a rake task from a ruby application?
To answer part of your question, here's how you'd run a rake task from inside Rails code: ``` require 'rake' load 'path/to/task.rake' Rake::Task['foo:bar:baz'].invoke ``` Mind you, I have no idea how (or why) you could have one database per user.
38,940
<p>If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:</p> <pre><code>SELECT Field1, Field2 FROM Table </code></pre> <p>And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:</p> <pre><code>SELECT Field1, Field2, Field3 = 'Value' FROM Table </code></pre> <p>Is this possible at all?</p>
[ { "answer_id": 38942, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT Field1, Field2, 'Value' Field3 FROM Table\n</code></pre>\n\n<p>or for clarity</p>\n\n<pre><code>SELECT Field1, Fi...
2008/09/02
[ "https://Stackoverflow.com/questions/38940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393028/" ]
If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be: ``` SELECT Field1, Field2 FROM Table ``` And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal: ``` SELECT Field1, Field2, Field3 = 'Value' FROM Table ``` Is this possible at all?
``` SELECT Field1, Field2, 'Value' Field3 FROM Table ``` or for clarity ``` SELECT Field1, Field2, 'Value' AS Field3 FROM Table ```
38,948
<p>Can I use <a href="http://struts.apache.org/" rel="nofollow noreferrer">Struts</a> as a backend and PHP as front end for a web application? If yes, what may be the implications.</p>
[ { "answer_id": 38972, "author": "Doug Miller", "author_id": 3431280, "author_profile": "https://Stackoverflow.com/users/3431280", "pm_score": 0, "selected": false, "text": "<p>What do you mean by backend and and frontend?</p>\n\n<p>If you mean using Java for the admin side of your site a...
2008/09/02
[ "https://Stackoverflow.com/questions/38948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can I use [Struts](http://struts.apache.org/) as a backend and PHP as front end for a web application? If yes, what may be the implications.
The first thing to came to mind is [Quercus](http://www.caucho.com/resin-3.0/quercus/) (from the makers of the Resin servlet engine), as Jordi mentioned. It is a Java implementation of the PHP runtime and purportedly allows you to access Java objects directly from your PHP (part of me says "yay, at last"). On the other hand, while I have been itching to try a project this way, I would probably keep the separation between Java EE and PHP unless there was a real reason to integrate on the code-level. Instead, why don't you try an [SOA](http://en.wikipedia.org/wiki/Service-oriented_architecture) approach, where your PHP "front-end" calls into the Struts application over a defined REST or SOAP API (strong vote for REST here) over HTTP. ``` http://mydomain.com/rest/this-is-a-method-call?parameter1=foo ``` You can use Struts to build your entire "backend" model, dealing only with business logic and data, and completely ignoring presentation. As you expose the API with these URLs, and you are basically building a REST API (which may come in handy later if you ever need to provide greater access to your backend, perhaps by other client apps). Your PHP application can be built separately (and rather thinly), calling into the REST API (perhaps using Curl) as if it would call into a database or some native PHP class library. Anyway, that's what I'd do. But, if you do use Quercus, please post how it went.
38,960
<p>I would like to test a string containing a path to a file for existence of that file (something like the <code>-e</code> test in Perl or the <code>os.path.exists()</code> in Python) in C#.</p>
[ { "answer_id": 38962, "author": "Daniel Jennings", "author_id": 3641, "author_profile": "https://Stackoverflow.com/users/3641", "pm_score": 9, "selected": true, "text": "<p>Use:</p>\n\n<pre><code>File.Exists(path)\n</code></pre>\n\n<p>MSDN: <a href=\"http://msdn.microsoft.com/en-us/libra...
2008/09/02
[ "https://Stackoverflow.com/questions/38960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I would like to test a string containing a path to a file for existence of that file (something like the `-e` test in Perl or the `os.path.exists()` in Python) in C#.
Use: ``` File.Exists(path) ``` MSDN: <http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx> Edit: In System.IO
38,987
<p>I want to merge two dictionaries into a new dictionary.</p> <pre><code>x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = merge(x, y) &gt;&gt;&gt; z {'a': 1, 'b': 3, 'c': 4} </code></pre> <p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>
[ { "answer_id": 38989, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = dict(x.items() + y.items())\nprint z\n</code></pre>\n\n<p>For i...
2008/09/02
[ "https://Stackoverflow.com/questions/38987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207/" ]
I want to merge two dictionaries into a new dictionary. ``` x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = merge(x, y) >>> z {'a': 1, 'b': 3, 'c': 4} ``` Whenever a key `k` is present in both dictionaries, only the value `y[k]` should be kept.
How can I merge two Python dictionaries in a single expression? --------------------------------------------------------------- For dictionaries `x` and `y`, their shallowly-merged dictionary `z` takes values from `y`, replacing those from `x`. * In Python 3.9.0 or greater (released 17 October 2020, [`PEP-584`](https://www.python.org/dev/peps/pep-0584/), [discussed here](https://bugs.python.org/issue36144)): ```py z = x | y ``` * In Python 3.5 or greater: ```py z = {**x, **y} ``` * In Python 2, (or 3.4 or lower) write a function: ```py def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z ``` and now: ```py z = merge_two_dicts(x, y) ``` ### Explanation Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries: ```py x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} ``` The desired result is to get a new dictionary (`z`) with the values merged, and the second dictionary's values overwriting those from the first. ```py >>> z {'a': 1, 'b': 3, 'c': 4} ``` A new syntax for this, proposed in [PEP 448](https://www.python.org/dev/peps/pep-0448) and [available as of Python 3.5](https://mail.python.org/pipermail/python-dev/2015-February/138564.html), is ```py z = {**x, **y} ``` And it is indeed a single expression. Note that we can merge in with literal notation as well: ```py z = {**x, 'foo': 1, 'bar': 2, **y} ``` and now: ```py >>> z {'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4} ``` It is now showing as implemented in the [release schedule for 3.5, PEP 478](https://www.python.org/dev/peps/pep-0478/#features-for-3-5), and it has now made its way into the [What's New in Python 3.5](https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations) document. However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process: ```py z = x.copy() z.update(y) # which returns None since it mutates z ``` In both approaches, `y` will come second and its values will replace `x`'s values, thus `b` will point to `3` in our final result. Not yet on Python 3.5, but want a *single expression* ----------------------------------------------------- If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a *single expression*, the most performant while the correct approach is to put it in a function: ```py def merge_two_dicts(x, y): """Given two dictionaries, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z ``` and then you have a single expression: ```py z = merge_two_dicts(x, y) ``` You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number: ```py def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. """ result = {} for dictionary in dict_args: result.update(dictionary) return result ``` This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries `a` to `g`: ```py z = merge_dicts(a, b, c, d, e, f, g) ``` and key-value pairs in `g` will take precedence over dictionaries `a` to `f`, and so on. Critiques of Other Answers -------------------------- Don't use what you see in the formerly accepted answer: ```py z = dict(x.items() + y.items()) ``` In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. **In Python 3, this will fail** because you're adding two `dict_items` objects together, not two lists - ```py >>> c = dict(a.items() + b.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' ``` and you would have to explicitly create them as lists, e.g. `z = dict(list(x.items()) + list(y.items()))`. This is a waste of resources and computation power. Similarly, taking the union of `items()` in Python 3 (`viewitems()` in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, **since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:** ```py >>> c = dict(a.items() | b.items()) ``` This example demonstrates what happens when values are unhashable: ```py >>> x = {'a': []} >>> y = {'b': []} >>> dict(x.items() | y.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' ``` Here's an example where `y` should have precedence, but instead the value from `x` is retained due to the arbitrary order of sets: ```py >>> x = {'a': 2} >>> y = {'a': 1} >>> dict(x.items() | y.items()) {'a': 2} ``` Another hack you should not use: ```py z = dict(x, **y) ``` This uses the `dict` constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic. Here's an example of the usage being [remediated in django](https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff). Dictionaries are intended to take hashable keys (e.g. `frozenset`s or tuples), but **this method fails in Python 3 when keys are not strings.** ```py >>> c = dict(a, **b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: keyword arguments must be strings ``` From the [mailing list](https://mail.python.org/pipermail/python-dev/2010-April/099459.html), Guido van Rossum, the creator of the language, wrote: > > I am fine with > declaring dict({}, \*\*{1:3}) illegal, since after all it is abuse of > the \*\* mechanism. > > > and > > Apparently dict(x, \*\*y) is going around as "cool hack" for "call > x.update(y) and return x". Personally, I find it more despicable than > cool. > > > It is my understanding (as well as the understanding of the [creator of the language](https://mail.python.org/pipermail/python-dev/2010-April/099485.html)) that the intended usage for `dict(**y)` is for creating dictionaries for readability purposes, e.g.: ```py dict(a=1, b=10, c=11) ``` instead of ```py {'a': 1, 'b': 10, 'c': 11} ``` Response to comments -------------------- > > Despite what Guido says, `dict(x, **y)` is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the \*\* operator in this place an abuse of the mechanism, in fact, \*\* was designed precisely to pass dictionaries as keywords. > > > Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. `dict` broke this consistency in Python 2: ``` >>> foo(**{('a', 'b'): None}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() keywords must be strings >>> dict(**{('a', 'b'): None}) {('a', 'b'): None} ``` This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change. I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints. More comments: > > `dict(x.items() + y.items())` is still the most readable solution for Python 2. Readability counts. > > > My response: `merge_two_dicts(x, y)` actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated. > > `{**x, **y}` does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging. > > > Yes. I must refer you back to the question, which is asking for a *shallow* merge of ***two*** dictionaries, with the first's values being overwritten by the second's - in a single expression. Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them: ```py from copy import deepcopy def dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z ``` Usage: ```py >>> x = {'a':{1:{}}, 'b': {2:{}}} >>> y = {'b':{10:{}}, 'c': {11:{}}} >>> dict_of_dicts_merge(x, y) {'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}} ``` Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at [my answer to the canonical question on a "Dictionaries of dictionaries merge"](https://stackoverflow.com/a/24088493/541136). Less Performant But Correct Ad-hocs ----------------------------------- These approaches are less performant, but they will provide correct behavior. They will be *much less* performant than `copy` and `update` or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they *do* respect the order of precedence (latter dictionaries have precedence) You can also chain the dictionaries manually inside a [dict comprehension](https://www.python.org/dev/peps/pep-0274/): ```py {k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7 ``` or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced): ```py dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2 ``` `itertools.chain` will chain the iterators over the key-value pairs in the correct order: ```py from itertools import chain z = dict(chain(x.items(), y.items())) # iteritems in Python 2 ``` Performance Analysis -------------------- I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.) ```py from timeit import repeat from itertools import chain x = dict.fromkeys('abcdefg') y = dict.fromkeys('efghijk') def merge_two_dicts(x, y): z = x.copy() z.update(y) return z min(repeat(lambda: {**x, **y})) min(repeat(lambda: merge_two_dicts(x, y))) min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) min(repeat(lambda: dict(chain(x.items(), y.items())))) min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) ``` In Python 3.8.1, NixOS: ```py >>> min(repeat(lambda: {**x, **y})) 1.0804965235292912 >>> min(repeat(lambda: merge_two_dicts(x, y))) 1.636518670246005 >>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) 3.1779992282390594 >>> min(repeat(lambda: dict(chain(x.items(), y.items())))) 2.740647904574871 >>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) 4.266070580109954 ``` ```sh $ uname -a Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux ``` Resources on Dictionaries ------------------------- * [My explanation of Python's **dictionary implementation**, updated for 3.6.](https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302) * [Answer on how to add new keys to a dictionary](https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535) * [Mapping two lists into a dictionary](https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067) * [The official Python docs on dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) * [The Dictionary Even Mightier](https://www.youtube.com/watch?v=66P5FMkWoVU) - talk by Brandon Rhodes at Pycon 2017 * [Modern Python Dictionaries, A Confluence of Great Ideas](https://www.youtube.com/watch?v=npw4s1QTmPg) - talk by Raymond Hettinger at Pycon 2017
38,993
<p>Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either <code>.sty</code> or <code>.cls</code>, how would I do that?</p>
[ { "answer_id": 38994, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 2, "selected": false, "text": "<pre><code>egrep \"\\.sty$|\\.cls$\"\n</code></pre>\n" }, { "answer_id": 39000, "author": "aku", "author...
2008/09/02
[ "https://Stackoverflow.com/questions/38993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either `.sty` or `.cls`, how would I do that?
``` ls | grep -E "\.(sty|cls)$" ``` * `\.` matches literally a `"."` - an unescaped `.` matches any character * `(sty|cls)` - match `"sty"` or `"cls"` - the | is an `or` and the brackets limit the expression. * `$` forces the match to be at the end of the line Note, you want `grep -E` or `egrep`, not `grep -e` as that's a different option for lists of patterns.
38,998
<p>I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.</p> <p>I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this?</p> <p>I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain.</p> <p>Any tips or advice greatly appreciated--anything for a few less sleepless nights...</p>
[ { "answer_id": 39012, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "<p>You can extend .net controls and make them return actual id's when related properties are called.</p>\n\n<p>ClientI...
2008/09/02
[ "https://Stackoverflow.com/questions/38998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3212/" ]
I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements. I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this? I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain. Any tips or advice greatly appreciated--anything for a few less sleepless nights...
The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery. something like this: ``` <asp:button id="ImAButton" runat="server">Click Me</asp:button> <script type="text/javascript"> var buttonId = "<%=ImAButton.ClientId%>"; $("#"+buttonId).bind('click', function() { alert('hi); }); </script> ``` It's a hack I know, but it will work. (I should note for the un-initiated, I'm using the Prototype $ get by id method there)
39,003
<p>If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?</p> <p>I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.</p> <p>What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid</p>
[ { "answer_id": 39008, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 0, "selected": false, "text": "<p>I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation ...
2008/09/02
[ "https://Stackoverflow.com/questions/39003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3024/" ]
If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface? I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing. What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid
If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes. Lets go with a smarter route instead; if your goal is to **avoid code and test code duplication** you might want to create an abstract class instead that handles the **recurring** code. E.g. you have the following interface: ``` public interface IFoo { public void CommonCode(); public void SpecificCode(); } ``` You might want to create an abstract class: ``` public abstract class AbstractFoo : IFoo { public void CommonCode() { SpecificCode(); } public abstract void SpecificCode(); } ``` Testing that is easy; implement the abstract class in the test class either as an inner class: ``` [TestFixture] public void TestClass { private class TestFoo : AbstractFoo { boolean hasCalledSpecificCode = false; public void SpecificCode() { hasCalledSpecificCode = true; } } [Test] public void testCommonCallsSpecificCode() { TestFoo fooFighter = new TestFoo(); fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); } } ``` ...or let the test class extend the abstract class itself if that fits your fancy. ``` [TestFixture] public void TestClass : AbstractFoo { boolean hasCalledSpecificCode; public void specificCode() { hasCalledSpecificCode = true; } [Test] public void testCommonCallsSpecificCode() { AbstractFoo fooFighter = this; hasCalledSpecificCode = false; fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); } } ``` Having an abstract class take care of common code that an interface implies gives a much cleaner code design. I hope this makes sense to you. --- As a side note, this is a common design pattern called the **[Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern)**. In the above example, the template method is the `CommonCode` method and `SpecificCode` is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff. A lot of frameworks rely on this behavioral pattern, e.g. [ASP.NET](http://msdn.microsoft.com/en-us/library/ms178472.aspx) where you have to implement the hooks in a page or a user controls such as the generated `Page_Load` method which is called by the `Load` event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method.
39,006
<p>I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file.</p> <p>This was working, but in the last week whenever I try &amp; start WAMP I get this error in the event logs:</p> <blockquote> <p>VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results.</p> </blockquote> <p>and the server won't start. I can't think of what's changed. </p> <p>I've copied the conf file below.</p> <pre><code>NameVirtualHost * &lt;VirtualHost *:80&gt; ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common &lt;Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/"&gt; Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p><strong>EDIT:</strong> I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e</p> <pre><code>NameVirtualHost *:80 </code></pre> <p>I get this error:</p> <blockquote> <p>Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80 </p> </blockquote>
[ { "answer_id": 39287, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Well, it seems the problem there is the way (and order) in which you assign the ports. </p>\n\n<p>Basically, *:80 means...
2008/09/02
[ "https://Stackoverflow.com/questions/39006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file. This was working, but in the last week whenever I try & start WAMP I get this error in the event logs: > > VirtualHost \*:80 -- mixing \* ports and > non-\* ports with a NameVirtualHost > address is not supported, proceeding > with undefined results. > > > and the server won't start. I can't think of what's changed. I've copied the conf file below. ``` NameVirtualHost * <VirtualHost *:80> ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common <Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/"> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all </Directory> </VirtualHost> ``` **EDIT:** I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e ``` NameVirtualHost *:80 ``` I get this error: > > Only one usage of each socket address (protocol/network address/port) is normally permitted. : make\_sock: could not bind to address 0.0.0.0:80 > > >
> > NameVirtualHost \*:80 > > > I get this error: > > > Only one usage of each socket address (protocol/network address/port) is normally >permitted. : make\_sock: could not bind to address 0.0.0.0:80 > > > I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running? (If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections")
39,053
<p>I'm trying to access a data source that is defined within a web container (JBoss) from a fat client outside the container.</p> <p>I've decided to look up the data source through JNDI. Actually, my persistence framework (Ibatis) does this.</p> <p>When performing queries I always end up getting this error:</p> <pre><code>java.lang.IllegalAccessException: Method=public abstract java.sql.Connection java.sql.Statement.getConnection() throws java.sql.SQLException does not return Serializable Stacktrace: org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.doStatementMethod(WrapperDataSourceS ervice.java:411), org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.invoke(WrapperDataSourceService.java :223), sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25), java.lang.reflect.Method.invoke(Method.java:585), org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155), org.jboss.mx.server.Invocation.dispatch(Invocation.java:94), org.jboss.mx.server.Invocation.invoke(Invocation.java:86), org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264), org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659), </code></pre> <p>My Datasource:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;datasources&gt; &lt;local-tx-datasource&gt; &lt;jndi-name&gt;jdbc/xxxxxDS&lt;/jndi-name&gt; &lt;connection-url&gt;jdbc:oracle:thin:@xxxxxxxxx:1521:xxxxxxx&lt;/connection-url&gt; &lt;use-java-context&gt;false&lt;/use-java-context&gt; &lt;driver-class&gt;oracle.jdbc.driver.OracleDriver&lt;/driver-class&gt; &lt;user-name&gt;xxxxxxxx&lt;/user-name&gt; &lt;password&gt;xxxxxx&lt;/password&gt; &lt;exception-sorter-class-name&gt;org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter&lt;/exception-sorter-class-name&gt; &lt;min-pool-size&gt;5&lt;/min-pool-size&gt; &lt;max-pool-size&gt;20&lt;/max-pool-size&gt; &lt;/local-tx-datasource&gt; &lt;/datasources&gt; </code></pre> <p>Does anyone have a clue where this could come from? </p> <p>Maybe someone even knows a better way how to achieve this. Any hints are much appreciated!</p> <p>Cheers,</p> <p>Michael</p>
[ { "answer_id": 39153, "author": "brabster", "author_id": 2362, "author_profile": "https://Stackoverflow.com/users/2362", "pm_score": 0, "selected": false, "text": "<p>I think the exception indicates that the SQLConnection object you're trying to retrieve doesn't implement the Serializabl...
2008/09/02
[ "https://Stackoverflow.com/questions/39053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to access a data source that is defined within a web container (JBoss) from a fat client outside the container. I've decided to look up the data source through JNDI. Actually, my persistence framework (Ibatis) does this. When performing queries I always end up getting this error: ``` java.lang.IllegalAccessException: Method=public abstract java.sql.Connection java.sql.Statement.getConnection() throws java.sql.SQLException does not return Serializable Stacktrace: org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.doStatementMethod(WrapperDataSourceS ervice.java:411), org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.invoke(WrapperDataSourceService.java :223), sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25), java.lang.reflect.Method.invoke(Method.java:585), org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155), org.jboss.mx.server.Invocation.dispatch(Invocation.java:94), org.jboss.mx.server.Invocation.invoke(Invocation.java:86), org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264), org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659), ``` My Datasource: ``` <?xml version="1.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> <jndi-name>jdbc/xxxxxDS</jndi-name> <connection-url>jdbc:oracle:thin:@xxxxxxxxx:1521:xxxxxxx</connection-url> <use-java-context>false</use-java-context> <driver-class>oracle.jdbc.driver.OracleDriver</driver-class> <user-name>xxxxxxxx</user-name> <password>xxxxxx</password> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name> <min-pool-size>5</min-pool-size> <max-pool-size>20</max-pool-size> </local-tx-datasource> </datasources> ``` Does anyone have a clue where this could come from? Maybe someone even knows a better way how to achieve this. Any hints are much appreciated! Cheers, Michael
Not sure if this is the same issue? [JBoss DataSource config](http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/Server_Configuration_Guide/Connectors_on_JBoss-Configuring_JDBC_DataSources.html) > > DataSource wrappers are not usable outside of the server VM > > >
39,061
<p>I've convinced myself that they can't.</p> <p>Take for example:</p> <p>4 4 + 4 /</p> <p>stack: 4 stack: 4 4 4 + 4 = 8 stack: 8 stack: 8 4 8 / 4 = 2 stack: 2</p> <p>There are two ways that you could write the above expression with the same operators and operands such that the operands all come first: "4 4 4 + /" and "4 4 4 / +", neither of which evaluate to 2.</p> <p>"4 4 4 + /" stack: 4 stack: 4 4 stack: 4 4 4 4 + 4 = 8 stack: 4 8 4 / 8 = 0.5 stack: 0.5</p> <p>"4 4 4 / +" stack: 4 stack: 4 4 stack: 4 4 4 4 / 4 = 1 stack: 4 1 4 + 1 = 5 stack: 5</p> <p>If you have the ability to swap items on the stack then yes, it's possible, otherwise, no.</p> <p>Thoughts?</p>
[ { "answer_id": 39068, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>It is enough to show one that can't in order to tell you the answer to this.</p>\n\n<p>If you can't reorder the sta...
2008/09/02
[ "https://Stackoverflow.com/questions/39061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175/" ]
I've convinced myself that they can't. Take for example: 4 4 + 4 / stack: 4 stack: 4 4 4 + 4 = 8 stack: 8 stack: 8 4 8 / 4 = 2 stack: 2 There are two ways that you could write the above expression with the same operators and operands such that the operands all come first: "4 4 4 + /" and "4 4 4 / +", neither of which evaluate to 2. "4 4 4 + /" stack: 4 stack: 4 4 stack: 4 4 4 4 + 4 = 8 stack: 4 8 4 / 8 = 0.5 stack: 0.5 "4 4 4 / +" stack: 4 stack: 4 4 stack: 4 4 4 4 / 4 = 1 stack: 4 1 4 + 1 = 5 stack: 5 If you have the ability to swap items on the stack then yes, it's possible, otherwise, no. Thoughts?
Consider the algebraic expression: ``` (a + b) * (c + d) ``` The obvious translation to RPN would be: ``` a b + c d + * ``` Even with a swap operation available, I don't think there is a way to collect all the operators on the right: ``` a b c d + a b S ``` where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either.
39,064
<p>I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting <code>P/Invoke</code> errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem. </p> <p>Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a <code>Unable to find entry point named XXX in DLL</code> error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.</p> <p>I'd like to use a .net declaration for the DLL of</p> <pre><code>Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer </code></pre>
[ { "answer_id": 39079, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>Try using the <a href=\"http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx\" rel=\"nofollow noreferrer\">__decspec(d...
2008/09/02
[ "https://Stackoverflow.com/questions/39064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting `P/Invoke` errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem. Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a `Unable to find entry point named XXX in DLL` error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer. I'd like to use a .net declaration for the DLL of ``` Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer ```
Try using the [\_\_decspec(dllexport)](http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx) magic pixie dust in your C++ function declaration. This declaration sets up several things that you need to successfully export a function from a DLL. You may also need to use WINAPI or something similar: ``` __declspec(dllexport) WINAPI int Multiply(int p1, int p2) { return p1 * p2; } ``` The WINAPI sets up the function calling convention such that it's suitable for calling from a language such as VB.NET.
39,070
<p>We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. </p> <p>Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?</p>
[ { "answer_id": 39074, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "<p>We have used a variation of <a href=\"http://www.jscape.com/articles/sftp_using_csharp.html\" rel=\"nofollow noreferrer\...
2008/09/02
[ "https://Stackoverflow.com/questions/39070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4180/" ]
We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?
the question has three subquestions: 1) choosing the secure transfer protocol The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL. You can check details about FTP, FTP/SSL and SFTP differences at <http://www.rebex.net/secure-ftp.net/> page. 2) SFTP or FTP/SSL server for Windows When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 (<http://www.g6ftpserver.com/>) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising (<http://www.bitvise.com/winsshd>). 3) Internet File Transfer Component for ASP.NET Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the [Rebex File Transfer Pack](http://www.rebex.net/file-transfer-pack/) - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer). Following code shows how to upload a file to the server via SFTP. The code is taken from our [Rebex SFTP tutorial page](http://www.rebex.net/sftp.net/tutorial-sftp.aspx#upload-download). ``` // create client, connect and log in Sftp client = new Sftp(); client.Connect(hostname); client.Login(username, password); // upload the 'test.zip' file to the current directory at the server client.PutFile(@"c:\data\test.zip", "test.zip"); // upload the 'index.html' file to the specified directory at the server client.PutFile(@"c:\data\index.html", "/wwwroot/index.html"); // download the 'test.zip' file from the current directory at the server client.GetFile("test.zip", @"c:\data\test.zip"); // download the 'index.html' file from the specified directory at the server client.GetFile("/wwwroot/index.html", @"c:\data\index.html"); // upload a text using a MemoryStream string message = "Hello from Rebex SFTP for .NET!"; byte[] data = System.Text.Encoding.Default.GetBytes(message); System.IO.MemoryStream ms = new System.IO.MemoryStream(data); client.PutFile(ms, "message.txt"); ``` Martin
39,086
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
[ { "answer_id": 39089, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new f...
2008/09/02
[ "https://Stackoverflow.com/questions/39086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4166/" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file ```
I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file: ``` from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with fdopen(fh,'w') as new_file: with open(file_path) as old_file: for line in old_file: new_file.write(line.replace(pattern, subst)) #Copy the file permissions from the old file to the new file copymode(file_path, abs_path) #Remove original file remove(file_path) #Move new file move(abs_path, file_path) ```
39,104
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p> <p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p> <pre> dbname = os.path.join(os.path.dirname(__file__), "database.dat") </pre> <p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
[ { "answer_id": 39295, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 2, "selected": false, "text": "<p>That's probably the way to do it, without resorting to something more advanced like using setuptools to install the fil...
2008/09/02
[ "https://Stackoverflow.com/questions/39104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4198/" ]
I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/). How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the `__file__` variable in the module which accesses the database: ``` dbname = os.path.join(os.path.dirname(__file__), "database.dat") ``` It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.
Try using pkg\_resources, which is part of setuptools (and available on all of the pythons I have access to right now): ``` >>> import pkg_resources >>> pkg_resources.resource_filename(__name__, "foo.config") 'foo.config' >>> pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' ``` There's more discussion about using pkg\_resources to get resources on the [eggs](http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources) page and the [pkg\_resources](http://peak.telecommunity.com/DevCenter/PkgResources) page. Also note, where possible it's probably advisable to use pkg\_resources.resource\_stream or pkg\_resources.resource\_string because if the package is part of an egg, resource\_filename will copy the file to a temporary directory.
39,108
<p>What would be the best way to draw a simple animation just before showing a modal <a href="https://docs.oracle.com/javase/9/docs/api/javax/swing/JDialog.html" rel="nofollow noreferrer">JDialog</a>? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the <code>setVisible</code> method of the dialog.</p> <p>However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into <a href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html" rel="nofollow noreferrer">EDT</a> before the JDialog becomes visible, since the current event on the EDT has not been completed yet.</p>
[ { "answer_id": 39868, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 1, "selected": false, "text": "<p>Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need...
2008/09/02
[ "https://Stackoverflow.com/questions/39108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3993/" ]
What would be the best way to draw a simple animation just before showing a modal [JDialog](https://docs.oracle.com/javase/9/docs/api/javax/swing/JDialog.html)? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the `setVisible` method of the dialog. However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into [EDT](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) before the JDialog becomes visible, since the current event on the EDT has not been completed yet.
Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need to bundle those actions in a runnable that is passed to the EDT at once. eg: ``` SwingUtilities.invokeLater(new Runnable(){ public void run(){ doAnnimation(); showDialog(); } } ``` It may be best to subclass JDialog so that you can just add the doAnnimation() logic to the setVisible(..) or show() method before calling the superclass implementation. Finally, I imagine you'll need to set the dimensions of the dalog manually -- I don't remember if Java will know the actual size of the dialog before it is shown, so you may get some useless information for your annimation if you query the size before showing it.
39,112
<p>I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.</p> <p>What is the best way in c# to implement cache locking in ASP.NET? </p>
[ { "answer_id": 39144, "author": "khebbie", "author_id": 4189, "author_profile": "https://Stackoverflow.com/users/4189", "pm_score": 2, "selected": false, "text": "<p>Craig Shoemaker has made an excellent show on asp.net caching:\n<a href=\"http://polymorphicpodcast.com/shows/webperforman...
2008/09/02
[ "https://Stackoverflow.com/questions/39112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2471/" ]
I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache. What is the best way in c# to implement cache locking in ASP.NET?
Here's the basic pattern: * Check the cache for the value, return if its available * If the value is not in the cache, then implement a lock * Inside the lock, check the cache again, you might have been blocked * Perform the value look up and cache it * Release the lock In code, it looks like this: ``` private static object ThisLock = new object(); public string GetFoo() { // try to pull from cache here lock (ThisLock) { // cache was empty before we got the lock, check again inside the lock // cache is still empty, so retreive the value here // store the value in the cache here } // return the cached value here } ```
39,240
<p>I have lots of article store in MS SQL server 2005 database in a table called Articles-</p> <pre><code>"Articles (ArticleID, ArticleTitle, ArticleContent)" </code></pre> <p>Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.</p> <p>Is it possible to do this in MS SQL Server 2005?</p>
[ { "answer_id": 39257, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>First of all you need to define what article similarity means.<br>\nFor example you can associate some meta information with a...
2008/09/02
[ "https://Stackoverflow.com/questions/39240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
I have lots of article store in MS SQL server 2005 database in a table called Articles- ``` "Articles (ArticleID, ArticleTitle, ArticleContent)" ``` Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy. Is it possible to do this in MS SQL Server 2005?
Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search. ``` Select Top 10 ArticleID, ArticleTitle, ArticleContent From Articles Order By (Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc, (Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc ``` You can then add/remove case statements from the order by clause to improve the list based on your data.
39,243
<p>Is there any query which can return me the number of revisions made to the structure of a database table?</p> <p>Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?</p>
[ { "answer_id": 39269, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 2, "selected": false, "text": "<p>I think you need to create a <code>trigger</code> and store all changes to the table in a separate table. You can ...
2008/09/02
[ "https://Stackoverflow.com/questions/39243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
Is there any query which can return me the number of revisions made to the structure of a database table? Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?
You can get last modify date or creation date of object in `SQL Server`. For examle info on tables: ``` SELECT * FROM sys.objects WHERE type='U' ``` [More info on msdn](http://msdn.microsoft.com/en-us/library/ms190324.aspx) Number of pages can be fetched from `sys.database_files`. [Check documentation](http://msdn.microsoft.com/en-us/library/ms174397.aspx)
39,281
<p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p> <p>e.g. for "Employee" Entity</p> <p><strong>Design 1:</strong></p> <pre><code>-- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" </code></pre> <p><strong>Design 2:</strong></p> <pre><code>-- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId, .., ..)" </code></pre> <p>Is there any other way of doing this thing? </p> <p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p> <p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>
[ { "answer_id": 39296, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 3, "selected": false, "text": "<p>The way that I've seen this done in the past is have</p>\n\n<pre><code>Employees (EmployeeId, DateModified, &lt; Em...
2008/09/02
[ "https://Stackoverflow.com/questions/39281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this: e.g. for "Employee" Entity **Design 1:** ``` -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" ``` **Design 2:** ``` -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)" -- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId, .., ..)" ``` Is there any other way of doing this thing? The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields. And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).
1. Do **not** put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems. 2. Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort. 3. Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this... ``` CREATE VIEW EmployeeHistory AS , FirstName, , DepartmentId SELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName, RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName, RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId, FROM EmployeeHistories ```
39,364
<p>I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.</p> <p>The following code:</p> <pre><code>&lt;?php // Make sure classes are in the include path. ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); // Use autoload so include or require statements are not needed. require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); // Run the application. App_Main::run('production'); </code></pre> <p>Is causing the following error:</p> <pre> [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 </pre> <p>I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.</p> <p>The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.</p> <p>I believe it must be something to do with the include_path but I am not sure.</p>
[ { "answer_id": 39372, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 1, "selected": false, "text": "<p>The fact that it only happens sporadically makes me think this is less of a programming issue, and more of a sysadmin ...
2008/09/02
[ "https://Stackoverflow.com/questions/39364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge. The following code: ``` <?php // Make sure classes are in the include path. ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); // Use autoload so include or require statements are not needed. require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); // Run the application. App_Main::run('production'); ``` Is causing the following error: ``` [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 ``` I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option. The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then. I believe it must be something to do with the include\_path but I am not sure.
for a start I think your include path should maybe have a trailing slash. Here is an example of mine : ``` set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/'); ``` You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes. For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they **have to be relative to the original requested index file, not the bootstrap file they are defined within**. This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file.
39,391
<p>If I create an HTTP <code>java.net.URL</code> and then call <code>openConnection()</code> on it, does it necessarily imply that an HTTP post is going to happen? I know that <code>openStream()</code> implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?</p>
[ { "answer_id": 39431, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 2, "selected": false, "text": "<p>No it does not. But if the protocol of the URL is HTTP, you'll get a <a href=\"http://java.sun.com/javase/6/docs/api/java/net/...
2008/09/02
[ "https://Stackoverflow.com/questions/39391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4223/" ]
If I create an HTTP `java.net.URL` and then call `openConnection()` on it, does it necessarily imply that an HTTP post is going to happen? I know that `openStream()` implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?
If you retrieve the `URLConnection` object using `openConnection()` it doesn't actually start communicating with the server. That doesn't happen until you get the stream from the `URLConnection()`. When you first get the connection you can add/change headers and other connection properties before actually opening it. URLConnection's life cycle is a bit odd. It doesn't send the headers to the server until you've gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you'll be writing data to it (You may need to call `setDoOutput(true)` for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server. For example, this should do a POST: ``` URL myURL = new URL("http://example.com/my/path"); URLConnection conn = myURL.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); OutputStream os = conn.getOutputStream(); os.write("Hi there!"); os.close(); InputStream is = conn.getInputStream(); // read stuff here ``` While this would do a GET: ``` URL myURL = new URL("http://example.com/my/path"); URLConnection conn = myURL.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); InputStream is = conn.getInputStream(); // read stuff here ``` `URLConnection` will also do other weird things. If the server specifies a content length then `URLConnection` will keep the underlying input stream open until it receives that much data, *even if you explicitly close it*. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as the `URLConnection` would keep the network connection open. This probably probably exists even if you just use `getStream()` though.
39,395
<p>How can I calculate the value of PI using C#?</p> <p>I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?</p> <p>I'm not too fussy about performance, mainly how to go about it from a learning point of view.</p>
[ { "answer_id": 39401, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 1, "selected": false, "text": "<p>Calculate like this:</p>\n\n<pre><code>x = 1 - 1/3 + 1/5 - 1/7 + 1/9 (... etc as far as possible.)\nPI = x * 4\n</code></pre>...
2008/09/02
[ "https://Stackoverflow.com/questions/39395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How can I calculate the value of PI using C#? I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up? I'm not too fussy about performance, mainly how to go about it from a learning point of view.
If you want recursion: ``` PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...)))) ``` This would become, after some rewriting: ``` PI = 2 * F(1); ``` with F(i): ``` double F (int i) { return 1 + i / (2.0 * i + 1) * F(i + 1); } ``` Isaac Newton (you may have heard of him before ;) ) came up with this trick. Note that I left out the end condition, to keep it simple. In real life, you kind of need one.
39,399
<p>I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in <code>web.xml</code>:</p> <pre><code>&lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; </code></pre> <p>and in <code>index.jsp</code>:</p> <pre><code>&lt;% response.sendRedirect("/myproject/MyAction.action"); %&gt; </code></pre> <p>Surely there's a better way!</p>
[ { "answer_id": 39599, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 1, "selected": false, "text": "<p>It appears that a popular solution will not work in all containers... <a href=\"http://www.theserverside.com/discussions/threa...
2008/09/02
[ "https://Stackoverflow.com/questions/39399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913/" ]
I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in `web.xml`: ``` <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> ``` and in `index.jsp`: ``` <% response.sendRedirect("/myproject/MyAction.action"); %> ``` Surely there's a better way!
Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request. So, in particular, I'd replace the ``` <% response.sendRedirect("/myproject/MyAction.action"); %> ``` in index.jsp with ``` <jsp:forward page="/MyAction.action" /> ``` The other effect of this change is that the user won't see the URL in the address bar change from "<http://server/myproject>" to "<http://server/myproject/index.jsp>", as the forward happens internally on the server.
39,447
<p>I have a class property exposing an internal IList&lt;> through</p> <pre><code>System.Collections.ObjectModel.ReadOnlyCollection&lt;&gt; </code></pre> <p>How can I pass a part of this <code>ReadOnlyCollection&lt;&gt;</code> without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.</p>
[ { "answer_id": 39460, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "<p>You can always write a class that implements IList and forwards all calls to the original list (so it doesn't have it's own co...
2008/09/02
[ "https://Stackoverflow.com/questions/39447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ]
I have a class property exposing an internal IList<> through ``` System.Collections.ObjectModel.ReadOnlyCollection<> ``` How can I pass a part of this `ReadOnlyCollection<>` without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.
Try a method that returns an enumeration using yield: ``` IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) { foreach ( T item in input ) if ( /* criterion is met */ ) yield return item; } ```
39,468
<p>I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?</p> <p>I've declared all my public functions as follows:</p> <pre><code>#define MYDCC_API __declspec(dllexport) MYDCCL_API unsigned long MYDCC_GetVer( void); . . . </code></pre> <p>Any ideas?</p> <hr> <p>Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:</p> <p><a href="http://www.codeproject.com/KB/DLL/XDllPt2.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/DLL/XDllPt2.aspx</a></p> <p>Also, I had a few problems passing strings to the DLL functions, I found this helpful:</p> <p><a href="http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml" rel="nofollow noreferrer">http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml</a></p> <hr>
[ { "answer_id": 39478, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<p>By using <code>__declspec</code> for export, the function name will get exported <em>mangled</em>, i.e. contain type...
2008/09/02
[ "https://Stackoverflow.com/questions/39468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3685/" ]
I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem? I've declared all my public functions as follows: ``` #define MYDCC_API __declspec(dllexport) MYDCCL_API unsigned long MYDCC_GetVer( void); . . . ``` Any ideas? --- Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful: <http://www.codeproject.com/KB/DLL/XDllPt2.aspx> Also, I had a few problems passing strings to the DLL functions, I found this helpful: <http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml> ---
By using `__declspec` for export, the function name will get exported *mangled*, i.e. contain type information to help the C++ compiler resolve overloads. VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an [export definition](http://msdn.microsoft.com/en-us/library/d91k01sh%28VS.80%29.aspx) file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions: ``` LIBRARY mylibname EXPORTS myfirstfunction secondfunction ``` Additionally, you have to specify the `stdcall` calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method.
39,475
<p>Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error? </p> <pre><code>$ git-fsck bad sha1 file: .git/objects/55/tmp_obj_a07724 </code></pre>
[ { "answer_id": 39927, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 4, "selected": true, "text": "<p>It's not a simple answer, sadly. But this might help:</p>\n\n<p><a href=\"http://schacon.github.com/git/user-manual.h...
2008/09/02
[ "https://Stackoverflow.com/questions/39475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ]
Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error? ``` $ git-fsck bad sha1 file: .git/objects/55/tmp_obj_a07724 ```
It's not a simple answer, sadly. But this might help: [Recovering from repository corruption](http://schacon.github.com/git/user-manual.html#recovering-from-repository-corruption) (from the Git's user manual).
39,476
<p>In the <a href="https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist">How Can I Expose Only a Fragment of IList&lt;></a> question one of the answers had the following code snippet:</p> <pre><code>IEnumerable&lt;object&gt; FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item)) yield return item; } } </code></pre> <p>What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.</p>
[ { "answer_id": 39482, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": false, "text": "<p>Iteration. It creates a state machine \"under the covers\" that remembers where you were on each additional cycle o...
2008/09/02
[ "https://Stackoverflow.com/questions/39476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
In the [How Can I Expose Only a Fragment of IList<>](https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist) question one of the answers had the following code snippet: ``` IEnumerable<object> FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item)) yield return item; } } ``` What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.
The `yield` contextual keyword actually does quite a lot here. The function returns an object that implements the `IEnumerable<object>` interface. If a calling function starts `foreach`ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in **C# 2.0**. In earlier versions you had to create your own `IEnumerable` and `IEnumerator` objects to do stuff like this. The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example: ``` public void Consumer() { foreach(int i in Integers()) { Console.WriteLine(i.ToString()); } } public IEnumerable<int> Integers() { yield return 1; yield return 2; yield return 4; yield return 8; yield return 16; yield return 16777216; } ``` When you step through the example, you'll find the first call to `Integers()` returns `1`. The second call returns `2` and the line `yield return 1` is not executed again. Here is a real-life example: ``` public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms) { using (var connection = CreateConnection()) { using (var command = CreateCommand(CommandType.Text, sql, connection, parms)) { command.CommandTimeout = dataBaseSettings.ReadCommandTimeout; using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return make(reader); } } } } } ```
39,536
<p>I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?</p> <p>Some points to note:</p> <ul> <li>Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1</li> <li>Local server is running the same (so using PHP is an option), but the OS is Windows</li> <li>Local server has Ruby on it (so using Ruby is a valid option)</li> <li>The live MySQL db <em>can</em> accept remote connections from different IPs</li> <li>I cannot enable replication on the remote server</li> </ul> <p><strong><em>Update:</em></strong> I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:</p> <p><code>mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql</code></p>
[ { "answer_id": 39545, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "<p>Is MySQL replication an option? You could even turn it on and off if you didn't want it constantly replicating.</p>\n\n<p...
2008/09/02
[ "https://Stackoverflow.com/questions/39536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this? Some points to note: * Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1 * Local server is running the same (so using PHP is an option), but the OS is Windows * Local server has Ruby on it (so using Ruby is a valid option) * The live MySQL db *can* accept remote connections from different IPs * I cannot enable replication on the remote server ***Update:*** I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password: `mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql`
Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline: ``` cd "into mysql directory" mysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\backup\database.sql ``` The program will ask you for the database password and then generate a file c:\backup\database.sql that you can run on your windows machine to insert the data. With a small database that should be fairly fast.
39,541
<p>Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):</p> <pre><code>Private Sub Command1_Click(Index As Integer) Text1(Index).Text = Timer End Sub </code></pre> <p>I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?</p>
[ { "answer_id": 39544, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Make an array of controls.</p>\n\n<pre><code>TextBox[] textboxes = new TextBox[] {\n textBox1,\n textBox2,\n ...
2008/09/02
[ "https://Stackoverflow.com/questions/39541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()): ``` Private Sub Command1_Click(Index As Integer) Text1(Index).Text = Timer End Sub ``` I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?
Make a generic list of textboxes: ``` var textBoxes = new List<TextBox>(); // Create 10 textboxes in the collection for (int i = 0; i < 10; i++) { var textBox = new TextBox(); textBox.Text = "Textbox " + i; textBoxes.Add(textBox); } // Loop through and set new values on textboxes in collection for (int i = 0; i < textBoxes.Count; i++) { textBoxes[i].Text = "New value " + i; // or like this var textBox = textBoxes[i]; textBox.Text = "New val " + i; } ```
39,561
<p>Trying to get my css / C# functions to look like this:</p> <pre><code>body { color:#222; } </code></pre> <p>instead of this:</p> <pre><code>body { color:#222; } </code></pre> <p>when I auto-format the code.</p>
[ { "answer_id": 39573, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "<p>Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines -> New Line Options for braces -> Uncheck all boxes.</p>\...
2008/09/02
[ "https://Stackoverflow.com/questions/39561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
Trying to get my css / C# functions to look like this: ``` body { color:#222; } ``` instead of this: ``` body { color:#222; } ``` when I auto-format the code.
**C#** 1. In the *Tools* Menu click *Options* 2. Click *Show all Parameters* (checkbox at the bottom left) (*Show all settings* in VS 2010) 3. Text Editor 4. C# 5. Formatting 6. New lines And there check when you want new lines with brackets **Css:** *almost the same, but fewer options* 1. In the *Tools* Menu click *Options* 2. Click *Show all Parameters* (checkbox at the bottom left) (*Show all settings* in VS 2010) 3. Text Editor 4. CSS 5. Format And than you select the formatting you want (in your case second radio button) **For Visual Studio 2015:** Tools → Options In the sidebar, go to Text Editor → C# → Formatting → New Lines and uncheck every checkbox in the section *"New line options for braces"* [![enter image description here](https://i.stack.imgur.com/Drc10.png)](https://i.stack.imgur.com/Drc10.png) **For Mac OS users:** Preferences → Source Code → Code Formatting → choose what ever you want to change (like C# source code) → C# Format → Edit -→ New Lines
39,562
<p>A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.</p> <p>I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:</p> <pre><code>welcome.english = "Welcome!" welcome.spanish = "¡Bienvenido!" ... </code></pre> <p>This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.</p> <p>How do you design the database to support this kind of implementation?</p> <p>Thanks.</p>
[ { "answer_id": 39587, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "<p>They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (da...
2008/09/02
[ "https://Stackoverflow.com/questions/39562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679/" ]
A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages. I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like: ``` welcome.english = "Welcome!" welcome.spanish = "¡Bienvenido!" ... ``` This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language. How do you design the database to support this kind of implementation? Thanks.
They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that has LanguageID(int) and LanguageName(varchar). Then, when you want to show your users the news-page you do: ``` SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID WHERE NewsText.NewsLanguageID = <<Session["UserLanguageID"]>> ``` That Session-bit is a local variable where you store the users language when they log in or enters the site for the first time.
39,567
<p>In Ruby, given an array in one of the following forms...</p> <pre><code>[apple, 1, banana, 2] [[apple, 1], [banana, 2]] </code></pre> <p>...what is the best way to convert this into a hash in the form of...</p> <pre><code>{apple =&gt; 1, banana =&gt; 2} </code></pre>
[ { "answer_id": 39621, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 7, "selected": false, "text": "<p>Simply use <code>Hash[*array_variable.flatten]</code></p>\n\n<p>For example:</p>\n\n<pre><code>a1 = ['apple', 1, 'bana...
2008/09/02
[ "https://Stackoverflow.com/questions/39567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4142/" ]
In Ruby, given an array in one of the following forms... ``` [apple, 1, banana, 2] [[apple, 1], [banana, 2]] ``` ...what is the best way to convert this into a hash in the form of... ``` {apple => 1, banana => 2} ```
**NOTE**: For a concise and efficient solution, please see [Marc-André Lafortune's answer](https://stackoverflow.com/a/20831486/332936) below. This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows. --- **Warning!** Solutions using **flatten** will not preserve Array keys or values! Building on @John Topley's popular answer, let's try: ``` a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ] h3 = Hash[*a3.flatten] ``` This throws an error: ``` ArgumentError: odd number of arguments for Hash from (irb):10:in `[]' from (irb):10 ``` The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values. If you want to use Array keys or values, you can use **map**: ``` h3 = Hash[a3.map {|key, value| [key, value]}] puts "h3: #{h3.inspect}" ``` This preserves the Array key: ``` h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2} ```
39,576
<p>I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.</p> <pre><code>INSERT INTO TMP_DIM_EXCH_RT (EXCH_WH_KEY, EXCH_NAT_KEY, EXCH_DATE, EXCH_RATE, FROM_CURCY_CD, TO_CURCY_CD, EXCH_EFF_DATE, EXCH_EFF_END_DATE, EXCH_LAST_UPDATED_DATE) VALUES (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'); </code></pre>
[ { "answer_id": 39602, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 9, "selected": true, "text": "<p>This works in Oracle:</p>\n<pre><code>insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)\n select 8000,0,'Mult...
2008/09/02
[ "https://Stackoverflow.com/questions/39576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3734/" ]
I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle. ``` INSERT INTO TMP_DIM_EXCH_RT (EXCH_WH_KEY, EXCH_NAT_KEY, EXCH_DATE, EXCH_RATE, FROM_CURCY_CD, TO_CURCY_CD, EXCH_EFF_DATE, EXCH_EFF_END_DATE, EXCH_LAST_UPDATED_DATE) VALUES (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'), (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'); ```
This works in Oracle: ``` insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE) select 8000,0,'Multi 8000',1 from dual union all select 8001,0,'Multi 8001',1 from dual ``` The thing to remember here is to use the `from dual` statement.
39,583
<p>How much do you rely on database transactions? </p> <p>Do you prefer small or large transaction scopes ? </p> <p>Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server side transactions or vice-versa? </p> <p>What about nested transactions? </p> <p>Do you have some tips&amp;tricks related to transactions ?</p> <p>Any gotchas you encountered working with transaction ?</p> <p>All sort of answers are welcome.</p>
[ { "answer_id": 39594, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 2, "selected": false, "text": "<p>I use transactions on every write operation to the database.<br>\nSo there are quite a few small \"transactions\" ...
2008/09/02
[ "https://Stackoverflow.com/questions/39583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
How much do you rely on database transactions? Do you prefer small or large transaction scopes ? Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server side transactions or vice-versa? What about nested transactions? Do you have some tips&tricks related to transactions ? Any gotchas you encountered working with transaction ? All sort of answers are welcome.
I always wrap a transaction in a using statement. ``` using(IDbTransaction transaction ) { // logic goes here. transaction.Commit(); } ``` Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback. In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits. I've found this pattern has drastically reduced record locking issues.
39,615
<p>I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:</p> <ul> <li>Display the base name 'f'</li> <li>Perform an action on 'f.in'</li> <li>Perform another action on 'f.out'</li> </ul> <p>I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.</p>
[ { "answer_id": 39636, "author": "Nathan Fritz", "author_id": 4142, "author_profile": "https://Stackoverflow.com/users/4142", "pm_score": 3, "selected": false, "text": "<p>Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second fil...
2008/09/02
[ "https://Stackoverflow.com/questions/39615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3974/" ]
I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should: * Display the base name 'f' * Perform an action on 'f.in' * Perform another action on 'f.out' I don't have any way to list the set of base filenames, other than to search for \*.in (or \*.out) for example.
Assuming you have two programs that process the two files, process\_in.exe and process\_out.exe: ``` for %%f in (*.in) do ( echo %%~nf process_in "%%~nf.in" process_out "%%~nf.out" ) ``` %%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in <https://technet.microsoft.com/en-us/library/bb490909.aspx> (midway down the page) or just in the next answer.
39,639
<p>My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3).</p> <p>I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file:</p> <pre><code>&lt;aop:aspectj-autoproxy /&gt; &lt;bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" /&gt; </code></pre> <p>Created aspect:</p> <pre><code>package com.example.bg.web.utils; import org.apache.log4j.Logger; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class AuditLogProcessor { private final static Logger log = Logger.getLogger(AuditLogProcessor.class); @After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))") public void afterHandleRequest() { log.info("test111"); } @After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))") public void afterRebuildThumbnail() { log.info("test222"); } }</code></pre> <p>My controllers:</p> <pre><code>class AssetAddController implements Controller class AssetThumbnailRebuildController extends MultiActionController</code></pre> <p>When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail() What did I do wrong?</p> <p><strong>NOTE</strong></p> <p>I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about.</p> <p><strong>EDIT</strong></p> <p>There were indeed some misspellings, thanks Cheekysoft. But the problem still persists.</p>
[ { "answer_id": 39766, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 1, "selected": false, "text": "<p>AspectJ doesn't work well with classes in the Spring Web MVC framework. <a href=\"http://static.springframework.org/spring/doc...
2008/09/02
[ "https://Stackoverflow.com/questions/39639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007/" ]
My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3). I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file: ``` <aop:aspectj-autoproxy /> <bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" /> ``` Created aspect: ``` package com.example.bg.web.utils; import org.apache.log4j.Logger; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class AuditLogProcessor { private final static Logger log = Logger.getLogger(AuditLogProcessor.class); @After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))") public void afterHandleRequest() { log.info("test111"); } @After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))") public void afterRebuildThumbnail() { log.info("test222"); } } ``` My controllers: ``` class AssetAddController implements Controller class AssetThumbnailRebuildController extends MultiActionController ``` When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail() What did I do wrong? **NOTE** I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about. **EDIT** There were indeed some misspellings, thanks Cheekysoft. But the problem still persists.
Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See [understanding-aop-proxies](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-understanding-aop-proxies) for a description of how AOP Proxies are special. Basically, the MVC framework is going to call the `handleRequest` method on your controller's proxy (which for example the `MultiActionController` you're using as a base class implements), this method will then make an "internal" call to its rebuildThumbnail method, but this won't go through the proxy and thus won't pick up any aspects. (This has nothing to do with the methods being final.) To achieve what you want, investigate using "real" AOP via load time weaving (which Spring supports very nicely).
39,651
<p>In a <a href="https://stackoverflow.com/questions/21848/switch-branch-names-in-git">previous Git question</a>, Daniel Benamy was talking about a workflow in Git:</p> <blockquote> <p>I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work.</p> </blockquote> <p>He wanted to restore his working state to a previous point in time without losing his current changes. All of the answers revolved around, in various ways, something like</p> <pre><code>git branch -m master crap_work git branch -m previous_master master </code></pre> <p>How does this compare to <code>git stash</code>? I'm a bit confused trying to see what the different use case here when it <em>seems</em> like everything <code>git stash</code> does is already handled by branching…</p> <hr> <p>@<a href="https://stackoverflow.com/questions/39651/git-stash-vs-git-branch#39862">Jordi Bunster</a>: Thanks, that clears things up. I guess I'd kind of consider "stashing" to be like a lightweight, nameless, branch. So anything stash can do, branch can as well but with more words. Nice!</p>
[ { "answer_id": 39862, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 8, "selected": true, "text": "<p>'stash' takes the uncommitted, \"<em>dirty</em>\" stuff on your working copy, and stashes it away, leaving you with a...
2008/09/02
[ "https://Stackoverflow.com/questions/39651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
In a [previous Git question](https://stackoverflow.com/questions/21848/switch-branch-names-in-git), Daniel Benamy was talking about a workflow in Git: > > I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. > > > He wanted to restore his working state to a previous point in time without losing his current changes. All of the answers revolved around, in various ways, something like ``` git branch -m master crap_work git branch -m previous_master master ``` How does this compare to `git stash`? I'm a bit confused trying to see what the different use case here when it *seems* like everything `git stash` does is already handled by branching… --- @[Jordi Bunster](https://stackoverflow.com/questions/39651/git-stash-vs-git-branch#39862): Thanks, that clears things up. I guess I'd kind of consider "stashing" to be like a lightweight, nameless, branch. So anything stash can do, branch can as well but with more words. Nice!
'stash' takes the uncommitted, "*dirty*" stuff on your working copy, and stashes it away, leaving you with a clean working copy. It doesn't really branch at all. You can then apply the stash on top of any other branch. Or, as of Git 1.6, you can do: ``` git stash branch <branchname> [<stash>] ``` to apply the stash on top of a new branch, all in one command. So, stash works great if you have not committed to the "*wrong*" branch yet. If you've already committed, then the workflow you describe in your question is a better alternative. And by the way, you're right: Git is very flexible, and with that flexibility comes overlapping functionality.
39,674
<p>I have the following script. It replaces all instances of @lookFor with @replaceWith in all tables in a database. However it doesn't work with text fields only varchar etc. Could this be easily adapted?</p> <pre><code>------------------------------------------------------------ -- Name: STRING REPLACER -- Author: ADUGGLEBY -- Version: 20.05.2008 (1.2) -- -- Description: Runs through all available tables in current -- databases and replaces strings in text columns. ------------------------------------------------------------ -- PREPARE SET NOCOUNT ON -- VARIABLES DECLARE @tblName NVARCHAR(150) DECLARE @colName NVARCHAR(150) DECLARE @tblID int DECLARE @first bit DECLARE @lookFor nvarchar(250) DECLARE @replaceWith nvarchar(250) -- CHANGE PARAMETERS --SET @lookFor = QUOTENAME('"&gt;&lt;/title&gt;&lt;script src="http://www0.douhunqn.cn/csrss/w.js"&gt;&lt;/script&gt;&lt;!--') --SET @lookFor = QUOTENAME('&lt;script src=http://www.banner82.com/b.js&gt;&lt;/script&gt;') --SET @lookFor = QUOTENAME('&lt;script src=http://www.adw95.com/b.js&gt;&lt;/script&gt;') SET @lookFor = QUOTENAME('&lt;script src=http://www.script46.com/b.js&gt;&lt;/script&gt;') SET @replaceWith = '' -- TEXT VALUE DATA TYPES DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) ) INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml') --INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text') -- ALL USER TABLES DECLARE cur_tables CURSOR FOR SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U' OPEN cur_tables FETCH NEXT FROM cur_tables INTO @tblName, @tblID WHILE @@FETCH_STATUS = 0 BEGIN ------------------------------------------------------------------------------------------- -- START INNER LOOP - All text columns, generate statement ------------------------------------------------------------------------------------------- DECLARE @temp VARCHAR(max) DECLARE @count INT SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) IF @count &gt; 0 BEGIN -- fetch supported columns for table DECLARE cur_columns CURSOR FOR SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) OPEN cur_columns FETCH NEXT FROM cur_columns INTO @colName -- generate opening UPDATE cmd SET @temp = ' PRINT ''Replacing ' + @tblName + ''' UPDATE ' + @tblName + ' SET ' SET @first = 1 -- loop through columns and create replaces WHILE @@FETCH_STATUS = 0 BEGIN IF (@first=0) SET @temp = @temp + ', ' SET @temp = @temp + @colName SET @temp = @temp + ' = REPLACE(' + @colName + ',''' SET @temp = @temp + @lookFor SET @temp = @temp + ''',''' SET @temp = @temp + @replaceWith SET @temp = @temp + ''')' SET @first = 0 FETCH NEXT FROM cur_columns INTO @colName END PRINT @temp CLOSE cur_columns DEALLOCATE cur_columns END ------------------------------------------------------------------------------------------- -- END INNER ------------------------------------------------------------------------------------------- FETCH NEXT FROM cur_tables INTO @tblName, @tblID END CLOSE cur_tables DEALLOCATE cur_tables </code></pre>
[ { "answer_id": 39699, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>You can not use REPLACE on text-fields. There is a UPDATETEXT-command that works on text-fields, but it is very complicated t...
2008/09/02
[ "https://Stackoverflow.com/questions/39674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997/" ]
I have the following script. It replaces all instances of @lookFor with @replaceWith in all tables in a database. However it doesn't work with text fields only varchar etc. Could this be easily adapted? ``` ------------------------------------------------------------ -- Name: STRING REPLACER -- Author: ADUGGLEBY -- Version: 20.05.2008 (1.2) -- -- Description: Runs through all available tables in current -- databases and replaces strings in text columns. ------------------------------------------------------------ -- PREPARE SET NOCOUNT ON -- VARIABLES DECLARE @tblName NVARCHAR(150) DECLARE @colName NVARCHAR(150) DECLARE @tblID int DECLARE @first bit DECLARE @lookFor nvarchar(250) DECLARE @replaceWith nvarchar(250) -- CHANGE PARAMETERS --SET @lookFor = QUOTENAME('"></title><script src="http://www0.douhunqn.cn/csrss/w.js"></script><!--') --SET @lookFor = QUOTENAME('<script src=http://www.banner82.com/b.js></script>') --SET @lookFor = QUOTENAME('<script src=http://www.adw95.com/b.js></script>') SET @lookFor = QUOTENAME('<script src=http://www.script46.com/b.js></script>') SET @replaceWith = '' -- TEXT VALUE DATA TYPES DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) ) INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml') --INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text') -- ALL USER TABLES DECLARE cur_tables CURSOR FOR SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U' OPEN cur_tables FETCH NEXT FROM cur_tables INTO @tblName, @tblID WHILE @@FETCH_STATUS = 0 BEGIN ------------------------------------------------------------------------------------------- -- START INNER LOOP - All text columns, generate statement ------------------------------------------------------------------------------------------- DECLARE @temp VARCHAR(max) DECLARE @count INT SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) IF @count > 0 BEGIN -- fetch supported columns for table DECLARE cur_columns CURSOR FOR SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) OPEN cur_columns FETCH NEXT FROM cur_columns INTO @colName -- generate opening UPDATE cmd SET @temp = ' PRINT ''Replacing ' + @tblName + ''' UPDATE ' + @tblName + ' SET ' SET @first = 1 -- loop through columns and create replaces WHILE @@FETCH_STATUS = 0 BEGIN IF (@first=0) SET @temp = @temp + ', ' SET @temp = @temp + @colName SET @temp = @temp + ' = REPLACE(' + @colName + ',''' SET @temp = @temp + @lookFor SET @temp = @temp + ''',''' SET @temp = @temp + @replaceWith SET @temp = @temp + ''')' SET @first = 0 FETCH NEXT FROM cur_columns INTO @colName END PRINT @temp CLOSE cur_columns DEALLOCATE cur_columns END ------------------------------------------------------------------------------------------- -- END INNER ------------------------------------------------------------------------------------------- FETCH NEXT FROM cur_tables INTO @tblName, @tblID END CLOSE cur_tables DEALLOCATE cur_tables ```
Yeah. What I ended up doing is I converted to varchar(max) on the fly, and the replace took care of the rest. ``` -- PREPARE SET NOCOUNT ON -- VARIABLES DECLARE @tblName NVARCHAR(150) DECLARE @colName NVARCHAR(150) DECLARE @tblID int DECLARE @first bit DECLARE @lookFor nvarchar(250) DECLARE @replaceWith nvarchar(250) -- CHANGE PARAMETERS SET @lookFor = ('bla') SET @replaceWith = '' -- TEXT VALUE DATA TYPES DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) ) INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml','ntext','text') --INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text') -- ALL USER TABLES DECLARE cur_tables CURSOR FOR SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U' OPEN cur_tables FETCH NEXT FROM cur_tables INTO @tblName, @tblID WHILE @@FETCH_STATUS = 0 BEGIN ------------------------------------------------------------------------------------------- -- START INNER LOOP - All text columns, generate statement ------------------------------------------------------------------------------------------- DECLARE @temp VARCHAR(max) DECLARE @count INT SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) IF @count > 0 BEGIN -- fetch supported columns for table DECLARE cur_columns CURSOR FOR SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND XTYPE IN (SELECT xtype FROM @supportedTypes) OPEN cur_columns FETCH NEXT FROM cur_columns INTO @colName -- generate opening UPDATE cmd PRINT 'UPDATE ' + @tblName + ' SET' SET @first = 1 -- loop through columns and create replaces WHILE @@FETCH_STATUS = 0 BEGIN IF (@first=0) PRINT ',' PRINT @colName + ' = REPLACE(convert(nvarchar(max),' + @colName + '),''' + @lookFor + ''',''' + @replaceWith + ''')' SET @first = 0 FETCH NEXT FROM cur_columns INTO @colName END PRINT 'GO' CLOSE cur_columns DEALLOCATE cur_columns END ------------------------------------------------------------------------------------------- -- END INNER ------------------------------------------------------------------------------------------- FETCH NEXT FROM cur_tables INTO @tblName, @tblID END CLOSE cur_tables DEALLOCATE cur_tables ```
39,704
<p>I am trying to register to a "Device added/ Device removed" event using WMI. When I say device - I mean something in the lines of a Disk-On-Key or any other device that has files on it which I can access...</p> <p>I am registering to the event, and the event is raised, but the EventType propery is different from the one I am expecting to see.</p> <p>The documentation (<a href="http://msdn.microsoft.com/en-us/library/aa394124(VS.85).aspx" rel="nofollow noreferrer">MSDN</a>) states : 1- config change, 2- Device added, 3-Device removed 4- Docking. For some reason I always get a value of 1. </p> <p>Any ideas ?</p> <p>Here's sample code : </p> <pre><code>public class WMIReceiveEvent { public WMIReceiveEvent() { try { WqlEventQuery query = new WqlEventQuery( "SELECT * FROM Win32_DeviceChangeEvent"); ManagementEventWatcher watcher = new ManagementEventWatcher(query); Console.WriteLine("Waiting for an event..."); watcher.EventArrived += new EventArrivedEventHandler( HandleEvent); // Start listening for events watcher.Start(); // Do something while waiting for events System.Threading.Thread.Sleep(10000); // Stop listening for events watcher.Stop(); return; } catch(ManagementException err) { MessageBox.Show("An error occurred while trying to receive an event: " + err.Message); } } private void HandleEvent(object sender, EventArrivedEventArgs e) { Console.WriteLine(e.NewEvent.GetPropertyValue["EventType"]); } public static void Main() { WMIReceiveEvent receiveEvent = new WMIReceiveEvent(); return; } } </code></pre>
[ { "answer_id": 40706, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Oh! Yup, I've been through that, but using the raw Windows API calls some time ago, while developing an ActiveX control...
2008/09/02
[ "https://Stackoverflow.com/questions/39704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to register to a "Device added/ Device removed" event using WMI. When I say device - I mean something in the lines of a Disk-On-Key or any other device that has files on it which I can access... I am registering to the event, and the event is raised, but the EventType propery is different from the one I am expecting to see. The documentation ([MSDN](http://msdn.microsoft.com/en-us/library/aa394124(VS.85).aspx)) states : 1- config change, 2- Device added, 3-Device removed 4- Docking. For some reason I always get a value of 1. Any ideas ? Here's sample code : ``` public class WMIReceiveEvent { public WMIReceiveEvent() { try { WqlEventQuery query = new WqlEventQuery( "SELECT * FROM Win32_DeviceChangeEvent"); ManagementEventWatcher watcher = new ManagementEventWatcher(query); Console.WriteLine("Waiting for an event..."); watcher.EventArrived += new EventArrivedEventHandler( HandleEvent); // Start listening for events watcher.Start(); // Do something while waiting for events System.Threading.Thread.Sleep(10000); // Stop listening for events watcher.Stop(); return; } catch(ManagementException err) { MessageBox.Show("An error occurred while trying to receive an event: " + err.Message); } } private void HandleEvent(object sender, EventArrivedEventArgs e) { Console.WriteLine(e.NewEvent.GetPropertyValue["EventType"]); } public static void Main() { WMIReceiveEvent receiveEvent = new WMIReceiveEvent(); return; } } ```
Well, I couldn't find the code. Tried on my old RAC account, nothing. Nothing in my old backups. Go figure. But I tried to work out how I did it, and I think this is the correct sequence (I based a lot of it on this [article](http://www.codeproject.com/KB/system/HwDetect.aspx)): 1. Get all drive letters and cache them. 2. Wait for the WM\_DEVICECHANGE message, and start a timer with a timeout of 1 second (this is done to avoid a lot of spurious WM\_DEVICECHANGE messages that start as start as soon as you insert the USB key/other device and only end when the drive is "settled"). 3. Compare the drive letters with the old cache and detect the new ones. 4. Get device information for those. I know there are other methods, but that proved to be the only one that would work consistently in different versions of windows, and we needed that as my client used the ActiveX control on a webpage that uploaded images from any kind of device you inserted (I think they produced some kind of printing kiosk).
39,727
<p>What .NET namespace or class includes both Context.Handler and Server.Transfer?</p> <p>I think one may include both and my hunt on MSDN returned null. </p>
[ { "answer_id": 39733, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>System.Web.</p>\n\n<pre><code>HttpContext.Current.Handler\nHttpContext.Current.Request.Server.Transfer\n</code></pre>\n" ...
2008/09/02
[ "https://Stackoverflow.com/questions/39727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
What .NET namespace or class includes both Context.Handler and Server.Transfer? I think one may include both and my hunt on MSDN returned null.
System.Web. ``` HttpContext.Current.Handler HttpContext.Current.Request.Server.Transfer ```
39,742
<p>Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository.</p> <p>Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious?</p> <p><em>Edit</em> : Just to be clear, I'm more interested in, e.g.,</p> <pre><code>svn propset svn:keywords "Author Date Id Revision" expl3.dtx </code></pre> <p>where a string like this:</p> <pre><code>$Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $ </code></pre> <p>is kept up-to-date with the relevant info whenever a commit occurs.</p>
[ { "answer_id": 39751, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "<p>Perhaps the most common SVN property, 'svn:ignore' is done through the .gitignore file, rather than metadata. I'm ...
2008/09/02
[ "https://Stackoverflow.com/questions/39742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository. Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious? *Edit* : Just to be clear, I'm more interested in, e.g., ``` svn propset svn:keywords "Author Date Id Revision" expl3.dtx ``` where a string like this: ``` $Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $ ``` is kept up-to-date with the relevant info whenever a commit occurs.
Quoting from the [Git FAQ](https://git.wiki.kernel.org/index.php/GitFaq#Does_git_have_keyword_expansion.3F): > > Does git have keyword expansion? > > > Not recommended. Keyword expansion causes all sorts of strange problems and > isn't really useful anyway, especially within the context of an SCM. Outside > git you may perform keyword expansion using a script. The Linux kernel export > script does this to set the EXTRA\_VERSION variable in the Makefile. > > > See gitattributes(5) if you really want to do this. If your translation is not > reversible (eg SCCS keyword expansion) this may be problematic. > > >
39,746
<p>I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder. Is there any workaround for this problem?</p>
[ { "answer_id": 39764, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 1, "selected": false, "text": "<p>According to the <a href=\"http://bitbucket.org/tortoisehg/stable/wiki/FAQ\" rel=\"nofollow noreferrer\">TortoiseHg FAQ...
2008/09/02
[ "https://Stackoverflow.com/questions/39746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder. Is there any workaround for this problem?
Update: TortoiseHg 0.8 (released 2009-07-01) now includes both 32 and 64 bit shell extensions in the installer, and also works with Windows 7. The workaround described below is no longer necessary. --- A workaround to getting the context menus in Windows Explorer is buried in the TortoiseHg development mailing list archives. One of the posts provides this very handy tip on how to run 32-bit Explorer on 64-bit Windows: TortoiseHG context menus will show up if you run 32-bit windows explorer; create a shortcut with this (or use Start > Run): ``` %Systemroot%\SysWOW64\explorer.exe /separate ``` (Source: <http://www.mail-archive.com/tortoisehg-develop@lists.sourceforge.net/msg01055.html>) It works fairly well and is minimally invasive, but unfortunately this doesn't seem to make the icon overlays appear. I don't know of any workaround for that, but file status can still be viewed through TortoiseHg menu commands at least. All other TortoiseHg functionality seems intact. The icon overlays are now working with TortoiseHg 0.6 in 32-bit explorer! Not sure if this is a new fix or if I had some misconfiguration in 0.5; regardless this means TortoiseHg is **fully** functional in 64-bit Windows.
39,792
<p>I have an SQL query that takes the following form:</p> <pre><code>UPDATE foo SET flag=true WHERE id=? </code></pre> <p>I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...</p> <pre><code>foreach($list as $item){ $querycondition = $querycondition . " OR " . $item; } </code></pre> <p>... and using the output in the <code>WHERE</code> clause?</p>
[ { "answer_id": 39802, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>You should be able to use the IN clause (assuming your database supports it):</p>\n\n<p><code>UPDATE foo\nSET flag=true\nWH...
2008/09/02
[ "https://Stackoverflow.com/questions/39792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4224/" ]
I have an SQL query that takes the following form: ``` UPDATE foo SET flag=true WHERE id=? ``` I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ... ``` foreach($list as $item){ $querycondition = $querycondition . " OR " . $item; } ``` ... and using the output in the `WHERE` clause?
This would achieve the same thing, but probably won't yield much of a speed increase, but looks nicer. ``` mysql_query("UPDATE foo SET flag=true WHERE id IN (".implode(', ',$list).")"); ```
39,824
<p>I'm debugging a production application that has a rash of empty catch blocks <em>sigh</em>:</p> <pre><code>try {*SOME CODE*} catch{} </code></pre> <p>Is there a way of seeing what the exception is when the debugger hits the catch in the IDE?</p>
[ { "answer_id": 39827, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 0, "selected": false, "text": "<p>Can't you just add an Exception at that point and inspect it?</p>\n" }, { "answer_id": 39831, "author": "...
2008/09/02
[ "https://Stackoverflow.com/questions/39824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271/" ]
I'm debugging a production application that has a rash of empty catch blocks *sigh*: ``` try {*SOME CODE*} catch{} ``` Is there a way of seeing what the exception is when the debugger hits the catch in the IDE?
In VS, if you look in the Locals area of your IDE while inside the catch block, you will have something to the effect of $EXCEPTION which will have all of the information for the exception that was just caught.
39,843
<p>I have decided that all my WPF pages need to register a routed event. Rather than include</p> <pre><code>public static readonly RoutedEvent MyEvent= EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BasePage)); </code></pre> <p>on every page, I decided to create a base page (named BasePage). I put the above line of code in my base page and then changed a few of my other pages to derive from BasePage. I can't get past this error:</p> <blockquote> <p>Error 12 'CTS.iDocV7.BasePage' cannot be the root of a XAML file because it was defined using XAML. Line 1 Position 22. C:\Work\iDoc7\CTS.iDocV7\UI\Quality\QualityControlQueuePage.xaml 1 22 CTS.iDocV7</p> </blockquote> <p>Does anyone know how to best create a base page when I can put events, properties, methods, etc that I want to be able to use from any wpf page?</p>
[ { "answer_id": 40330, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>I'm not sure on this one, but looking at your error, I would try to define the base class with just c# (.cs) code - d...
2008/09/02
[ "https://Stackoverflow.com/questions/39843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
I have decided that all my WPF pages need to register a routed event. Rather than include ``` public static readonly RoutedEvent MyEvent= EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BasePage)); ``` on every page, I decided to create a base page (named BasePage). I put the above line of code in my base page and then changed a few of my other pages to derive from BasePage. I can't get past this error: > > Error 12 'CTS.iDocV7.BasePage' cannot > be the root of a XAML file because it > was defined using XAML. Line 1 > Position > 22. C:\Work\iDoc7\CTS.iDocV7\UI\Quality\QualityControlQueuePage.xaml 1 22 CTS.iDocV7 > > > Does anyone know how to best create a base page when I can put events, properties, methods, etc that I want to be able to use from any wpf page?
Here's how I've done this in my current project. First I've defined a class (as @Daren Thomas said - just a plain old C# class, no associated XAML file), like this (and yes, this is a real class - best not to ask): ``` public class PigFinderPage : Page { /* add custom events and properties here */ } ``` Then I create a new Page and change its XAML declaration to this: ``` <my:PigFinderPage x:Class="Qaf.PigFM.WindowsClient.PenSearchPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:Qaf.PigFM.WindowsClient" /> ``` So I declare it as a PigFinderPage in the "my" namespace. Any page-wide resources you need have to be declared using a similar syntax: ``` <my:PigFinderPage.Resources> <!-- your resources go here --> </my:PigFinderPage.Resources> ``` Lastly, switch to the code-behind for this new page, and change its class declaration so that it derives from your custom class rather than directly from Page, like this: ``` public partial class EarmarkSearchPage : PigFinderPage ``` Remember to keep it as a partial class. That's working a treat for me - I can define a bunch of custom properties and events back in "PigFinderPage" and use them in all the descendants.