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
|
---|---|---|---|---|---|---|
182,622 |
<p>I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)</p>
<p>My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usage (pointers?).</p>
<p>What I am interested in is what is the best method to debug these situations?<br>
How do you debug a program that has already closed?<br>
I am looking for a starting point to break down a larger problem.</p>
<p>These errors seem to present themselves in several ways (some run time, some debug):</p>
<pre>
1: .NET-BroadcastEventWindow.2.0.0.0.378734a.0: Application.exe - Application Error<BR>
The instruction at "0x03b4eddb" referenced memory at "0x00000004". The memory could not be "written".
2: Application.vshost.exe - Application Error<br>
The instruction at "0x0450eddb" referenced memory at "0x00000004". The memory could not be "written".
3: Application.vshost.exe - Application Error<br>
The instruction at "0x7c911669" referenced memory at "0x00000000". The memory could not be "read".
4: Application.vshost.exe - Application Error<br>
The instruction at "0x7c910ed4" referenced memory at "0xfffffff8". The memory could not be "read".
</pre>
|
[
{
"answer_id": 182704,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 1,
"selected": false,
"text": "<p>I've seen plently of errors just like this recently. My issues were releated to how the CRT (C Runtime) intereacting with the .NET runtime cleans up a closing process. My application is complicated by the fact it is C++, but allows COM add-ins to to loaded, some which are written in C#.</p>\n\n<p>To debug this, I think you're going to need to use native debugging. Visual Studio (set to mixed mode debugging) or WinDbg. Look up how to use the Microsoft public symbol server to download PDBs for windows components - you'll <strong><em>need</em></strong> those symbols.</p>\n\n<p>Many of our problems were with .NET's (awful) COM client support. I say awful since it doesn't reference count correctly (without a lot of work on the developer's end). COM objects were not being referenced-counted down to zero until garbage collect was done. This often setup odd timing issues during shutdown - COM objects being cleaned up long after they should have been.</p>\n"
},
{
"answer_id": 182878,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 3,
"selected": true,
"text": "<p>If your app is multi-threaded you could be getting errors from worker threads which aren't properly terminating and trying to access disposed objects.</p>\n"
},
{
"answer_id": 184285,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>A fancier word for \"inconsistent\" is \"non-deterministic.\" And what happens non-deterministically in the .NET environment? Object destruction.</p>\n\n<p>When this happened to me, the culprit was in the class that I wrote to wrap unsafe calls to an external API. I put cleanup code in the class's destructor, expecting the code to be called when the object went out of scope. But that's not how object destruction works in .NET, When an object goes out of scope, it gets put in the finalizer's queue, and its destructor doesn't get called until the finalizer gets around to it. It may not do this until after the program terminates. If this happens, the result will look a lot like what you're describing here.</p>\n\n<p>Once I made my class implement <code>IDisposable</code>, and explicitly called <code>Dispose()</code> on the object when I was done with it, the problem went away. (Another advantage of implementing IDisposable is that you can instantiate your object at the start of a <code>using</code> block and be confident that Dispose() will get when the code leaves the block.)</p>\n"
},
{
"answer_id": 315312,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "<p>try this to force the bug to happen while under program control</p>\n\n<pre><code> //set as many statics as you can to null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n} //exit main\n</code></pre>\n"
},
{
"answer_id": 2835201,
"author": "Mark Paint",
"author_id": 341356,
"author_profile": "https://Stackoverflow.com/users/341356",
"pm_score": 0,
"selected": false,
"text": "<p>The error stopped appearing after using the suggested code:</p>\n\n<pre><code>GC.Collect(); \nGC.WaitForPendingFinalizers(); \n</code></pre>\n"
},
{
"answer_id": 3438858,
"author": "Miroslav Zadravec",
"author_id": 8239,
"author_profile": "https://Stackoverflow.com/users/8239",
"pm_score": 3,
"selected": false,
"text": "<p>I had this problem using AcrobarReader COM component. Every now and then after application exit I had \"Application.vshost.exe - Application Error\" \"memory could not be read\". GC.Collect() and WaitForPendingFinalizers() didn't help.</p>\n\n<p>My google-fu lead me to this page: <a href=\"http://support.microsoft.com/kb/826220\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/826220</a>. I modified method 3 for my case.</p>\n\n<p>Using process explorer I found that AcroPDF.dll is not released before the last line in the Main function. So, here come the API calls.</p>\n\n<p>DLLImports (DLLImport is in System.Runtime.InteropServices namespace):</p>\n\n<pre><code><DllImport(\"kernel32.dll\", EntryPoint:=\"GetModuleHandle\", _\n SetLastError:=True, CharSet:=CharSet.Auto, _\n CallingConvention:=CallingConvention.StdCall)> _\nPublic Overloads Shared Function GetModuleHandle(ByVal sLibName As String) As IntPtr\nEnd Function\n\n<DllImport(\"kernel32.dll\", EntryPoint:=\"FreeLibrary\", _\n SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _\nPublic Overloads Shared Function FreeLibrary(ByVal hMod As IntPtr) As Integer\nEnd Function\n</code></pre>\n\n<p>And then before application exit:</p>\n\n<pre><code>Dim hOwcHandle As IntPtr = GetModuleHandle(\"AcroPDF.dll\")\nIf Not hOwcHandle.Equals(IntPtr.Zero) Then\n FreeLibrary(hOwcHandle)\n Debug.WriteLine(\"AcroPDF.dll freed\")\nEnd If\n</code></pre>\n\n<p>This procedure can be modified for any other ill-behaved dll. I just hope it doesn't introduce any new bugs.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6721/"
] |
I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)
My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usage (pointers?).
What I am interested in is what is the best method to debug these situations?
How do you debug a program that has already closed?
I am looking for a starting point to break down a larger problem.
These errors seem to present themselves in several ways (some run time, some debug):
```
1: .NET-BroadcastEventWindow.2.0.0.0.378734a.0: Application.exe - Application Error
The instruction at "0x03b4eddb" referenced memory at "0x00000004". The memory could not be "written".
2: Application.vshost.exe - Application Error
The instruction at "0x0450eddb" referenced memory at "0x00000004". The memory could not be "written".
3: Application.vshost.exe - Application Error
The instruction at "0x7c911669" referenced memory at "0x00000000". The memory could not be "read".
4: Application.vshost.exe - Application Error
The instruction at "0x7c910ed4" referenced memory at "0xfffffff8". The memory could not be "read".
```
|
If your app is multi-threaded you could be getting errors from worker threads which aren't properly terminating and trying to access disposed objects.
|
182,630 |
<h2>Syntax</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218129#2218129">Shorthand for the ready-event</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218135#2218135">Line breaks and chainability</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389474#389474">Nesting filters</a> by Nathan Long</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/552831#552831">Cache a collection and execute commands on the same line</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1519474#1519474">Contains selector</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Defining properties at element creation</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/3967325#3967325">Access jQuery functions as you would an array</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182666#182666">The noConflict function - Freeing up the $ variable</a> by Oli</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382853#382853">Isolate the $ variable in noConflict mode</a> by nickf</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218120#2218120">No-conflict mode</a> by roosteronacid</li>
</ul>
<h2>Data Storage</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382834#382834">The data function - bind data to elements</a> by TenebrousX</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/5410587#5410587">HTML5 data attributes support, on steroids!</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504776#504776">The jQuery metadata plug-in</a> by Filip Dupanović</li>
</ul>
<h2>Optimization</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1019899#1019899">Optimize performance of complex selectors</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504732#504732">The context parameter</a> by lupefiasco</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389793#389793">Save and reuse searches</a> by Nathan Long</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382922#382922">Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors</a> by Andreas Grech</li>
</ul>
<h2>Miscellaneous</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389906#389906">Check the index of an element in a collection</a> by redsquare</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/892617#892617">Live event handlers</a> by TM</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385">Replace anonymous functions with named functions</a> by ken</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191139#191139">Microsoft AJAX framework and jQuery bridge</a> by Slace</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/922865#922865">jQuery tutorials</a> by egyamado</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/998547#998547">Remove elements from a collection and preserve chainability</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191061#191061">Declare $this at the beginning of anonymous functions</a> by Ben</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1771311#1771311">FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN</a> by Colour Blend</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182715#182715">Judicious use of third-party jQuery scripts</a> by harriyott</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1584927#1584927">The each function</a> by Jan Zich</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1235178#1235178">Form Extensions plug-in</a> by Chris S</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Asynchronous each function</a> by OneNerd</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/4962433#4962433">The jQuery template plug-in: implementing complex logic using render-functions</a> by roosteronacid</li>
</ul>
|
[
{
"answer_id": 182666,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 6,
"selected": false,
"text": "<p>I'm really not a fan of the <code>$(document).ready(fn)</code> shortcut. Sure it cuts down on the code but it also cuts way down on the readability of the code. When you see <code>$(document).ready(...)</code>, you know what you're looking at. <code>$(...)</code> is used in far too many other ways to immediately make sense.</p>\n\n<p>If you have multiple frameworks you can use <code>jQuery.noConflict();</code> as you say, but you can also assign a different variable for it like this:</p>\n\n<pre><code>var $j = jQuery.noConflict();\n\n$j(\"#myDiv\").hide();\n</code></pre>\n\n<p>Very useful if you have several frameworks that can be boiled down to <code>$x(...)</code>-style calls.</p>\n"
},
{
"answer_id": 182715,
"author": "harriyott",
"author_id": 5744,
"author_profile": "https://Stackoverflow.com/users/5744",
"pm_score": 3,
"selected": false,
"text": "<p>Judicious use of third-party jQuery scripts, such as form field validation or url parsing. It's worth seeing what's about so you'll know when you next encounter a JavaScript requirement.</p>\n"
},
{
"answer_id": 191061,
"author": "Ben Crouse",
"author_id": 6705,
"author_profile": "https://Stackoverflow.com/users/6705",
"pm_score": 4,
"selected": false,
"text": "<p>I like declare a <code>$this</code> variable at the beginning of anonymous functions, so I know I can reference a jQueried this.</p>\n\n<p>Like so:</p>\n\n<pre><code>$('a').each(function() {\n var $this = $(this);\n\n // Other code\n});\n</code></pre>\n"
},
{
"answer_id": 191139,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "<p>Not really jQuery only but I made a nice little bridge for jQuery and MS AJAX:</p>\n\n<pre><code>Sys.UI.Control.prototype.j = function Sys$UI$Control$j(){\n return $('#' + this.get_id());\n}\n</code></pre>\n\n<p>It's really nice if you're doing lots of ASP.NET AJAX, since jQuery is supported by MS now having a nice bridge means it's really easy to do jQuery operations:</p>\n\n<pre><code>$get('#myControl').j().hide();\n</code></pre>\n\n<p>So the above example isn't great, but if you're writing ASP.NET AJAX server controls, makes it easy to have jQuery inside your client-side control implementation.</p>\n"
},
{
"answer_id": 382834,
"author": "clawr",
"author_id": 46201,
"author_profile": "https://Stackoverflow.com/users/46201",
"pm_score": 7,
"selected": false,
"text": "<p>jQuery's <a href=\"http://docs.jquery.com/Core/data\" rel=\"nofollow noreferrer\"><code>data()</code></a> method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.</p>\n"
},
{
"answer_id": 382853,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "<p>instead of using a different alias for the jQuery object (when using noConflict), I always write my jQuery code by wrapping it all in a closure. This can be done in the document.ready function:</p>\n\n<pre><code>var $ = someOtherFunction(); // from a different library\n\njQuery(function($) {\n if ($ instanceOf jQuery) {\n alert(\"$ is the jQuery object!\");\n }\n});\n</code></pre>\n\n<p>alternatively you can do it like this:</p>\n\n<pre><code>(function($) {\n $('...').etc() // whatever jQuery code you want\n})(jQuery);\n</code></pre>\n\n<p>I find this to be the most portable. I've been working on a site which uses both Prototype AND jQuery simultaneously and these techniques have avoided all conflicts.</p>\n"
},
{
"answer_id": 382922,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Creating an HTML Element and keeping a reference</strong></p>\n\n<pre><code>var newDiv = $(\"<div />\");\n\nnewDiv.attr(\"id\", \"myNewDiv\").appendTo(\"body\");\n\n/* Now whenever I want to append the new div I created, \n I can just reference it from the \"newDiv\" variable */\n</code></pre>\n\n<p><br />\n<strong>Checking if an element exists</strong></p>\n\n<pre><code>if ($(\"#someDiv\").length)\n{\n // It exists...\n}\n</code></pre>\n\n<p><br />\n<strong>Writing your own selectors</strong></p>\n\n<pre><code>$.extend($.expr[\":\"], {\n over100pixels: function (e)\n {\n return $(e).height() > 100;\n }\n});\n\n$(\".box:over100pixels\").click(function ()\n{\n alert(\"The element you clicked is over 100 pixels height\");\n});\n</code></pre>\n"
},
{
"answer_id": 389474,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 7,
"selected": false,
"text": "<h2>Nesting Filters</h2>\n<p>You can nest filters (as <a href=\"https://stackoverflow.com/questions/382301/jquery-accordion-close-then-open#382828\">nickf showed here</a>).</p>\n<pre><code>.filter(":not(:has(.selected))")\n</code></pre>\n"
},
{
"answer_id": 389793,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 4,
"selected": false,
"text": "<h2>Save jQuery Objects in Variables for Reuse</h2>\n<p>Saving a jQuery object to a variable lets you reuse it without having to search back through the DOM to find it.</p>\n<p>(As @Louis suggested, I now use $ to indicate that a variable holds a jQuery object.)</p>\n<pre><code>// Bad: searching the DOM multiple times for the same elements\n$('div.foo').each...\n$('div.foo').each...\n\n// Better: saving that search for re-use\nvar $foos = $('div.foo');\n$foos.each...\n$foos.each...\n</code></pre>\n<p>As a more complex example, say you've got a list of foods in a store, and you want to show only the ones that match a user's criteria. You have a form with checkboxes, each one containing a criteria. The checkboxes have names like <code>organic</code> and <code>lowfat</code>, and the products have corresponding classes - <code>.organic</code>, etc.</p>\n<pre><code>var $allFoods, $matchingFoods;\n$allFoods = $('div.food');\n</code></pre>\n<p>Now you can keep working with that jQuery object. Every time a checkbox is clicked (to check or uncheck), start from the master list of foods and filter down based on the checked boxes:</p>\n<pre><code>// Whenever a checkbox in the form is clicked (to check or uncheck)...\n$someForm.find('input:checkbox').click(function(){\n\n // Start out assuming all foods should be showing\n // (in case a checkbox was just unchecked)\n var $matchingFoods = $allFoods;\n\n // Go through all the checked boxes and keep only the foods with\n // a matching class \n this.closest('form').find("input:checked").each(function() { \n $matchingFoods = $matchingFoods.filter("." + $(this).attr("name")); \n });\n\n // Hide any foods that don't match the criteria\n $allFoods.not($matchingFoods).hide();\n});\n</code></pre>\n"
},
{
"answer_id": 389906,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 5,
"selected": false,
"text": "<h2><strong>Check the Index</strong></h2>\n\n<p>jQuery has .index but it is a pain to use, as you need the list of elements, and pass in the element you want the index of:</p>\n\n<pre><code>var index = e.g $('#ul>li').index( liDomObject );\n</code></pre>\n\n<p>The following is much easier:</p>\n\n<p>If you want to know the index of an element within a set (e.g. list items) within a unordered list:</p>\n\n<pre><code>$(\"ul > li\").click(function () {\n var index = $(this).prevAll().length;\n});\n</code></pre>\n"
},
{
"answer_id": 504732,
"author": "mshafrir",
"author_id": 5675,
"author_profile": "https://Stackoverflow.com/users/5675",
"pm_score": 5,
"selected": false,
"text": "<p>On the core jQuery function, specify the context parameter in addition to the selector parameter. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.</p>\n\n<p>Example: Finds all inputs of type radio within the first form in the document.</p>\n\n<pre><code>$(\"input:radio\", document.forms[0]);\n</code></pre>\n\n<p>Reference: <a href=\"http://docs.jquery.com/Core/jQuery#expressioncontext\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Core/jQuery#expressioncontext</a></p>\n"
},
{
"answer_id": 504776,
"author": "Filip Dupanović",
"author_id": 44041,
"author_profile": "https://Stackoverflow.com/users/44041",
"pm_score": 6,
"selected": false,
"text": "<p>Ooooh, let's not forget <a href=\"http://docs.jquery.com/Plugins/Metadata\" rel=\"nofollow noreferrer\">jQuery metadata</a>! The data() function is great, but it has to be populated via jQuery calls.</p>\n\n<p>Instead of breaking W3C compliance with custom element attributes such as:</p>\n\n<pre><code><input \n name=\"email\" \n validation=\"required\" \n validate=\"email\" \n minLength=\"7\" \n maxLength=\"30\"/> \n</code></pre>\n\n<p>Use metadata instead:</p>\n\n<pre><code><input \n name=\"email\" \n class=\"validation {validate: email, minLength: 2, maxLength: 50}\" />\n\n<script>\n jQuery('*[class=validation]').each(function () {\n var metadata = $(this).metadata();\n // etc.\n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 552831,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": false,
"text": "<p>Syntactic shorthand-sugar-thing--Cache an object collection and execute commands on one line:</p>\n\n<p><strong>Instead of:</strong></p>\n\n<pre><code>var jQueryCollection = $(\"\");\n\njQueryCollection.command().command();\n</code></pre>\n\n<p><strong>I do:</strong></p>\n\n<pre><code>var jQueryCollection = $(\"\").command().command();\n</code></pre>\n\n<p>A somewhat \"real\" use case could be something along these lines:</p>\n\n<pre><code>var cache = $(\"#container div.usehovereffect\").mouseover(function ()\n{\n cache.removeClass(\"hover\").filter(this).addClass(\"hover\");\n});\n</code></pre>\n"
},
{
"answer_id": 696385,
"author": "ken",
"author_id": 84473,
"author_profile": "https://Stackoverflow.com/users/84473",
"pm_score": 6,
"selected": false,
"text": "<p>Replace anonymous functions with named functions. This really supercedes the jQuery context, but it comes into play more it seems like when using jQuery, due to its reliance on callback functions. The problems I have with inline anonymous functions, are that they are harder to debug (much easier to look at a callstack with distinctly-named functions, instead 6 levels of \"anonymous\"), and also the fact that multiple anonymous functions within the same jQuery-chain can become unwieldy to read and/or maintain. Additionally, anonymous functions are typically not re-used; on the other hand, declaring named functions encourages me to write code that is more likely to be re-used.</p>\n\n<p>An illustration; instead of:</p>\n\n<pre><code>$('div').toggle(\n function(){\n // do something\n },\n function(){\n // do something else\n }\n);\n</code></pre>\n\n<p>I prefer:</p>\n\n<pre><code>function onState(){\n // do something\n}\n\nfunction offState(){\n // do something else\n}\n\n$('div').toggle( offState, onState );\n</code></pre>\n"
},
{
"answer_id": 892617,
"author": "TM.",
"author_id": 12983,
"author_profile": "https://Stackoverflow.com/users/12983",
"pm_score": 6,
"selected": false,
"text": "<h2>Live Event Handlers</h2>\n\n<p>Set an event handler for <strong>any</strong> element that matches a selector, even if it gets added to the DOM after the initial page load:</p>\n\n<pre><code>$('button.someClass').live('click', someFunction);\n</code></pre>\n\n<p>This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.</p>\n\n<p>Likewise, to stop the live event handling:</p>\n\n<pre><code>$('button.someClass').die('click', someFunction);\n</code></pre>\n\n<p>These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases.</p>\n\n<p>For more info see the <a href=\"http://docs.jquery.com/Events/live\" rel=\"noreferrer\">jQuery Documentation</a>.</p>\n\n<p><strong>UPDATE: <code>live()</code> and <code>die()</code> are deprecated in jQuery 1.7. See <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\">http://api.jquery.com/on/</a> and <a href=\"http://api.jquery.com/off/\" rel=\"noreferrer\">http://api.jquery.com/off/</a> for similar replacement functionality.</strong></p>\n\n<p><strong>UPDATE2: <code>live()</code> has been long deprecated, even before jQuery 1.7. For versions jQuery 1.4.2+ before 1.7 use <a href=\"http://api.jquery.com/delegate/\" rel=\"noreferrer\"><code>delegate()</code></a> and <code>undelegate()</code>.</strong> The <code>live()</code> example (<code>$('button.someClass').live('click', someFunction);</code>) can be rewritten using <code>delegate()</code> like that: <code>$(document).delegate('button.someClass', 'click', someFunction);</code>.</p>\n"
},
{
"answer_id": 922865,
"author": "egyamado",
"author_id": 66493,
"author_profile": "https://Stackoverflow.com/users/66493",
"pm_score": 4,
"selected": false,
"text": "<p>Speaking of Tips and Tricks and as well some tutorials. I found these series of tutorials (<strong>“jQuery for Absolute Beginners” Video Series)</strong> by <a href=\"http://jeffrey-way.com/\" rel=\"nofollow noreferrer\">Jeffery Way</a> are VERY HELPFUL. </p>\n\n<p>It targets those developers who are new to jQuery. He shows how to create many cool stuff with jQuery, like animation, Creating and Removing Elements and more...</p>\n\n<p>I learned a lot from it. He shows how it's easy to use jQuery.\nNow I love it and i can read and understand any jQuery script even if it's complex.</p>\n\n<p>Here is one example I like \"<strong>Resizing Text</strong>\"</p>\n\n<p><strong>1- jQuery...</strong></p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\n $(function() {\n $('a').click(function() {\n var originalSize = $('p').css('font-size'); // get the font size \n var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable \"originalSize\"\n var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch\n\n $('p').css('font-size', number / 1.2 + unitOfMeasure);\n if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered\n }); \n });\n</script>\n</code></pre>\n\n<p><strong>2- CSS Styling...</strong> </p>\n\n<pre><code><style type=\"text/css\" >\nbody{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}\n.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}\n</style>\n</code></pre>\n\n<p><strong>2- HTML...</strong> </p>\n\n<pre><code><div class=\"box\">\n <a href=\"#\" id=\"larger\">Larger</a> | \n <a href=\"#\" id=\"Smaller\">Smaller</a>\n <p>\n In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods. \n </p>\n</div>\n</code></pre>\n\n<p>Highly recommend these tutorials... </p>\n\n<p><a href=\"http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/\" rel=\"nofollow noreferrer\">http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/</a></p>\n"
},
{
"answer_id": 998547,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Remove elements from a collection and preserve chainability</strong></p>\n\n<p>Consider the following:</p>\n\n<pre><code><ul>\n <li>One</li>\n <li>Two</li>\n <li>Three</li>\n <li>Four</li>\n <li>Five</li>\n</ul>\n</code></pre>\n\n<p><br /></p>\n\n<pre><code>$(\"li\").filter(function()\n{\n var text = $(this).text();\n\n // return true: keep current element in the collection\n if (text === \"One\" || text === \"Two\") return true;\n\n // return false: remove current element from the collection\n return false;\n}).each(function ()\n{\n // this will alert: \"One\" and \"Two\" \n alert($(this).text());\n});\n</code></pre>\n\n<p>The <code>filter()</code> function removes elements from the jQuery object. In this case: All li-elements not containing the text \"One\" or \"Two\" will be removed.</p>\n"
},
{
"answer_id": 1019899,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Optimize performance of complex selectors</strong></p>\n\n<p>Query a subset of the DOM when using complex selectors drastically improves performance:</p>\n\n<pre><code>var subset = $(\"\");\n\n$(\"input[value^='']\", subset);\n</code></pre>\n"
},
{
"answer_id": 1235178,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "<p><em>(This is a shamless plug)</em></p>\n\n<p>Instead of writing repetitive form handling code, you can try out <a href=\"http://code.google.com/p/jquery-form-extensions/\" rel=\"nofollow noreferrer\">this plugin</a> I wrote that adds to the fluent API of jQuery by adding form related methods:</p>\n\n<pre><code>// elementExists is also added\nif ($(\"#someid\").elementExists())\n alert(\"found it\");\n\n// Select box related\n$(\"#mydropdown\").isDropDownList();\n\n// Can be any of the items from a list of radio boxes - it will use the name\n$(\"#randomradioboxitem\").isRadioBox(\"myvalue\");\n$(\"#radioboxitem\").isSelected(\"myvalue\");\n\n// The value of the item selected. For multiple selects it's the first value\n$(\"#radioboxitem\").selectedValue();\n\n// Various, others include password, hidden. Buttons also\n$(\"#mytextbox\").isTextBox();\n$(\"#mycheck\").isCheckBox();\n$(\"#multi-select\").isSelected(\"one\", \"two\", \"three\");\n\n// Returns the 'type' property or 'select-one' 'select-multiple'\nvar fieldType = $(\"#someid\").formElementType();\n</code></pre>\n"
},
{
"answer_id": 1519474,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": false,
"text": "<p>This one goes out to <a href=\"https://stackoverflow.com/users/7586/kobi\">Kobi</a>.</p>\n\n<p>Consider the following snippet of code:</p>\n\n<pre><code>// hide all elements which contains the text \"abc\"\n$(\"p\").each(function ()\n{\n var that = $(this);\n\n if (that.text().indexOf(\"abc\") > -1) that.hide();\n}); \n</code></pre>\n\n<p>Here's a shorthand... which is about twice as fast:</p>\n\n<pre><code>$(\"p.value:contains('abc')\").hide();\n</code></pre>\n"
},
{
"answer_id": 1584927,
"author": "Jan Zich",
"author_id": 15716,
"author_profile": "https://Stackoverflow.com/users/15716",
"pm_score": 4,
"selected": false,
"text": "<p>It seems that most of the interesting and important tips have been already mentioned, so this one is just a little addition.</p>\n\n<p>The little tip is the <a href=\"http://docs.jquery.com/Utilities/jQuery.each\" rel=\"nofollow noreferrer\">jQuery.each(object, callback)</a> function. Everybody is probably using the <a href=\"http://docs.jquery.com/Core/each\" rel=\"nofollow noreferrer\">jQuery.each(callback)</a> function to iterate over the jQuery object itself because it is natural. The jQuery.each(object, callback) utility function iterates over objects and arrays. For a long time, I somehow did not see what it could be for apart from a different syntax (I don’t mind writing all fashioned loops), and I’m a bit ashamed that I realized its main strength only recently.</p>\n\n<p>The thing is that since the <strong>body of the loop in jQuery.each(object, callback) is a function</strong>, you get a <strong>new scope</strong> every time in the loop which is especially convenient when you create <strong>closures</strong> in the loop.</p>\n\n<p>In other words, a typical common mistake is to do something like:</p>\n\n<pre><code>var functions = [];\nvar someArray = [1, 2, 3];\nfor (var i = 0; i < someArray.length; i++) {\n functions.push(function() { alert(someArray[i]) });\n}\n</code></pre>\n\n<p>Now, when you invoke the functions in the <code>functions</code> array, you will get three times alert with the content <code>undefined</code> which is most likely not what you wanted. The problem is that there is just one variable <code>i</code>, and all three closures refer to it. When the loop finishes, the final value of <code>i</code> is 3, and <code>someArrary[3]</code> is <code>undefined</code>. You could work around it by calling another function which would create the closure for you. Or you use the jQuery utility which it will basically do it for you:</p>\n\n<pre><code>var functions = [];\nvar someArray = [1, 2, 3];\n$.each(someArray, function(item) {\n functions.push(function() { alert(item) });\n});\n</code></pre>\n\n<p>Now, when you invoke the functions you get three alerts with the content 1, 2 and 3 as expected.</p>\n\n<p>In general, it is nothing you could not do yourself, but it’s nice to have.</p>\n"
},
{
"answer_id": 1771311,
"author": "Orson",
"author_id": 207756,
"author_profile": "https://Stackoverflow.com/users/207756",
"pm_score": 3,
"selected": false,
"text": "<p>Update:</p>\n\n<p>Just include this script on the site and you’ll get a Firebug console that pops up for debugging in any browser. Not quite as full featured but it’s still pretty helpful! Remember to remove it when you are done.</p>\n\n<pre><code><script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>\n</code></pre>\n\n<p>Check out this link:</p>\n\n<p><a href=\"http://css-tricks.com/snippets/html/use-firebug-in-any-browser/\" rel=\"nofollow noreferrer\">From CSS Tricks</a></p>\n\n<p>Update:\nI found something new; its the the JQuery Hotbox.</p>\n\n<p><a href=\"http://www.s3maphor3.org/demo/hotbox/\" rel=\"nofollow noreferrer\">JQuery Hotbox</a></p>\n\n<p>Google hosts several JavaScript libraries on Google Code. Loading it from there saves bandwidth and it loads quick cos it has already been cached.</p>\n\n<pre><code><script src=\"http://www.google.com/jsapi\"></script> \n<script type=\"text/javascript\"> \n\n // Load jQuery \n google.load(\"jquery\", \"1.2.6\"); \n\n google.setOnLoadCallback(function() { \n // Your code goes here. \n }); \n\n</script>\n</code></pre>\n\n<p>Or</p>\n\n<pre><code><script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\" type=\"text/javascript\"></script>\n</code></pre>\n\n<p>You can also use this to tell when an image is fully loaded.</p>\n\n<pre><code>$('#myImage').attr('src', 'image.jpg').load(function() { \n alert('Image Loaded'); \n});\n</code></pre>\n\n<p>The \"console.info\" of firebug, which you can use to dump messages and variables to the screen without having to use alert boxes. \"console.time\" allows you to easily set up a timer to wrap a bunch of code and see how long it takes.</p>\n\n<pre><code>console.time('create list');\n\nfor (i = 0; i < 1000; i++) {\n var myList = $('.myList');\n myList.append('This is list item ' + i);\n}\n\nconsole.timeEnd('create list');\n</code></pre>\n"
},
{
"answer_id": 2217596,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Defining properties at element creation</strong></p>\n\n<p>In jQuery 1.4 you can use an object literal to define properties when you create an element:</p>\n\n<pre><code>var e = $(\"<a />\", { href: \"#\", class: \"a-class another-class\", title: \"...\" });\n</code></pre>\n\n<p>... You can even add styles:</p>\n\n<pre><code>$(\"<a />\", {\n ...\n css: {\n color: \"#FF0000\",\n display: \"block\"\n }\n});\n</code></pre>\n\n<p>Here's a <a href=\"http://api.jquery.com/jQuery/#jQuery2\" rel=\"nofollow noreferrer\">link to the documentation</a>.</p>\n"
},
{
"answer_id": 2218120,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<p><strong>No-conflict mode</strong></p>\n\n<pre><code>jQuery.noConflict();\n</code></pre>\n\n<blockquote>\n <p>\"Run this function to give control of the <code>$</code> variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the <code>$</code> object of other libraries.</p>\n \n <p>By using this function, you will only be able to access jQuery using the <code>jQuery</code> variable. For example, where you used to do <code>$(\"div p\")</code>, you now must do <code>jQuery(\"div p\")</code>\".</p>\n</blockquote>\n"
},
{
"answer_id": 2218129,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Shorthand for the ready-event</strong></p>\n\n<p>The explicit and verbose way:</p>\n\n<pre><code>$(document).ready(function ()\n{\n // ...\n});\n</code></pre>\n\n<p>The shorthand:</p>\n\n<pre><code>$(function ()\n{\n // ...\n});\n</code></pre>\n"
},
{
"answer_id": 2218135,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Line-breaks and chainability</strong></p>\n\n<p>When chaining multiple calls on collections...</p>\n\n<pre><code>$(\"a\").hide().addClass().fadeIn().hide();\n</code></pre>\n\n<p>You can increase readability with linebreaks. Like this:</p>\n\n<pre><code>$(\"a\")\n.hide()\n.addClass()\n.fadeIn()\n.hide();\n</code></pre>\n"
},
{
"answer_id": 2218334,
"author": "Vivin Paliath",
"author_id": 263004,
"author_profile": "https://Stackoverflow.com/users/263004",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Changing the type of an input element</strong></p>\n\n<p>I ran into this issue when I was trying to change the type of an input element already attached to the DOM. You have to clone the existing element, insert it before the old element, and then delete the old element. Otherwise it doesn't work:</p>\n\n<pre><code>var oldButton = jQuery(\"#Submit\");\nvar newButton = oldButton.clone();\n\nnewButton.attr(\"type\", \"button\");\nnewButton.attr(\"id\", \"newSubmit\");\nnewButton.insertBefore(oldButton);\noldButton.remove();\nnewButton.attr(\"id\", \"Submit\");\n</code></pre>\n"
},
{
"answer_id": 2750689,
"author": "OneNerd",
"author_id": 76682,
"author_profile": "https://Stackoverflow.com/users/76682",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Asynchronous each() function</strong></p>\n\n<p>If you have <strong>really complex documents</strong> where running the jquery <strong>each()</strong> function locks up the browser during the iteration, and/or Internet Explorer pops up the '<em>do you want to continue running this script</em>' message, this solution will save the day.</p>\n\n<pre><code>jQuery.forEach = function (in_array, in_pause_ms, in_callback)\n{\n if (!in_array.length) return; // make sure array was sent\n\n var i = 0; // starting index\n\n bgEach(); // call the function\n\n function bgEach()\n {\n if (in_callback.call(in_array[i], i, in_array[i]) !== false)\n {\n i++; // move to next item\n\n if (i < in_array.length) setTimeout(bgEach, in_pause_ms);\n }\n }\n\n return in_array; // returns array\n};\n\n\njQuery.fn.forEach = function (in_callback, in_optional_pause_ms)\n{\n if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default\n\n return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it\n};\n</code></pre>\n\n<p><br /></p>\n\n<p><strong>The first way you can use it is just like each():</strong></p>\n\n<pre><code>$('your_selector').forEach( function() {} );\n</code></pre>\n\n<p>An <strong>optional 2nd parameter lets you specify the speed/delay in between iterations</strong> which may be useful for animations (<em>the following example will wait 1 second in between iterations</em>):</p>\n\n<pre><code>$('your_selector').forEach( function() {}, 1000 );\n</code></pre>\n\n<p>Remember that since this works asynchronously, you can't rely on the iterations to be complete before the next line of code, for example:</p>\n\n<pre><code>$('your_selector').forEach( function() {}, 500 );\n// next lines of code will run before above code is complete\n</code></pre>\n\n<p><br /></p>\n\n<p>I wrote this for an internal project, and while I am sure it can be improved, it worked for what we needed, so hope some of you find it useful. Thanks -</p>\n"
},
{
"answer_id": 2777444,
"author": "Kenneth J",
"author_id": 195456,
"author_profile": "https://Stackoverflow.com/users/195456",
"pm_score": 3,
"selected": false,
"text": "<p>Use .stop(true,true) when triggering an animation prevents it from repeating the animation. This is especially helpful for rollover animations.</p>\n\n<pre><code>$(\"#someElement\").hover(function(){\n $(\"div.desc\", this).stop(true,true).fadeIn();\n},function(){\n $(\"div.desc\", this).fadeOut();\n});\n</code></pre>\n"
},
{
"answer_id": 3189444,
"author": "Rixius",
"author_id": 212307,
"author_profile": "https://Stackoverflow.com/users/212307",
"pm_score": 3,
"selected": false,
"text": "<p>Using self-executing anonymous functions in a method call such as <code>.append()</code> to iterate through something. I.E.:</p>\n\n<pre><code>$(\"<ul>\").append((function ()\n{\n var data = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\"],\n output = $(\"<div>\"),\n x = -1,\n y = data.length;\n\n while (++x < y) output.append(\"<li>\" + info[x] + \"</li>\");\n\n return output.children();\n}()));\n</code></pre>\n\n<p>I use this to iterate through things that would be large and uncomfortable to break out of my chaining to build.</p>\n"
},
{
"answer_id": 3189764,
"author": "adam",
"author_id": 73894,
"author_profile": "https://Stackoverflow.com/users/73894",
"pm_score": 0,
"selected": false,
"text": "<h2>Increment Row Index in name</h2>\n<p>Here is a neat way to increment a row index of a cloned input element if your input element name contains a row index like <code>'0_row'</code>:</p>\n<pre><code>$(this).attr('name', $(this).attr('name').replace(/^\\d+/, function(n){ return ++n; }));\n</code></pre>\n<p>The cloned element's name will now be <code>'1_row'</code></p>\n"
},
{
"answer_id": 3967325,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Access jQuery functions as you would an array</strong></p>\n\n<p>Add/remove a class based on a boolean...</p>\n\n<pre><code>function changeState(b)\n{\n $(\"selector\")[b ? \"addClass\" : \"removeClass\"](\"name of the class\");\n}\n</code></pre>\n\n<p>Is the shorter version of...</p>\n\n<pre><code>function changeState(b)\n{\n if (b)\n {\n $(\"selector\").addClass(\"name of the class\");\n }\n else\n {\n $(\"selector\").removeClass(\"name of the class\");\n }\n}\n</code></pre>\n\n<p>Not that many use-cases for this. Never the less; I think it's neat :)</p>\n\n<p><br /></p>\n\n<p><strong>Update</strong></p>\n\n<p>Just in case you are not the comment-reading-type, ThiefMaster points out that the <a href=\"http://api.jquery.com/toggleClass/\" rel=\"nofollow\">toggleClass accepts a boolean value</a>, which determines if a class should be added or removed. So as far as my example code above goes, this would be the best approach...</p>\n\n<pre><code>$('selector').toggleClass('name_of_the_class', true/false);\n</code></pre>\n"
},
{
"answer_id": 4348522,
"author": "Ralph Holzmann",
"author_id": 346724,
"author_profile": "https://Stackoverflow.com/users/346724",
"pm_score": 3,
"selected": false,
"text": "<p>Use filtering methods over pseudo selectors when possible so jQuery can use querySelectorAll (which is much faster than sizzle). Consider this selector:</p>\n\n<pre><code>$('.class:first')\n</code></pre>\n\n<p>The same selection can be made using:</p>\n\n<pre><code>$('.class').eq(0)\n</code></pre>\n\n<p>Which is must faster because the initial selection of '.class' is QSA compatible</p>\n"
},
{
"answer_id": 4962433,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<p>A shameless plug... <a href=\"http://roosteronacid.com/blog/index.php/2011/02/10/the-jquery-template-plug-in-implementing-complex-logic-using-render-functions/\" rel=\"nofollow\">The jQuery template plug-in: implementing complex logic using render-functions</a></p>\n\n<blockquote>\n <p>The new jQuery template plug-in is\n awesome. That being said, the\n double-curly brace template-tags are\n not exactly my cup of tea. In a more\n complex template the tags obscure the\n templates markup, and implementing\n logic past simple if/else statements\n is a pain.</p>\n \n <p>After messing around with the plug-in\n for a few hours, my head began to hurt\n from trying to distinguish the markup\n in my template from the millions of\n double curly braces.</p>\n \n <p>So I popped an aspirin and began work\n on an alternative</p>\n</blockquote>\n"
},
{
"answer_id": 5059173,
"author": "adardesign",
"author_id": 56449,
"author_profile": "https://Stackoverflow.com/users/56449",
"pm_score": 2,
"selected": false,
"text": "<h2>Add a selector for elements above the fold</h2>\n\n<h3>As a jQuery selector plugin</h3>\n\n<pre><code> $.extend($.expr[':'], {\n \"aboveFold\": function(a, i, m) {\n var container = m[3],\n var fold;\n if (typeof container === \"undefined\") {\n fold = $(window).height() + $(window).scrollTop();\n } else {\n if ($(container).length == 0 || $(container).offset().top == null) return false;\n fold = $(container).offset().top + $(container).height();\n }\n return fold >= $(a).offset().top;\n } \n});\n</code></pre>\n\n<h3>Usage:</h3>\n\n<pre><code>$(\"p:aboveFold\").css({color:\"red\"});\n</code></pre>\n\n<p>Thx to <a href=\"http://flowcoder.com/scottymac\" rel=\"nofollow\">scottymac</a></p>\n"
},
{
"answer_id": 5259973,
"author": "rbginge",
"author_id": 524263,
"author_profile": "https://Stackoverflow.com/users/524263",
"pm_score": 1,
"selected": false,
"text": "<p>On a more fundamental and high-level note, you could try to emulate the basic selector mechanism of jQuery by writing your own little framework (it's simpler than it sounds). Not only will it improve your Javascript no end, it will also help you to understand just why jQuery's $(\"#elementId\") is many times faster than $(\".elementClass\") and is also faster than $(\"element#elementId\") (which is perhaps on the surface counter-intuitive).</p>\n\n<p>This will also force you to learn about object oriented Javascript which will help you to organise your code in a more modular fashion, thereby avoiding the spaghetti code nature that heavy jQuery script blocks can take on.</p>\n"
},
{
"answer_id": 5409115,
"author": "Shahin",
"author_id": 369161,
"author_profile": "https://Stackoverflow.com/users/369161",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Access iFrame Elements</strong>\nIframes aren’t the best solution to most problems, but when you do need to use one it’s very handy to know how to access the elements inside it with Javascript. jQuery’s contents() method makes this a breeze, enabling us to load the iframe’s DOM in one line like this:</p>\n\n<pre><code>$(function(){\n var iFrameDOM = $(\"iframe#someID\").contents();\n //Now you can use <strong>find()</strong> to access any element in the iframe:\n\n iFrameDOM.find(\".message\").slideUp();\n //Slides up all elements classed 'message' in the iframe\n});\n</code></pre>\n\n<p><a href=\"http://www.problogdesign.com/coding/30-pro-jquery-tips-tricks-and-strategies/\" rel=\"nofollow\">source</a></p>\n"
},
{
"answer_id": 5410587,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": false,
"text": "<p><strong>HTML5 data attributes support, on steroids!</strong></p>\n\n<p>The <a href=\"http://api.jquery.com/data/\">data function</a> has been mentioned before. With it, you are able to associate data with DOM elements.</p>\n\n<p>Recently the jQuery team has added support for <a href=\"http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data-with-the-data-attributes\">HTML5 custom data-* attributes</a>. And as if that wasn't enough; they've force-fed the data function with steroids, which means that you are able to store complex objects in the form of JSON, directly in your markup.\n<br /><br /></p>\n\n<p>The HTML:</p>\n\n<pre><code><p data-xyz = '{\"str\": \"hi there\", \"int\": 2, \"obj\": { \"arr\": [1, 2, 3] } }' />\n</code></pre>\n\n<p><br />\nThe JavaScript:</p>\n\n<pre><code>var data = $(\"p\").data(\"xyz\");\n\ndata.str // \"hi there\"\ntypeof data.str // \"string\"\n\ndata.int + 2 // 4\ntypeof data.int // \"number\"\n\ndata.obj.arr.join(\" + \") + \" = 6\" // \"1 + 2 + 3 = 6\"\ntypeof data.obj.arr // \"object\" ... Gobbles! Errrghh!\n</code></pre>\n"
},
{
"answer_id": 5724897,
"author": "btt",
"author_id": 193479,
"author_profile": "https://Stackoverflow.com/users/193479",
"pm_score": 1,
"selected": false,
"text": "<p>The \"ends with\" element selector is great for ASP.NET web forms development because you don't need to worry about the prepended ctl00 silliness:</p>\n\n<pre><code>$(\"[id$='txtFirstName']\");\n</code></pre>\n\n<p>As noted in the comments, this selector (as with any layer of abstraction) can be slow if used without care. Prefer to scope the selector to some containing element, e.g.,</p>\n\n<pre><code>$(\".container [id$='txtFirstName']\");\n</code></pre>\n\n<p>to reduce the number of required elements to traverse.</p>\n\n<p><a href=\"http://docs.jquery.com/Selectors/attributeEndsWith#attributevalue\" rel=\"nofollow\">jQuery documentation</a></p>\n"
},
{
"answer_id": 6769692,
"author": "ngn",
"author_id": 23109,
"author_profile": "https://Stackoverflow.com/users/23109",
"pm_score": 0,
"selected": false,
"text": "<p>Bind to an event and execute the event handler immediately:</p>\n\n<pre><code>$('selector').bind('change now', function () { // bind to two events: 'change' and 'now'\n // update other portions of the UI\n}).trigger('now'); // 'now' is a custom event\n</code></pre>\n\n<p>This is like</p>\n\n<pre><code>function update() {\n // update other portions of the UI\n}\n$('selector').change(update);\nupdate();\n</code></pre>\n\n<p>but without the need to create a separate named function.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
Syntax
------
* [Shorthand for the ready-event](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218129#2218129) by roosteronacid
* [Line breaks and chainability](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218135#2218135) by roosteronacid
* [Nesting filters](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389474#389474) by Nathan Long
* [Cache a collection and execute commands on the same line](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/552831#552831) by roosteronacid
* [Contains selector](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1519474#1519474) by roosteronacid
* [Defining properties at element creation](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689) by roosteronacid
* [Access jQuery functions as you would an array](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/3967325#3967325) by roosteronacid
* [The noConflict function - Freeing up the $ variable](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182666#182666) by Oli
* [Isolate the $ variable in noConflict mode](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382853#382853) by nickf
* [No-conflict mode](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218120#2218120) by roosteronacid
Data Storage
------------
* [The data function - bind data to elements](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382834#382834) by TenebrousX
* [HTML5 data attributes support, on steroids!](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/5410587#5410587) by roosteronacid
* [The jQuery metadata plug-in](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504776#504776) by Filip Dupanović
Optimization
------------
* [Optimize performance of complex selectors](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1019899#1019899) by roosteronacid
* [The context parameter](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504732#504732) by lupefiasco
* [Save and reuse searches](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389793#389793) by Nathan Long
* [Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382922#382922) by Andreas Grech
Miscellaneous
-------------
* [Check the index of an element in a collection](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389906#389906) by redsquare
* [Live event handlers](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/892617#892617) by TM
* [Replace anonymous functions with named functions](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385) by ken
* [Microsoft AJAX framework and jQuery bridge](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191139#191139) by Slace
* [jQuery tutorials](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/922865#922865) by egyamado
* [Remove elements from a collection and preserve chainability](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/998547#998547) by roosteronacid
* [Declare $this at the beginning of anonymous functions](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191061#191061) by Ben
* [FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1771311#1771311) by Colour Blend
* [Judicious use of third-party jQuery scripts](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182715#182715) by harriyott
* [The each function](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1584927#1584927) by Jan Zich
* [Form Extensions plug-in](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1235178#1235178) by Chris S
* [Asynchronous each function](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689) by OneNerd
* [The jQuery template plug-in: implementing complex logic using render-functions](https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/4962433#4962433) by roosteronacid
|
**Creating an HTML Element and keeping a reference**
```
var newDiv = $("<div />");
newDiv.attr("id", "myNewDiv").appendTo("body");
/* Now whenever I want to append the new div I created,
I can just reference it from the "newDiv" variable */
```
**Checking if an element exists**
```
if ($("#someDiv").length)
{
// It exists...
}
```
**Writing your own selectors**
```
$.extend($.expr[":"], {
over100pixels: function (e)
{
return $(e).height() > 100;
}
});
$(".box:over100pixels").click(function ()
{
alert("The element you clicked is over 100 pixels height");
});
```
|
182,635 |
<p>I am trying to find all matches in a string that begins with <code>| |</code>. </p>
<p>I have tried: <code>if ($line =~ m/^\\\|\s\\\|/)</code> which didn't work. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 182650,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "<p>You are escaping the pipe one time too many, effectively escaping the backslash instead.</p>\n\n<pre><code>print \"YES!\" if ($line =~ m/^\\|\\s\\|/);\n</code></pre>\n"
},
{
"answer_id": 182676,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": -1,
"selected": false,
"text": "<p>What about:</p>\n\n<pre><code>m/^\\|\\s*\\|/ \n</code></pre>\n"
},
{
"answer_id": 183271,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Pipe character should be escaped with a single backslash in a Perl regex. (Perl regexes are a bit different from POSIX regexes. If you're using this in, say, grep, things would be a bit different.) If you're specifically looking for a space between them, then use an unescaped space. They're perfectly acceptable in a Perl regex. Here's a brief test program:</p>\n\n<pre><code>my @lines = <DATA>;\n\nfor (@lines) {\n print if /^\\| \\|/;\n}\n\n__DATA__ \n| | Good - space \n|| Bad - no space \n| | Bad - tab \n | | Bad - beginning space \n Bad - no bars \n</code></pre>\n"
},
{
"answer_id": 183297,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 2,
"selected": false,
"text": "<p><p>If it's a literal string you're searching for, you don't need a regular expression.</p>\n\n<pre><code>my $search_for = '| |';\nmy $search_in = whatever();\nif ( substr( $search_in, 0, length $search_for ) eq $search_for ) {\n print \"found '$search_for' at start of string.\\n\";\n}\n</code></pre>\n\n<p><p>Or it might be clearer to do this:</p>\n\n<pre><code>my $search_for = '| |';\nmy $search_in = whatever();\nif ( 0 == index( $search_in, $search_for ) ) {\n print \"found '$search_for' at start of string.\\n\";\n}\n</code></pre>\n\n<p><p>You might also want to look at <a href=\"http://perldoc.perl.org/functions/quotemeta.html\" rel=\"nofollow noreferrer\">quotemeta</a> when you want to use a literal in a regexp.</p>\n"
},
{
"answer_id": 727016,
"author": "Mathieu Longtin",
"author_id": 54320,
"author_profile": "https://Stackoverflow.com/users/54320",
"pm_score": 0,
"selected": false,
"text": "<p>Remove the ^ and the double back-slashes. The ^ forces the string to be at the beginning of the string. Since you're looking for all matches in one string, that's probably not what you want.</p>\n\n<pre><code>m/\\|\\s\\|/\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to find all matches in a string that begins with `| |`.
I have tried: `if ($line =~ m/^\\\|\s\\\|/)` which didn't work.
Any ideas?
|
You are escaping the pipe one time too many, effectively escaping the backslash instead.
```
print "YES!" if ($line =~ m/^\|\s\|/);
```
|
182,636 |
<p>I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.</p>
<p>Example:</p>
<pre><code>public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
</code></pre>
<p>Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.</p>
<p>My question is: does someone know a good alternative or workaround for this?</p>
|
[
{
"answer_id": 182672,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 7,
"selected": true,
"text": "<p>Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method : </p>\n\n<pre><code>public class MyGenericClass<T> {\n\n private final Class<T> clazz;\n\n public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {\n return new MyGenericClass<U>(clazz);\n }\n\n protected MyGenericClass(Class<T> clazz) {\n this.clazz = clazz;\n }\n\n public void doSomething() {\n T instance = clazz.newInstance();\n }\n}\n</code></pre>\n\n<p>It's ugly, but it works.</p>\n"
},
{
"answer_id": 4699117,
"author": "Christoph",
"author_id": 576648,
"author_profile": "https://Stackoverflow.com/users/576648",
"pm_score": 5,
"selected": false,
"text": "<p>I was just pointed to this solution:</p>\n\n<pre><code>import java.lang.reflect.ParameterizedType;\n\npublic abstract class A<B> {\n public Class<B> g() throws Exception {\n ParameterizedType superclass =\n (ParameterizedType) getClass().getGenericSuperclass();\n\n return (Class<B>) superclass.getActualTypeArguments()[0];\n }\n}\n</code></pre>\n\n<p>This works if <code>A</code> is given a concrete type by a subclass:</p>\n\n<pre><code>new A<String>() {}.g() // this will work\n\nclass B extends A<String> {}\nnew B().g() // this will work\n\nclass C<T> extends A<T> {}\nnew C<String>().g() // this will NOT work\n</code></pre>\n"
},
{
"answer_id": 4927744,
"author": "Steven Collins",
"author_id": 602136,
"author_profile": "https://Stackoverflow.com/users/602136",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately Christoph's solution as written only works in very limited circumstances. [EDIT: as commented below I no longer remember my reasoning for this sentence and it is likely wrong: \"Note that this will only work in abstract classes, first of all.\"] The next difficulty is that <code>g()</code> only works from DIRECT subclasses of <code>A</code>. We can fix that, though:</p>\n\n<pre><code>private Class<?> extractClassFromType(Type t) throws ClassCastException {\n if (t instanceof Class<?>) {\n return (Class<?>)t;\n }\n return (Class<?>)((ParameterizedType)t).getRawType();\n}\n\npublic Class<B> g() throws ClassCastException {\n Class<?> superClass = getClass(); // initial value\n Type superType;\n do {\n superType = superClass.getGenericSuperclass();\n superClass = extractClassFromType(superType);\n } while (! (superClass.equals(A.class)));\n\n Type actualArg = ((ParameterizedType)superType).getActualTypeArguments()[0];\n return (Class<B>)extractClassFromType(actualArg);\n}\n</code></pre>\n\n<p>This will work in many situations in practice, but not ALL the time. Consider:</p>\n\n<pre><code>public class Foo<U,T extends Collection<?>> extends A<T> {}\n\n(new Foo<String,List<Object>>() {}).g();\n</code></pre>\n\n<p>This will throw a <code>ClassCastException</code>, because the type argument here isn't a <code>Class</code> or a <code>ParameterizedType</code> at all; it's the <code>TypeVariable</code> <code>T</code>. So now you would be stuck trying to figure out what type <code>T</code> was supposed to stand for, and so on down the rabbit hole.</p>\n\n<p>I think the only reasonable, general answer is something akin to Nicolas's initial answer -- in general, if your class needs to instantiate objects of some other class that is unknown at compile-time, users of your class need to pass that class literal (or, perhaps, a Factory) to your class explicitly and not rely solely on generics.</p>\n"
},
{
"answer_id": 8061600,
"author": "Jet Geng",
"author_id": 1004479,
"author_profile": "https://Stackoverflow.com/users/1004479",
"pm_score": 2,
"selected": false,
"text": "<p>i find another way to obtain the Class of the generic object</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>public Class<?> getGenericClass(){\n Class<?> result =null;\n Type type =this.getClass().getGenericSuperclass();\n\n if(type instanceofParameterizedType){\n ParameterizedType pt =(ParameterizedType) type;\n Type[] fieldArgTypes = pt.getActualTypeArguments();\n result =(Class<?>) fieldArgTypes[0];\n }\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 25253110,
"author": "intrepidis",
"author_id": 847235,
"author_profile": "https://Stackoverflow.com/users/847235",
"pm_score": 0,
"selected": false,
"text": "<p>I will elaborate on Christoph's solution.</p>\n\n<p>Here is the ClassGetter abstract class:</p>\n\n<pre><code>private abstract class ClassGetter<T> {\n public final Class<T> get() {\n final ParameterizedType superclass = (ParameterizedType)\n getClass().getGenericSuperclass();\n return (Class<T>)superclass.getActualTypeArguments()[0];\n }\n}\n</code></pre>\n\n<p>Here is a static method which uses the above class to find a generic class' type:</p>\n\n<pre><code>public static <T> Class<T> getGenericClass() {\n return new ClassGetter<T>() {}.get();\n}\n</code></pre>\n\n<p>As an example of it's usage, you could make this method:</p>\n\n<pre><code>public static final <T> T instantiate() {\n final Class<T> clazz = getGenericClass();\n try {\n return clazz.getConstructor((Class[])null).newInstance(null);\n } catch (Exception e) {\n return null;\n }\n}\n</code></pre>\n\n<p>And then use it like this:</p>\n\n<pre><code>T var = instantiate();\n</code></pre>\n"
},
{
"answer_id": 50577180,
"author": "Abul Kasim M",
"author_id": 9822428,
"author_profile": "https://Stackoverflow.com/users/9822428",
"pm_score": -1,
"selected": false,
"text": "<p>public class DatabaseAccessUtil {</p>\n\n<pre><code>EntityManagerFactory entitymanagerfactory;\nEntityManager entitymanager;\n\npublic DatabaseAccessUtil() {\n entitymanagerfactory=Persistence.createEntityManagerFactory(\"bookmyshow\");\n entitymanager=entitymanagerfactory.createEntityManager();\n}\n\npublic void save (T t) {\n entitymanager.getTransaction().begin();\n entitymanager.persist(t);\n entitymanager.getTransaction().commit();\n}\n\npublic void update(T t) {\n entitymanager.getTransaction().begin();\n entitymanager.persist(t);\n entitymanager.getTransaction().commit();\n}\n\npublic void delete(T t) {\n entitymanager.getTransaction().begin();\n entitymanager.remove(t);\n entitymanager.getTransaction().commit();\n}\n\npublic Object retrieve(Query query) {\n return query.getSingleResult();\n}\n//call the method - retrieve(object,requiredclass.class)\npublic Object retrieve(Object primaryKey,class clazz) throws Exception {\n\n return entitymanager.find(clazz,primaryKey); \n\n}\n</code></pre>\n\n<p>}</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26066/"
] |
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.
Example:
```
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
```
Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.
My question is: does someone know a good alternative or workaround for this?
|
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
```
public class MyGenericClass<T> {
private final Class<T> clazz;
public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
return new MyGenericClass<U>(clazz);
}
protected MyGenericClass(Class<T> clazz) {
this.clazz = clazz;
}
public void doSomething() {
T instance = clazz.newInstance();
}
}
```
It's ugly, but it works.
|
182,675 |
<p>On a server I have to take care of, errors from a vhost do not go to the standard PHP error log.</p>
<p>In the php.ini we have </p>
<pre><code>log = /var/log/file
</code></pre>
<p>and <code>phpinfo()</code> does not show any difference between the vhost and the whole server.</p>
<p>But the callback function set up by <code>set_error_handler()</code> catches errors which are not in the php log.</p>
<p><code>error_reporting</code> is set to <code>E_ALL</code> once and never modified.</p>
<p>Could you help me to find a way to explore what's happening here?</p>
|
[
{
"answer_id": 182705,
"author": "Rimas Kudelis",
"author_id": 25804,
"author_profile": "https://Stackoverflow.com/users/25804",
"pm_score": 3,
"selected": true,
"text": "<p>Perhaps the errors that aren't logged <a href=\"http://php.net/error-reporting\" rel=\"nofollow noreferrer\">aren't supposed to be logged</a>? The <a href=\"http://php.net/set_error_handler\" rel=\"nofollow noreferrer\">error reporting settings have no effect when set_error_handler is used</a>, hence you see more errors than are in the logfile.</p>\n"
},
{
"answer_id": 192875,
"author": "Clutch",
"author_id": 25143,
"author_profile": "https://Stackoverflow.com/users/25143",
"pm_score": 0,
"selected": false,
"text": "<p>I would take a look at error_log, log_error and error_reporting directive in php.ini and also take a look in the httpd.conf because directives can also be added there using \"php_admin_value\" and others.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8404/"
] |
On a server I have to take care of, errors from a vhost do not go to the standard PHP error log.
In the php.ini we have
```
log = /var/log/file
```
and `phpinfo()` does not show any difference between the vhost and the whole server.
But the callback function set up by `set_error_handler()` catches errors which are not in the php log.
`error_reporting` is set to `E_ALL` once and never modified.
Could you help me to find a way to explore what's happening here?
|
Perhaps the errors that aren't logged [aren't supposed to be logged](http://php.net/error-reporting)? The [error reporting settings have no effect when set\_error\_handler is used](http://php.net/set_error_handler), hence you see more errors than are in the logfile.
|
182,683 |
<p>I have a very interesting problem on my LinqToSql model. On some of my tables i have a references to other tables and in LinqToSql this is represented by a EnitiyRef class, when you are trying to access the references table LinqToSql will load the reference from the database.</p>
<p>On my development machine everything worked fine (the references were loaded perfectly) but last night i uploaded the changed to our production server and started getting NullReferenceExceptions when trying to access the reference on my tables.</p>
<p>Sample code:</p>
<pre><code>var sale = db.Sales.Single(s => s.ID == 1);
string username = sale.User.Name; // User is a reference to a User table
// LinqToSql will automatically load the
// row and access the fields i need.
// On my server the sale.User throws an exception that its null (User) but the user
// is definitly in the database (there is even a FK constraint from Sale to User)
</code></pre>
<p>At first i thought that it my DataContext got GC'd but i double checked everything with no result (besides it works on my box).</p>
<p>(Everything is the same on the server and my box, same dll's, same db schema etc...)
(I actually copied the entire DBF file over to my server so its the exact same schema)</p>
|
[
{
"answer_id": 182696,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Have you turned the context logging on and compared the results on your dev box to those on your production box?</p>\n"
},
{
"answer_id": 182728,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>If you move your source to the production server and compile it there, try regenerating the generated source for the DataContext. You can do this by running \"run user defined tool\" from the context menu of your DataContext source file.</p>\n\n<p>If both share the same binary, make sure the database definition is exactly the same in both databases. A small difference like one column being nullable on your production server but not nullable on your devbox can make all the difference.</p>\n"
},
{
"answer_id": 182944,
"author": "bovium",
"author_id": 11135,
"author_profile": "https://Stackoverflow.com/users/11135",
"pm_score": 1,
"selected": false,
"text": "<p>In order to find and resolve an issue like that it would be helpful with a stacktrace and perhaps a profiling on the database.</p>\n\n<p>The problem could perhaps be a security issue. Have you tried to log in with the same credentials in Management Studio as your application uses and do a select on the table.</p>\n\n<p>That would at least give you an idea about security or a linq issue.</p>\n"
},
{
"answer_id": 183300,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>Examine DataContext lifetime. There may be stale cache at work here</p>\n\n<p>For example: </p>\n\n<ol>\n<li>Context1 : Load Sale with ID == 1. Examine its User property and observe null User.</li>\n<li>Context2: Load Sale with ID == 1. Modify User property by adding a new User. Commit.</li>\n<li>Context1: Load Sale with ID == 1. Examine its User property. Yup, still null (it's cached!!).</li>\n</ol>\n"
},
{
"answer_id": 188153,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 0,
"selected": false,
"text": "<p>One possibility is that you connection string used by your DBML is still pointing to a database server other than Production. </p>\n\n<p>This happened to us whenever a LinqDataSource was used directly in an ASPX page, and thus the DataContext was using the default constructor, which was pointing to a connection string based on the database that the last developer used to import the DBML.</p>\n\n<p>What we did was create a DataContext object that inherited from the generated DataContext and overrode the default constructor with the correct connection string from our web.config.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26135/"
] |
I have a very interesting problem on my LinqToSql model. On some of my tables i have a references to other tables and in LinqToSql this is represented by a EnitiyRef class, when you are trying to access the references table LinqToSql will load the reference from the database.
On my development machine everything worked fine (the references were loaded perfectly) but last night i uploaded the changed to our production server and started getting NullReferenceExceptions when trying to access the reference on my tables.
Sample code:
```
var sale = db.Sales.Single(s => s.ID == 1);
string username = sale.User.Name; // User is a reference to a User table
// LinqToSql will automatically load the
// row and access the fields i need.
// On my server the sale.User throws an exception that its null (User) but the user
// is definitly in the database (there is even a FK constraint from Sale to User)
```
At first i thought that it my DataContext got GC'd but i double checked everything with no result (besides it works on my box).
(Everything is the same on the server and my box, same dll's, same db schema etc...)
(I actually copied the entire DBF file over to my server so its the exact same schema)
|
Have you turned the context logging on and compared the results on your dev box to those on your production box?
|
182,721 |
<p>We use Spring + Hibernate for a Webapp.</p>
<p>This Webapp will be deployed on two unrelated production sites. These two production sites will use the Webapp to generate and use Person data in parallel.</p>
<p>What I need to do, is to make sure that the Persons generated on these two unrelated production sites all have distinct PKs, so that we can merge the Person data from these two sites at any time.</p>
<p>A further constraint imposed to me is that these PKs fit in a <code>Long</code>, so I can't use UUIDs.</p>
<p>What I'm trying to do is to change the current hibernate mapping, that has sequence <code>S_PERSON</code> as generator:</p>
<pre><code><hibernate-mapping default-cascade="save-update" auto-import="false">
<class name="com.some.domain.Person" abstract="true">
<id name="id">
<column name="PERSON_ID"/>
<generator class="sequence">
<param name="sequence">S_PERSON</param>
</generator>
</id>
...
</hibernate-mapping>
</code></pre>
<p>into something configurable, so that <code>PERSON_ID</code> have its PKs generated from different sequences (maybe <code>S_PERSON_1</code> and <code>S_PERSON_2</code>) depending on the deployment site's Spring configuration files.</p>
<p>Of course,</p>
<pre><code> <generator class="sequence">
<param name="sequence">${sequenceName}</param>
</generator>
</code></pre>
<p>doesn't work, so I have to figure out something else... I guess my generator should point to a configurable bean that in turn points to a sequence or another, but I can't figure how to do that...</p>
<p>Any ideas or workaround?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 183682,
"author": "Eric R. Rath",
"author_id": 23883,
"author_profile": "https://Stackoverflow.com/users/23883",
"pm_score": 3,
"selected": true,
"text": "<p>You could use sequences on both production systems, but define them differently:</p>\n\n<p>Production System 1:\nCREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 2;</p>\n\n<p>Production System 2:\nCREATE SEQUENCE sequence_name START WITH 2 INCREMENT BY 2;</p>\n\n<p>The first sequence will generate only odd numbers, the second only even numbers.</p>\n"
},
{
"answer_id": 184018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You basically need to make sure the values for the keys fall into different sets. So prepending a varchar with a system identifier.</p>\n\n<p>Note: I havent tested this but you should be able to define a normal sequence per database</p>\n\n<p>and do something like </p>\n\n<pre><code>insert VALUES('Sys1' || to_char(sequence.nextval), val1, val2, val3);\ninsert VALUES('Sys2' || to_char(sequence.nextval), val1, val2, val3);\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] |
We use Spring + Hibernate for a Webapp.
This Webapp will be deployed on two unrelated production sites. These two production sites will use the Webapp to generate and use Person data in parallel.
What I need to do, is to make sure that the Persons generated on these two unrelated production sites all have distinct PKs, so that we can merge the Person data from these two sites at any time.
A further constraint imposed to me is that these PKs fit in a `Long`, so I can't use UUIDs.
What I'm trying to do is to change the current hibernate mapping, that has sequence `S_PERSON` as generator:
```
<hibernate-mapping default-cascade="save-update" auto-import="false">
<class name="com.some.domain.Person" abstract="true">
<id name="id">
<column name="PERSON_ID"/>
<generator class="sequence">
<param name="sequence">S_PERSON</param>
</generator>
</id>
...
</hibernate-mapping>
```
into something configurable, so that `PERSON_ID` have its PKs generated from different sequences (maybe `S_PERSON_1` and `S_PERSON_2`) depending on the deployment site's Spring configuration files.
Of course,
```
<generator class="sequence">
<param name="sequence">${sequenceName}</param>
</generator>
```
doesn't work, so I have to figure out something else... I guess my generator should point to a configurable bean that in turn points to a sequence or another, but I can't figure how to do that...
Any ideas or workaround?
Thanks!
|
You could use sequences on both production systems, but define them differently:
Production System 1:
CREATE SEQUENCE sequence\_name START WITH 1 INCREMENT BY 2;
Production System 2:
CREATE SEQUENCE sequence\_name START WITH 2 INCREMENT BY 2;
The first sequence will generate only odd numbers, the second only even numbers.
|
182,742 |
<p>Specifically MSSQL 2005.</p>
|
[
{
"answer_id": 182745,
"author": "David Collie",
"author_id": 7577,
"author_profile": "https://Stackoverflow.com/users/7577",
"pm_score": 0,
"selected": false,
"text": "<p>Some links to possible answers:</p>\n\n<ul>\n<li><p><a href=\"http://www.extremeexperts.com/sql/Tips/DateTrick.aspx\" rel=\"nofollow noreferrer\">http://www.extremeexperts.com/sql/Tips/DateTrick.aspx</a></p></li>\n<li><p><a href=\"http://www.devx.com/tips/Tip/14405\" rel=\"nofollow noreferrer\">http://www.devx.com/tips/Tip/14405</a></p></li>\n<li><p><a href=\"http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/\" rel=\"nofollow noreferrer\">http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/</a></p></li>\n<li><p><a href=\"http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html\" rel=\"nofollow noreferrer\">http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html</a></p></li>\n</ul>\n"
},
{
"answer_id": 182769,
"author": "sebagomez",
"author_id": 23893,
"author_profile": "https://Stackoverflow.com/users/23893",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)\n</code></pre>\n"
},
{
"answer_id": 182776,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.</p>\n\n<pre><code>select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );\n</code></pre>\n\n<p>To understand how it works we have to look at the <a href=\"http://www.w3schools.com/sql/func_dateadd.asp\" rel=\"noreferrer\">dateadd()</a> and <a href=\"http://www.w3schools.com/sql/func_datediff.asp\" rel=\"noreferrer\">datediff()</a> functions.</p>\n\n<pre><code>DATEADD(datepart, number, date) \nDATEDIFF(datepart, startdate, enddate)\n</code></pre>\n\n<p>If you run just the most inner call to datediff(), you get the current month number since timestamp 0.</p>\n\n<pre><code>select datediff(m, 0, getdate() ); \n1327\n</code></pre>\n\n<p>The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.</p>\n\n<pre><code>select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );\n2010-09-01 00:00:00.000\n</code></pre>\n\n<p>Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.</p>\n\n<pre><code>select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );\n2010-08-31 23:59:59.000\n</code></pre>\n\n<p><hr/>\n<strong>This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.</strong></p>\n\n<p>Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.</p>\n\n<pre><code>dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))\n</code></pre>\n"
},
{
"answer_id": 182950,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>DECLARE\n @Now datetime,\n @Today datetime,\n @ThisMonth datetime,\n @NextMonth datetime,\n @LastDayThisMonth datetime\n\nSET @Now = getdate()\nSET @Today = DateAdd(dd, DateDiff(dd, 0, @Now), 0)\nSET @ThisMonth = DateAdd(mm, DateDiff(mm, 0, @Now), 0)\nSET @NextMonth = DateAdd(mm, 1, @ThisMonth)\nSET @LastDayThisMonth = DateAdd(dd, -1, @NextMonth)\n</code></pre>\n\n<p>Sometimes you really do need the last day of this month, but frequently what you really want is to describe the <strong>time interval of this month</strong>. This is the best way to describe the <strong>time interval of this month</strong>:</p>\n\n<pre><code>WHERE @ThisMonth <= someDate and someDate < @NextMonth\n</code></pre>\n"
},
{
"answer_id": 183022,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')\n</code></pre>\n\n<p>Explanation: </p>\n\n<p>General approach: use temporal functionality.</p>\n\n<pre><code>SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'\n</code></pre>\n\n<p>These are DATETIME literals, being the first time granule on the first day and last day respectively of the same 31-day month. Which month is chosen is entirely arbitrary.</p>\n\n<pre><code>SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)\n</code></pre>\n\n<p>This is the difference in whole months between the first day of the reference month and the current timestamp. Let's call this <code>@calc</code>.</p>\n\n<pre><code>SELECT DATEADD(M, @calc, '1990-01-31T00:00:00.000')\n</code></pre>\n\n<p>This adds <code>@calc</code> month granules to the last day of the reference month, the result of which is the current timestamp 'rounded' to the last day of its month. Q.E. D.</p>\n"
},
{
"answer_id": 183591,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 0,
"selected": false,
"text": "<p>For completeness, in Oracle you'd do something like ...</p>\n\n<pre><code>select add_months(trunc(sysdate,'MM'),1) ...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>select last_day(sysdate)+1 ...\n</code></pre>\n"
},
{
"answer_id": 1453783,
"author": "van",
"author_id": 99594,
"author_profile": "https://Stackoverflow.com/users/99594",
"pm_score": 0,
"selected": false,
"text": "<pre><code>DATEADD(dd, -1, DATEADD(mm, +1, DATEADD(dd, 1 - DATEPART(dd, @myDate), @myDate)))\n</code></pre>\n"
},
{
"answer_id": 6610577,
"author": "Taherul",
"author_id": 833497,
"author_profile": "https://Stackoverflow.com/users/833497",
"pm_score": 2,
"selected": false,
"text": "<p>They key points are if you can get first day of current month,Last Day of Last Month and Last Day of Current Month.</p>\n\n<p>Below is the Step by Step way to write query:</p>\n\n<p>In SQL Server Date Starts from 1901/01/01( Date 0) and up to now each month can be identified by a number. Month 12 is first month of 1902 means January. Month 1200 is January of 2001. Similarly each day can be assigned by unique number e.g Date 0 is 1901/01/01. Date 31 is 1901/02/01 as January of 1901 starts from 0.</p>\n\n<p>To find out First day of Current Month(Current Date or a given date)</p>\n\n<ol>\n<li>First we need to check how many months have passed since date 0(1901/01/01).\nSELECT DATEDIFF(MM,0,GETDATE())</li>\n<li>Add same number of month to date 0(1901/01/01)\n<blockquote>\n <blockquote>\n <p>SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0)</li>\n </ol>\n\n<p>Then we will get first day of current month(Current Date or a given date)</p>\n </blockquote>\n</blockquote></p>\n\n<p>To get Last Day of Last Month</p>\n\n<p>We need to subtract a second from first day of current month</p>\n\n<blockquote>\n <blockquote>\n <p>SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0))</p>\n </blockquote>\n</blockquote>\n\n<p>To get Last Day of Current Month</p>\n\n<p>To get first day of current month first we checked how many months have been passed since date 0(1901/01/01). If we add another month with the total months since date 0 and then add total months with date 0, we will get first day of next month.</p>\n\n<pre><code>SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0)\n</code></pre>\n\n<p>If we get first day of next month then to get last day of current month, all we need to subtract a second.</p>\n\n<blockquote>\n <blockquote>\n <p>SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0))</p>\n </blockquote>\n</blockquote>\n\n<p>Hope that would help.</p>\n"
},
{
"answer_id": 33475656,
"author": "Ragul",
"author_id": 5010874,
"author_profile": "https://Stackoverflow.com/users/5010874",
"pm_score": 1,
"selected": false,
"text": "<p>Using SQL2005, you do not have access to a helpful function <a href=\"https://msdn.microsoft.com/en-gb/library/hh213020.aspx\" rel=\"nofollow\"><code>EOMONTH()</code></a>, So you must calculate this yourself.</p>\n\n<blockquote>\n <p>This simple function will works similar to <strong>EOMONTH</strong></p>\n</blockquote>\n\n<pre><code>CREATE FUNCTION dbo.endofmonth(@date DATETIME= NULL)\nRETURNS DATETIME\nBEGIN\nRETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(@date,GETDATE())), ISNULL(@date,GETDATE()))))\nEND\n</code></pre>\n\n<p><strong>Query to perform:</strong></p>\n\n<pre><code>SELECT dbo.endofmonth(DEFAULT) --Current month-end date\nSELECT dbo.endofmonth('02/25/2012') --User-defined month-end date\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7577/"
] |
Specifically MSSQL 2005.
|
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
```
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
```
To understand how it works we have to look at the [dateadd()](http://www.w3schools.com/sql/func_dateadd.asp) and [datediff()](http://www.w3schools.com/sql/func_datediff.asp) functions.
```
DATEADD(datepart, number, date)
DATEDIFF(datepart, startdate, enddate)
```
If you run just the most inner call to datediff(), you get the current month number since timestamp 0.
```
select datediff(m, 0, getdate() );
1327
```
The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.
```
select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000
```
Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.
```
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000
```
---
**This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.**
Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.
```
dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
```
|
182,865 |
<p>I'm using Test/Unit with a standard <strong>rails 2.1</strong> project. I would like to be able to test Partial Views in isolation from any particular controller / action.</p>
<p>It seemed as though <a href="http://zentest.rubyforge.org/" rel="noreferrer">ZenTest's Test::Rails::ViewTestCase</a> would help, but I couldn't get it working, similarly with view_test <a href="http://www.continuousthinking.com/tags/view_test" rel="noreferrer">http://www.continuousthinking.com/tags/view_test</a> </p>
<p>Most of the stuff Google turns up seems quite out of date, so I'm guessing doesn't really work with Rails 2.1</p>
<p>Any help with this much appreciated.</p>
<p>Thanks,
Roland</p>
|
[
{
"answer_id": 183980,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": -1,
"selected": false,
"text": "<p>Testing a view without the controller code is a dangerous thing. Your tests might pass but your application might throw an error. Always test against real life situations not artificial ones.</p>\n"
},
{
"answer_id": 189607,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "<p>We're using <a href=\"http://rspec.info\" rel=\"noreferrer\">RSpec</a> in our Rails 2.1 project, and we can do this sort of thing:</p>\n\n<pre><code>describe \"/posts/_form\" do\n before do\n render :partial => \"posts/form\"\n end\n it \"says hello\" do\n response.should match(/hello/i)\n end\n it \"renders a form\" do\n response.should have_tag(\"form\")\n end\nend\n</code></pre>\n\n<p>However I don't know how much of that you can do with the vanilla Rails testing apparatus.</p>\n"
},
{
"answer_id": 225037,
"author": "Roland",
"author_id": 15965,
"author_profile": "https://Stackoverflow.com/users/15965",
"pm_score": 1,
"selected": false,
"text": "<p>Found this which may be relevant:</p>\n\n<p><a href=\"http://broadcast.oreilly.com/2008/10/testing-rails-partials.html\" rel=\"nofollow noreferrer\">http://broadcast.oreilly.com/2008/10/testing-rails-partials.html</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15965/"
] |
I'm using Test/Unit with a standard **rails 2.1** project. I would like to be able to test Partial Views in isolation from any particular controller / action.
It seemed as though [ZenTest's Test::Rails::ViewTestCase](http://zentest.rubyforge.org/) would help, but I couldn't get it working, similarly with view\_test <http://www.continuousthinking.com/tags/view_test>
Most of the stuff Google turns up seems quite out of date, so I'm guessing doesn't really work with Rails 2.1
Any help with this much appreciated.
Thanks,
Roland
|
We're using [RSpec](http://rspec.info) in our Rails 2.1 project, and we can do this sort of thing:
```
describe "/posts/_form" do
before do
render :partial => "posts/form"
end
it "says hello" do
response.should match(/hello/i)
end
it "renders a form" do
response.should have_tag("form")
end
end
```
However I don't know how much of that you can do with the vanilla Rails testing apparatus.
|
182,872 |
<p>What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List<String>?</p>
<p>Consider this snippet:</p>
<pre><code>public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> method2();
public StringList method3();
</code></pre>
<p>All methods 1, 2, 3 fulfill the requirement. It's quite easy to test it for the method1 (via getGenericReturnType(), which returns instance of ParameterizedType), but for methods2 and 3, it's not so obvious. I imagine, that by traversing all getGenericSuperclass() and getGenericInterfaces(), we can get quite close, but I don't see, how to match the TypeVariable in List<E> (which occurs somewhere in the superclass interfaces) with the actual type parameter (i.e. where this E is matched to String).</p>
<p>Or maybe is there a completely different (easier) way, which I overlook?</p>
<p><strong>EDIT:</strong> For those looking into it, here is method4, which also fulfills the requirement and which shows some more cases, which have to be investigated:</p>
<pre><code>public interface Parametrized<T extends StringList> {
T method4();
}
</code></pre>
|
[
{
"answer_id": 183232,
"author": "Jasper",
"author_id": 18702,
"author_profile": "https://Stackoverflow.com/users/18702",
"pm_score": 3,
"selected": false,
"text": "<p>I tried this code and it returns the actual generic type class so it seems the type info can be retrieved. However this only works for method 1 and 2. Method 3 does not seem to return a list typed String as the poster assumes and therefore fails.</p>\n\n<pre><code>public class Main {\n/**\n * @param args the command line arguments\n */\npublic static void main(String[] args) {\n try{\n Method m = Main.class.getDeclaredMethod(\"method1\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method2\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method3\", new Class[]{});\n instanceOf(m, List.class, String.class);\n m = Main.class.getDeclaredMethod(\"method4\", new Class[]{});\n instanceOf(m, StringList.class);\n }catch(Exception e){\n System.err.println(e.toString());\n }\n}\n\npublic static boolean instanceOf (\n Method m, \n Class<?> returnedBaseClass, \n Class<?> ... genericParameters) {\n System.out.println(\"Testing method: \" + m.getDeclaringClass().getName()+\".\"+ m.getName());\n boolean instanceOf = false;\n instanceOf = returnedBaseClass.isAssignableFrom(m.getReturnType());\n System.out.println(\"\\tReturn type test succesfull: \" + instanceOf + \" (expected '\"+returnedBaseClass.getName()+\"' found '\"+m.getReturnType().getName()+\"')\");\n System.out.print(\"\\tNumber of generic parameters matches: \");\n Type t = m.getGenericReturnType();\n if(t instanceof ParameterizedType){\n ParameterizedType pt = (ParameterizedType)t;\n Type[] actualGenericParameters = pt.getActualTypeArguments();\n instanceOf = instanceOf\n && actualGenericParameters.length == genericParameters.length;\n System.out.println(\"\" + instanceOf + \" (expected \"+ genericParameters.length +\", found \" + actualGenericParameters.length+\")\");\n for (int i = 0; instanceOf && i < genericParameters.length; i++) {\n if (actualGenericParameters[i] instanceof Class) {\n instanceOf = instanceOf\n && genericParameters[i].isAssignableFrom(\n (Class) actualGenericParameters[i]);\n System.out.println(\"\\tGeneric parameter no. \" + (i+1) + \" matches: \" + instanceOf + \" (expected '\"+genericParameters[i].getName()+\"' found '\"+((Class) actualGenericParameters[i]).getName()+\"')\");\n } else {\n instanceOf = false;\n System.out.println(\"\\tFailure generic parameter is not a class\");\n }\n }\n } else {\n System.out.println(\"\" + true + \" 0 parameters\");\n }\n return instanceOf;\n}\npublic List<String> method1() {\n return null;\n}\npublic ArrayList<String> method2() {\n return new ArrayList<String>();\n}\npublic StringList method3() {\n return null;\n}\npublic <T extends StringList> T method4() {\n return null;\n}\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre>\nTesting method: javaapplication2.Main.method1\n Return type test succesfull: true (expected 'java.util.List' found 'java.util.List')\n Number of generic parameters matches: true (expected 1, found 1)\n Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')\nTesting method: javaapplication2.Main.method2\n Return type test succesfull: true (expected 'java.util.List' found 'java.util.ArrayList')\n Number of generic parameters matches: true (expected 1, found 1)\n Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')\nTesting method: javaapplication2.Main.method3\n Return type test succesfull: false (expected 'java.util.List' found 'com.sun.org.apache.xerces.internal.xs.StringList')\n Number of generic parameters matches: true 0 parameters\nTesting method: javaapplication2.Main.method4\n Return type test succesfull: true (expected 'com.sun.org.apache.xerces.internal.xs.StringList' found 'com.sun.org.apache.xerces.internal.xs.StringList')\n Number of generic parameters matches: true 0 parameters\n</pre>\n"
},
{
"answer_id": 183452,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://forums.java.net/jive/thread.jspa?threadID=47527&tstart=0\" rel=\"nofollow noreferrer\" title=\"Generics and getting the actual type ...\">This thread</a> on the java.net forums might be helpful (although I have to admit I didn't understand everything they said).</p>\n"
},
{
"answer_id": 189511,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are already on the right track. Just keep using <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getGenericSuperclass()\" rel=\"nofollow noreferrer\">getGenericSuperclass()</a> and getGenericInterface() until you start getting parameterized types back...</p>\n\n<p>So basically:</p>\n\n<pre><code>//For string list\nParameterizedType type = (ParameterizedType)StringList.class.getGenericSuperclass();\nSystem.out.println( type.getActualTypeArguments()[0] );\n\n//for a descendant of string list\nClass clazz = (Class)StringListChild.class.getGenericSuperclass();\nParameterizedType type = (ParameterizedType)clazz.getGenericSuperclass();\nSystem.out.println( type.getActualTypeArguments()[0] );\n</code></pre>\n\n<p>You'd want to build something that was recursive that would check for this--maybe even go up the chain looking for java.util.List.</p>\n"
},
{
"answer_id": 405594,
"author": "Wouter Coekaerts",
"author_id": 3432,
"author_profile": "https://Stackoverflow.com/users/3432",
"pm_score": 3,
"selected": true,
"text": "<p>Solving this in general is really not easy to do yourself using only the tools provided by Java itself. There are a lot of special cases (nested classes, type parameter bounds,...) to take care of.\nThat's why I wrote a library to make generic type reflection easier: <a href=\"http://code.google.com/p/gentyref/\" rel=\"nofollow noreferrer\">gentyref</a>. I added sample code (in the form of a JUnit test) to show how to use it to solve this problem: <a href=\"http://code.google.com/p/gentyref/source/browse/trunk/gentyref/src/test/java/com/googlecode/gentyref/StackoverflowQ182872Test.java\" rel=\"nofollow noreferrer\">StackoverflowQ182872Test.java</a>. Basically, you just call <code>GenericTypeReflector.isSuperType</code> using a <code>TypeToken</code> (idea from <a href=\"http://gafter.blogspot.com/2006/12/super-type-tokens.html\" rel=\"nofollow noreferrer\">Neil Gafter</a>) to see if <code>List<String></code> is a supertype of the return type.</p>\n\n<p>I also added a 5th test case, to show that an extra transformation on the return type (<code>GenericTypeReflector.getExactReturnType</code>) to replace type parameters with their values is sometimes needed.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7135/"
] |
What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List<String>?
Consider this snippet:
```
public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> method2();
public StringList method3();
```
All methods 1, 2, 3 fulfill the requirement. It's quite easy to test it for the method1 (via getGenericReturnType(), which returns instance of ParameterizedType), but for methods2 and 3, it's not so obvious. I imagine, that by traversing all getGenericSuperclass() and getGenericInterfaces(), we can get quite close, but I don't see, how to match the TypeVariable in List<E> (which occurs somewhere in the superclass interfaces) with the actual type parameter (i.e. where this E is matched to String).
Or maybe is there a completely different (easier) way, which I overlook?
**EDIT:** For those looking into it, here is method4, which also fulfills the requirement and which shows some more cases, which have to be investigated:
```
public interface Parametrized<T extends StringList> {
T method4();
}
```
|
Solving this in general is really not easy to do yourself using only the tools provided by Java itself. There are a lot of special cases (nested classes, type parameter bounds,...) to take care of.
That's why I wrote a library to make generic type reflection easier: [gentyref](http://code.google.com/p/gentyref/). I added sample code (in the form of a JUnit test) to show how to use it to solve this problem: [StackoverflowQ182872Test.java](http://code.google.com/p/gentyref/source/browse/trunk/gentyref/src/test/java/com/googlecode/gentyref/StackoverflowQ182872Test.java). Basically, you just call `GenericTypeReflector.isSuperType` using a `TypeToken` (idea from [Neil Gafter](http://gafter.blogspot.com/2006/12/super-type-tokens.html)) to see if `List<String>` is a supertype of the return type.
I also added a 5th test case, to show that an extra transformation on the return type (`GenericTypeReflector.getExactReturnType`) to replace type parameters with their values is sometimes needed.
|
182,876 |
<p>Often, I found OutOfMemoryException on IBM Websphere Application Server.
I think this exception occur because my application retrieve Huge data from database. So, I limit all query don't retreive data more than 1000 records and set JVM of WAS follow</p>
<pre><code>+ Verbose garbage collection
+ Maximum Heap size = 1024 (RAM on my server is 16 GB and now I already change to 8192)
+ Debug arguments = -Djava.compiler=NONE -Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777
+ Generic JVM arguments = -Dsun.rmi.dgc.server.gcInterval=60000
-Dsun.rmi.dgc.client.gcInterval=60000 -Xdisableexplicitgc
-Dws.log=E:\WebApp\log -Dws.log.level=debug
(ws.log and ws.log.level are my properties)
</code></pre>
<p>And I found <strong>heapdump</strong>, <strong>javacore</strong> and <strong>snap</strong> files in profiles folder I think them can tell me about cause of problem but I don't know how to read/use heapdump, javacore and snap files.</p>
<p>Please tell me how to prevent/avoid/fix OutOfMemoryException.
Thanks</p>
|
[
{
"answer_id": 183082,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 2,
"selected": true,
"text": "<p>The answer to this is dependent on the message associated with the OutOfMemoryException. You can also try -XX:MaxPermSize=... and set it to something larger like 256m.</p>\n\n<p>Also, if you have a recursive function somewhere, that may be causing a stack overflow. </p>\n\n<p>If you can, please post the message associated with the exception. Stacktrace might also help.</p>\n"
},
{
"answer_id": 183144,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to look at the heap dump files, IBM offers tools to analyze them <a href=\"http://publib.boulder.ibm.com/infocenter/tivihelp/v3r1/index.jsp?topic=/com.ibm.itcamwas_b.doc_6.1/pdmst_basic56.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 183842,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 0,
"selected": false,
"text": "<p>Try to reproduce the problem locally so you can use a tool like JProfiler to debug it. Even if you can't force an OOM locally, chances are you'll see the memory increase in JProfiler. Then you take snapshots and look for classes that aren't being garbage collected. It's not an exact science, but it's much easier than looking through an IBM heapdump. However, if you have to, the old way of examining a heap dump was with HeapRoots. It may depend on the version you're on. I do know that some versions of the IBM JDK have problems with compacting so even if you have plenty of memory, you can get an OOM because there's not a large enough fragment available.</p>\n"
},
{
"answer_id": 187718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I assume your using hibernate/JPA as a persistence provider? Are you using a second level cache? If so have you considered evicting large results sets from the cache?</p>\n"
},
{
"answer_id": 189591,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 0,
"selected": false,
"text": "<p>The question is hard to answer if we don't know what <em>kind</em> of OutOfMemoryError it is; <code>permgen</code> and <code>heapspace</code> are two very different beasts.</p>\n\n<p>I was chasing a perm-gen for many months on JBoss, though the that particular type of problem was general to any application server that reloaded web applications on the fly. The saga is documented <a href=\"http://my.opera.com/karmazilla/blog/2008/08/31/permgen-our-workable-solution\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Those heap-dumps you have... could be that you can analyze them in <a href=\"http://www.eclipse.org/mat/\" rel=\"nofollow noreferrer\">Eclipse MAT</a>.</p>\n"
},
{
"answer_id": 881524,
"author": "dertoni",
"author_id": 65967,
"author_profile": "https://Stackoverflow.com/users/65967",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.ibm.com/developerworks/linux/library/j-nativememory-linux/index.html?ca=dgr-jw22Linux-JVM&S%5FTACT=105AGX59&S%5FCMP=grjw22\" rel=\"nofollow noreferrer\">\"Thanks for the memory\"</a> is a good article about the JVMs use of memory, which might help to analyse this problem...</p>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/15375/bwalliser\">bwalliser</a> for this link</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
Often, I found OutOfMemoryException on IBM Websphere Application Server.
I think this exception occur because my application retrieve Huge data from database. So, I limit all query don't retreive data more than 1000 records and set JVM of WAS follow
```
+ Verbose garbage collection
+ Maximum Heap size = 1024 (RAM on my server is 16 GB and now I already change to 8192)
+ Debug arguments = -Djava.compiler=NONE -Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777
+ Generic JVM arguments = -Dsun.rmi.dgc.server.gcInterval=60000
-Dsun.rmi.dgc.client.gcInterval=60000 -Xdisableexplicitgc
-Dws.log=E:\WebApp\log -Dws.log.level=debug
(ws.log and ws.log.level are my properties)
```
And I found **heapdump**, **javacore** and **snap** files in profiles folder I think them can tell me about cause of problem but I don't know how to read/use heapdump, javacore and snap files.
Please tell me how to prevent/avoid/fix OutOfMemoryException.
Thanks
|
The answer to this is dependent on the message associated with the OutOfMemoryException. You can also try -XX:MaxPermSize=... and set it to something larger like 256m.
Also, if you have a recursive function somewhere, that may be causing a stack overflow.
If you can, please post the message associated with the exception. Stacktrace might also help.
|
182,891 |
<p>Does anyone have an XSLT that will take the app.config and render it into a non-techie palatable format?</p>
<p>The purpose being mainly informational, but with the nice side-effect of validating the XML (if it's been made invalid, it won't render)</p>
|
[
{
"answer_id": 183060,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>What type of conversion are you looking for? Just for informational purposes? What level of detail are you looking to transform?</p>\n"
},
{
"answer_id": 203485,
"author": "Don Vince",
"author_id": 6023,
"author_profile": "https://Stackoverflow.com/users/6023",
"pm_score": 3,
"selected": true,
"text": "<p>First draft at a solution to show</p>\n\n<ul>\n<li>Connection Strings</li>\n<li>App Settings</li>\n</ul>\n\n<p>Whack this in the app.config:</p>\n\n<pre><code><?xml-stylesheet type=\"text/xsl\" href=\"display-config.xslt\"?>\n</code></pre>\n\n<p>And this is the contents of display-config.xslt:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:template match=\"/\">\n <html>\n <body>\n <h2>Settings</h2> \n <xsl:apply-templates /> \n </body>\n </html>\n </xsl:template> \n\n\n <xsl:template match=\"connectionStrings\">\n <h3>Connection Strings</h3>\n <table border=\"1\">\n <tr bgcolor=\"#abcdef\">\n <th align=\"left\">Name</th>\n <th align=\"left\">Connection String</th>\n </tr>\n <xsl:for-each select=\"add\">\n <tr>\n <td><xsl:value-of select=\"@name\"/></td>\n <td><xsl:value-of select=\"@connectionString\"/></td>\n </tr>\n </xsl:for-each>\n </table>\n </xsl:template>\n\n\n <xsl:template match=\"appSettings\">\n <h3>Settings</h3>\n <table border=\"1\">\n <tr bgcolor=\"#abcdef\">\n <th align=\"left\">Key</th>\n <th align=\"left\">Value</th>\n </tr>\n <xsl:for-each select=\"add\">\n <tr>\n <td><xsl:value-of select=\"@key\"/></td>\n <td><xsl:value-of select=\"@value\"/></td>\n </tr>\n </xsl:for-each>\n </table>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] |
Does anyone have an XSLT that will take the app.config and render it into a non-techie palatable format?
The purpose being mainly informational, but with the nice side-effect of validating the XML (if it's been made invalid, it won't render)
|
First draft at a solution to show
* Connection Strings
* App Settings
Whack this in the app.config:
```
<?xml-stylesheet type="text/xsl" href="display-config.xslt"?>
```
And this is the contents of display-config.xslt:
```
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Settings</h2>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="connectionStrings">
<h3>Connection Strings</h3>
<table border="1">
<tr bgcolor="#abcdef">
<th align="left">Name</th>
<th align="left">Connection String</th>
</tr>
<xsl:for-each select="add">
<tr>
<td><xsl:value-of select="@name"/></td>
<td><xsl:value-of select="@connectionString"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
<xsl:template match="appSettings">
<h3>Settings</h3>
<table border="1">
<tr bgcolor="#abcdef">
<th align="left">Key</th>
<th align="left">Value</th>
</tr>
<xsl:for-each select="add">
<tr>
<td><xsl:value-of select="@key"/></td>
<td><xsl:value-of select="@value"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
```
|
182,928 |
<p>we have a template project we often copy. so we can costumize the copy and still have a common template.<br></p>
<p>To optimize the "copy & initial changes"-process, i though that i can write a little script, that does the following:</p>
<ul>
<li>copy the project-template (in svn) to another directory in the svn</li>
<li>check-out the project and do some changes (change names in some files)</li>
<li>check-in the customized project</li>
</ul>
<p>The question is: what's the best way to do this? any experience in this? which type of script (normal batch or java)? any example code?</p>
<p>thanks for your answers</p>
|
[
{
"answer_id": 183031,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": -1,
"selected": false,
"text": "<p>Just a shell script would do.</p>\n"
},
{
"answer_id": 183056,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 1,
"selected": true,
"text": "<p>Here is something i put together with some information i found <a href=\"http://forums.devshed.com/unix-help-35/unix-find-and-replace-text-within-all-files-within-a-146179.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>#!/bin/bash\n\n\nsearchterm=\"<ProjectName>\"\nreplaceterm=\"New Project\"\nsrcsvnrepo=\"file:///svnrepoaddress\"\ndestsvnrepo=\"file:///data/newrepo\"\ndumpfile=\"/home/<user>/repo.dump\"\ntmpfolder=\"/home/<user>/tmp_repo\"\n\nsvnadmin dump $srcsvnrepo > $dumpfile\nsvnadmin create --fs-type fsfs $destsvnrepo\nsvnadmin load $destsvnrepo < $dumpfile\nsvn co $destsvnrepo $tmpfolder\n\nfor file in $(grep -l -R $searchterm $tmpfolder)\n do\n sed -e \"s/$searchterm/$replaceterm/ig\" $file > /tmp/tempfile.tmp\n mv /tmp/tempfile.tmp $file\n echo \"Modified: \" $file\n done\n\nsvn ci $tmpfolder --message \"Initial Check-In\"\n</code></pre>\n\n<p>Basically this will dump a backup of the specified source svn repo to a file, create a new repo, load the backup into it, check out the files, get a list of files that contain the string to search for, perform a regex on each of those files storing the new version in a temp location and then moving the temp file back to the original location, and finally checking the changes back into the new repo.</p>\n\n<p>I haven't fully tested this so some minor tweaking may be necessary, but the basic steps should be correct. Please let me know if i've made some gross miscalculation and this totally does not work.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25730/"
] |
we have a template project we often copy. so we can costumize the copy and still have a common template.
To optimize the "copy & initial changes"-process, i though that i can write a little script, that does the following:
* copy the project-template (in svn) to another directory in the svn
* check-out the project and do some changes (change names in some files)
* check-in the customized project
The question is: what's the best way to do this? any experience in this? which type of script (normal batch or java)? any example code?
thanks for your answers
|
Here is something i put together with some information i found [here](http://forums.devshed.com/unix-help-35/unix-find-and-replace-text-within-all-files-within-a-146179.html).
```
#!/bin/bash
searchterm="<ProjectName>"
replaceterm="New Project"
srcsvnrepo="file:///svnrepoaddress"
destsvnrepo="file:///data/newrepo"
dumpfile="/home/<user>/repo.dump"
tmpfolder="/home/<user>/tmp_repo"
svnadmin dump $srcsvnrepo > $dumpfile
svnadmin create --fs-type fsfs $destsvnrepo
svnadmin load $destsvnrepo < $dumpfile
svn co $destsvnrepo $tmpfolder
for file in $(grep -l -R $searchterm $tmpfolder)
do
sed -e "s/$searchterm/$replaceterm/ig" $file > /tmp/tempfile.tmp
mv /tmp/tempfile.tmp $file
echo "Modified: " $file
done
svn ci $tmpfolder --message "Initial Check-In"
```
Basically this will dump a backup of the specified source svn repo to a file, create a new repo, load the backup into it, check out the files, get a list of files that contain the string to search for, perform a regex on each of those files storing the new version in a temp location and then moving the temp file back to the original location, and finally checking the changes back into the new repo.
I haven't fully tested this so some minor tweaking may be necessary, but the basic steps should be correct. Please let me know if i've made some gross miscalculation and this totally does not work.
|
182,945 |
<p>I've committed changes in numerous files to a SVN repository from Eclipse.</p>
<p>I then go to website directory on the linux box where I want to update these changes from the repository to the directory there.</p>
<p>I want to say "svn update project100" which will update the directories under "project100" with all my added and changed files, etc.</p>
<p>HOWEVER, I don't want to necessarily update changes that I didn't make.
So I thought I could say "svn status project100" but when I do this I get a totally different list of changes that will be made, none of mine are in the list, which is odd.</p>
<p>Hence to be sure that only my changes are updated to the web directory, I am forced to navigate to every directory where I know there is a change that I made and explicitly update only those files, e.g. "svn update newfile1.php" etc. which is tedious.</p>
<p>Can anyone shed any light on the standard working procedure here, namely how do I get an accurate list of all the changes that are about to be made before I execute the "svn update" command? I thought it was the "status" command.</p>
|
[
{
"answer_id": 182960,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 6,
"selected": false,
"text": "<p>You can see what will updated (without actually updating) by issuing:</p>\n\n<pre><code>svn merge --dry-run -r BASE:HEAD .\n</code></pre>\n\n<p>More details <a href=\"http://translocator.ws/2005/10/12/svn-update-dry-run\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 182964,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": -1,
"selected": false,
"text": "<p>You can use 'svn diff' to see the difference between your working copy and the repository.</p>\n"
},
{
"answer_id": 182966,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 8,
"selected": true,
"text": "<p>Try:</p>\n\n<pre><code>svn status --show-updates\n</code></pre>\n\n<p>or (the same but shorter):</p>\n\n<pre><code>svn status -u\n</code></pre>\n"
},
{
"answer_id": 183003,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 0,
"selected": false,
"text": "<p>In theory you could make all your changes in a branch which you created for your own use. \nYou would then be reasonably sure that you were the only one committing to it.</p>\n\n<p>IMHO feature development should be done like this.</p>\n\n<p>Then you could update this target machine from this branch instead of from the trunk.</p>\n"
},
{
"answer_id": 4997135,
"author": "Jeff",
"author_id": 616827,
"author_profile": "https://Stackoverflow.com/users/616827",
"pm_score": 4,
"selected": false,
"text": "<p>This is what I was looking for. Checked Google first, but <code>svn help</code> ended up coming through for me :)</p>\n\n<pre><code>svn diff -r BASE:HEAD .\n</code></pre>\n"
},
{
"answer_id": 7157966,
"author": "Kenzo",
"author_id": 1952147,
"author_profile": "https://Stackoverflow.com/users/1952147",
"pm_score": 4,
"selected": false,
"text": "<p>The same but shorter shorter :) :</p>\n\n<pre><code>svn st -u\n</code></pre>\n"
},
{
"answer_id": 13292998,
"author": "TianCaiBenBen",
"author_id": 1521200,
"author_profile": "https://Stackoverflow.com/users/1521200",
"pm_score": 6,
"selected": false,
"text": "<p>Depending on what you want to know between your working copy and the latest svn\nserver repository, without updating your local working copy, here is what you can\ndo: </p>\n\n<p>if you want to know what has been changed in svn server repository, run\ncommand: </p>\n\n<pre><code>$ svn st -u\n</code></pre>\n\n<p>if you want to know if the same file has been modified both in your local\nworking copy and in svn server repository, run command: </p>\n\n<pre><code>$ svn st -u | grep -E '^M {7}\\*'\n</code></pre>\n\n<p>if you want to get list of files changed between a particular revision and\nHEAD, run command: </p>\n\n<pre><code>$ svn diff -r revisionNumber:HEAD --summarize\n</code></pre>\n\n<p>if you want to get a list of files changed between paticular revisions, run\ncommand: </p>\n\n<pre><code>$ svn diff -r revisionNumber:anotherRevisionNumber --summarize\n</code></pre>\n\n<p>if you want to see what will be updated (without actually updating), run\ncommand: </p>\n\n<pre><code>$ svn merge --dry-run -r BASE:HEAD .\n</code></pre>\n\n<p>if you want to know what content of a particular file has been changed in svn\nserver repository compared with your working copy, run command: </p>\n\n<pre><code>$ svn diff -r BASE:HEAD ./pathToYour/file\n</code></pre>\n\n<p>if you want to know what contents of all the files have been changed in svn\nserver repository compared with your working copy, run command: </p>\n\n<pre><code>$ svn diff -r BASE:HEAD .\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
I've committed changes in numerous files to a SVN repository from Eclipse.
I then go to website directory on the linux box where I want to update these changes from the repository to the directory there.
I want to say "svn update project100" which will update the directories under "project100" with all my added and changed files, etc.
HOWEVER, I don't want to necessarily update changes that I didn't make.
So I thought I could say "svn status project100" but when I do this I get a totally different list of changes that will be made, none of mine are in the list, which is odd.
Hence to be sure that only my changes are updated to the web directory, I am forced to navigate to every directory where I know there is a change that I made and explicitly update only those files, e.g. "svn update newfile1.php" etc. which is tedious.
Can anyone shed any light on the standard working procedure here, namely how do I get an accurate list of all the changes that are about to be made before I execute the "svn update" command? I thought it was the "status" command.
|
Try:
```
svn status --show-updates
```
or (the same but shorter):
```
svn status -u
```
|
182,957 |
<p>im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?</p>
<pre><code>int value = *min_element(v2.begin(), v2.end());
cout << "min value at position " << *find(v2.begin(), v2.end(), value);
</code></pre>
|
[
{
"answer_id": 182973,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p><code>min_element</code> already gives you the iterator, no need to invoke <code>find</code> (additionally, it's inefficient because it's twice the work). Use <code>distance</code> or the <code>-</code> operator:</p>\n\n<pre><code>cout << \"min value at \" << min_element(v2.begin(), v2.end()) - v2.begin();\n</code></pre>\n"
},
{
"answer_id": 183036,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 4,
"selected": false,
"text": "<p>Both algorithms you're using return iterators. If you dereference an iterator, you get the object which is \"pointed\" by this iterator, which is why you print the <em>value</em> and not the <em>position</em> when doing</p>\n\n<blockquote>\n<pre><code>cout << \"min value at position \" << *find(v2.begin(), v2.end(), value);\n</code></pre>\n</blockquote>\n\n<p>An iterator can be seen as a pointer (well, not exactly, but let's say so for the sake of simplicity); therefore, an iterator alone can't give you the position in the container. Since you're iterating a vector, you can use the minus operator, as Konrad said:</p>\n\n<blockquote>\n<pre><code>cout << \"min value at \" << min_element(v2.begin(), v2.end()) - v2.begin();\n</code></pre>\n</blockquote>\n\n<p>but I would recommend using the std::distance algorithm, which is much more flexible and will work on all standard containers:</p>\n\n<blockquote>\n<pre><code>cout << \"min value at \" << distance(v2.begin(), min_element(v2.begin(), v2.end()));\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 186054,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "<p>The short answer to what you think you asked with \"How do I determine position in <code>std::vector<></code> given an iterator from it?\" is the function <code>std::distance</code>.</p>\n\n<p>What you probably meant to do, however, was to get the value for the iterator, which you get by dereferencing it:</p>\n\n<pre><code>using namespace std;\nvector<int>::const_iterator it = min_element(v2.begin(), v2.end());\ncout << \"min value at position \" << distance(v2.begin(), it) << \" is \" << *it;\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8768/"
] |
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min\_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?
```
int value = *min_element(v2.begin(), v2.end());
cout << "min value at position " << *find(v2.begin(), v2.end(), value);
```
|
`min_element` already gives you the iterator, no need to invoke `find` (additionally, it's inefficient because it's twice the work). Use `distance` or the `-` operator:
```
cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
```
|
182,984 |
<p>Files:</p>
<p>Website\Controls\map.ascx</p>
<p>Website\App_Code\map.cs</p>
<p>I'd like to create a strongly typed instance of map.ascx in map.cs</p>
<p>Normally, in an aspx, you would add a <%Register... tag to be able to instantiate in codebehind. Is this possible in an app_code class?
I'm using .NET 3.5/Visual Studio 2008</p>
<p>Thanks!</p>
|
[
{
"answer_id": 182992,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 3,
"selected": true,
"text": "<p>Normally, I'd do something like this (assuming your type is \"Map\" and that you have the appropriate \"Inherits\" declaration in your .ascx file):</p>\n\n<pre><code>Map map = (Map)LoadControl(\"~/Controls/map.ascx\");\n</code></pre>\n"
},
{
"answer_id": 183117,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a map.ascx.cs file in Website\\Controls? If so, move it to App_Code. Note you may have to update the CodeFile attribute in the .ascx file to ~\\App_Code\\map.ascx.cs.\nAlternatively, since the control is a partial class, you could just create the code in ~\\App_Code\\map.cs as:</p>\n\n<pre><code>public partial class controls_Map : UserControl\n{\n protected void Page_Load( object sender, EventArgs e )\n {\n ...code here....\n }\n}\n</code></pre>\n\n<p>And remove all the methods from the map.ascx.cs file in the controls directory.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11831/"
] |
Files:
Website\Controls\map.ascx
Website\App\_Code\map.cs
I'd like to create a strongly typed instance of map.ascx in map.cs
Normally, in an aspx, you would add a <%Register... tag to be able to instantiate in codebehind. Is this possible in an app\_code class?
I'm using .NET 3.5/Visual Studio 2008
Thanks!
|
Normally, I'd do something like this (assuming your type is "Map" and that you have the appropriate "Inherits" declaration in your .ascx file):
```
Map map = (Map)LoadControl("~/Controls/map.ascx");
```
|
182,988 |
<p>I have valid <code>HBITMAP</code> handle of <code>ARGB</code> type. How to draw it using <em>GDI+</em>?</p>
<p>I've tried method:</p>
<pre><code>graphics.DrawImage(Bitmap::FromHBITMAP(m_hBitmap, NULL), 0, 0);
</code></pre>
<p>But it doesn't use alpha channel.</p>
|
[
{
"answer_id": 183029,
"author": "Jeff B",
"author_id": 25879,
"author_profile": "https://Stackoverflow.com/users/25879",
"pm_score": -1,
"selected": false,
"text": "<p>Ah... but .Net doesn't use HBITMAP and GDI+ is a C++ library atop the basic Windows GDI, so I'm assuming you're using non-.Net C++.</p>\n\n<p>GDI+ has a Bitmap class, which has a FromHBITMAP() method.</p>\n\n<p>Once you have the GDI+ Bitmap instance, you can use it with the GDI+ library.</p>\n\n<p>Of course, if you can write your program in C# using .Net it will be a lot easier.</p>\n"
},
{
"answer_id": 183512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I've got working sample:</p>\n<p><em>Get info using bitmap handle: image size, bits</em></p>\n<pre><code>BITMAP bmpInfo; \n::GetObject(m_hBitmap, sizeof(BITMAP), &bmpInfo); \nint cxBitmap = bmpInfo.bmWidth; \nint cyBitmap = bmpInfo.bmHeight; \nvoid* bits = bmpInfo.bmBits; \n</code></pre>\n<p><em>Create & draw new GDI+ bitmap using bits with pixel format PixelFormat32bppARGB</em></p>\n<pre><code>Gdiplus::Graphics graphics(dcMemory); \nGdiplus::Bitmap bitmap(cxBitmap, cyBitmap, cxBitmap*4, PixelFormat32bppARGB, (BYTE*)bits); \ngraphics.DrawImage(&bitmap, 0, 0); \n</code></pre>\n"
},
{
"answer_id": 4606637,
"author": "Ron",
"author_id": 175938,
"author_profile": "https://Stackoverflow.com/users/175938",
"pm_score": 0,
"selected": false,
"text": "<p>I had similar issues getting my transparent channel to work. In my case, I knew what the background color should be used for the transparent area (it was solid). I used the Bitmap.GetHBITMAP(..) method and passed in the background color to be used for the transparent area. This was a much easier solution that other attempts I was trying using LockBits and re-creating the Bitmap with PixelFormat32bppARGB, as well as cloning. In my case, the Bitmap was ignoring the alpha channel since it was created from Bitmap.FromStream.</p>\n\n<p>I also had some very strange problems with the background area of my image being changed slightly. For example, instead of pure white, it was off white like 0xfff7f7. This was the case whether I was using JPG (with blended colors) or with PNG and transparent colors.</p>\n\n<p>See my question and solution at </p>\n\n<p><a href=\"https://stackoverflow.com/questions/4596346/gdi-drawimage-of-a-jpg-with-white-background-is-not-white\">GDI+ DrawImage of a JPG with white background is not white</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have valid `HBITMAP` handle of `ARGB` type. How to draw it using *GDI+*?
I've tried method:
```
graphics.DrawImage(Bitmap::FromHBITMAP(m_hBitmap, NULL), 0, 0);
```
But it doesn't use alpha channel.
|
I've got working sample:
*Get info using bitmap handle: image size, bits*
```
BITMAP bmpInfo;
::GetObject(m_hBitmap, sizeof(BITMAP), &bmpInfo);
int cxBitmap = bmpInfo.bmWidth;
int cyBitmap = bmpInfo.bmHeight;
void* bits = bmpInfo.bmBits;
```
*Create & draw new GDI+ bitmap using bits with pixel format PixelFormat32bppARGB*
```
Gdiplus::Graphics graphics(dcMemory);
Gdiplus::Bitmap bitmap(cxBitmap, cyBitmap, cxBitmap*4, PixelFormat32bppARGB, (BYTE*)bits);
graphics.DrawImage(&bitmap, 0, 0);
```
|
182,993 |
<p>I have the following in my Global.asax.cs</p>
<pre><code>routes.MapRoute(
"Arrival",
"{partnerID}",
new { controller = "Search", action = "Index", partnerID="1000" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
</code></pre>
<p>My SearchController looks like this</p>
<pre><code>public class SearchController : Controller
{
// Display search results
public ActionResult Index(int partnerID)
{
ViewData["partnerID"] = partnerID;
return View();
}
}
</code></pre>
<p>and Index.aspx simply shows ViewData["partnerID"] at the moment.</p>
<p>I have a virtual directory set up in IIS on Windows XP called Test.</p>
<p>If I point my browser at <a href="http://localhost/Test/" rel="noreferrer">http://localhost/Test/</a> then I get 1000 displayed as expected. However, if I try <a href="http://localhost/Test/1000" rel="noreferrer">http://localhost/Test/1000</a> I get a page not found error. Any ideas?</p>
<p>Are there any special considerations for running MVC in a virtual directory?</p>
|
[
{
"answer_id": 183008,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 1,
"selected": false,
"text": "<p>There are a number of considerations when using virtual directories in your application. </p>\n\n<p>One is particular is that most browsers will not submit cookies that came from one virtual directory to another, even if the apps reside on the same server. </p>\n"
},
{
"answer_id": 184033,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 1,
"selected": false,
"text": "<p>Try set virtual path: right click on mvc project, properties, web tab, there enter appropriate location.</p>\n"
},
{
"answer_id": 194034,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing this on Windows XP, then you're using IIS 5.1. You need to get ASP.Net to handle your request. You need to either add an extension to your routes ({controller}.mvc/{action}/{id}) and map that extension to ASP.Net or map all requests to ASP.Net. The <a href=\"http://localhost/Test\" rel=\"nofollow noreferrer\">http://localhost/Test</a> works because it goes to Default.aspx which is handled specially in MVC projects.</p>\n\n<p>Additionally, you need to specify <a href=\"http://localhost/Test/Search/Index/1000\" rel=\"nofollow noreferrer\">http://localhost/Test/Search/Index/1000</a>. The controller and action pieces are not optional if you want to specify an ID.</p>\n"
},
{
"answer_id": 237830,
"author": "Amith George",
"author_id": 30007,
"author_profile": "https://Stackoverflow.com/users/30007",
"pm_score": 3,
"selected": true,
"text": "<p>IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so?</p>\n\n<blockquote>\n <p>This happens because IIS 6 only\n invokes ASP.NET when it sees a\n “filename extension” in the URL that’s\n mapped to aspnet_isapi.dll (which is a\n C/C++ ISAPI filter responsible for\n invoking ASP.NET). Since routing is a\n .NET IHttpModule called\n UrlRoutingModule, it doesn’t get\n invoked unless ASP.NET itself gets\n invoked, which only happens when\n aspnet_isapi.dll gets invoked, which\n only happens when there’s a .aspx in\n the URL. So, no .aspx, no\n UrlRoutingModule, hence the 404.</p>\n</blockquote>\n\n<p>Easiest solution is:</p>\n\n<blockquote>\n <p>If you don’t mind having .aspx in your\n URLs, just go through your routing\n config, adding .aspx before a\n forward-slash in each pattern. For\n example, use\n {controller}.aspx/{action}/{id} or\n myapp.aspx/{controller}/{action}/{id}.\n Don’t put .aspx inside the\n curly-bracket parameter names, or into\n the ‘default’ values, because it isn’t\n really part of the controller name -\n it’s just in the URL to satisfy IIS.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/\" rel=\"nofollow noreferrer\">http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/182993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4431/"
] |
I have the following in my Global.asax.cs
```
routes.MapRoute(
"Arrival",
"{partnerID}",
new { controller = "Search", action = "Index", partnerID="1000" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
```
My SearchController looks like this
```
public class SearchController : Controller
{
// Display search results
public ActionResult Index(int partnerID)
{
ViewData["partnerID"] = partnerID;
return View();
}
}
```
and Index.aspx simply shows ViewData["partnerID"] at the moment.
I have a virtual directory set up in IIS on Windows XP called Test.
If I point my browser at <http://localhost/Test/> then I get 1000 displayed as expected. However, if I try <http://localhost/Test/1000> I get a page not found error. Any ideas?
Are there any special considerations for running MVC in a virtual directory?
|
IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so?
>
> This happens because IIS 6 only
> invokes ASP.NET when it sees a
> “filename extension” in the URL that’s
> mapped to aspnet\_isapi.dll (which is a
> C/C++ ISAPI filter responsible for
> invoking ASP.NET). Since routing is a
> .NET IHttpModule called
> UrlRoutingModule, it doesn’t get
> invoked unless ASP.NET itself gets
> invoked, which only happens when
> aspnet\_isapi.dll gets invoked, which
> only happens when there’s a .aspx in
> the URL. So, no .aspx, no
> UrlRoutingModule, hence the 404.
>
>
>
Easiest solution is:
>
> If you don’t mind having .aspx in your
> URLs, just go through your routing
> config, adding .aspx before a
> forward-slash in each pattern. For
> example, use
> {controller}.aspx/{action}/{id} or
> myapp.aspx/{controller}/{action}/{id}.
> Don’t put .aspx inside the
> curly-bracket parameter names, or into
> the ‘default’ values, because it isn’t
> really part of the controller name -
> it’s just in the URL to satisfy IIS.
>
>
>
Source: <http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/>
|
183,013 |
<p>I want to compare the current value of an in-memory Hibernate entity with the value in the database:</p>
<pre><code>HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
sess.update(newEntity);
</code></pre>
<p>In <strong>CODEBLOCK#1</strong> I get that <code>newEntity.getProperty()="new value"</code> AND <code>oldEntity.getProperty()="new value"</code> (while I expected <code>oldEntity.getProperty()="old value"</code>, of course). In fact the two objects are exactly the same in memory.</p>
<p>I messed around with <code>HibernateSessionFactory.getSession().evict(newEntity)</code> and attempted to set <code>oldEntity=null</code> to get rid of it (I need it only for the comparison):</p>
<pre><code>HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
HibernateSessionFactory.getSession().evict(newEntity);
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
oldEntity = null;
sess.update(newEntity);
</code></pre>
<p>and now the two entities are distinct, but of course I get the dreaded <code>org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session</code>.</p>
<p>Any idea?</p>
<p><strong>EDIT:</strong> I tried the double session strategy; I modified my <code>HibernateSessionFactory</code> to implement a map of session and then...</p>
<pre><code>Session session1 = HibernateSessionFactory.getSession(SessionKeys.DEFAULT);
Session session2 = HibernateSessionFactory.getSession(SessionKeys.ALTERNATE);
Entity newEntity = (Entity)entity;
newEntity.setNote("edited note");
Entity oldEntity = (Entity)session1.load(Entity.class, id);
System.out.println("NEW:" + newEntity.getNote());
System.out.println("OLD: " + oldEntity.getNote()); // HANGS HERE!!!
HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE);
</code></pre>
<p>My unit test hangs while attempting to print the oldEntity note... :-(</p>
|
[
{
"answer_id": 183808,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 0,
"selected": false,
"text": "<p>What about using session.isDirty()? The JavaDoc says that method will answer the question \"Would any SQL be executed if we flushed this session?\" Of course, that would only work if you had a new clean Session to start with. Another option - just use two different Sessions.</p>\n"
},
{
"answer_id": 186561,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 4,
"selected": true,
"text": "<p>Two easy options spring to mind:</p>\n\n<ol>\n<li>Evict oldEntity before saving newEntity</li>\n<li>Use session.merge() on oldEntity to replace the version in the session cache (newEntity) with the original (oldEntity)</li>\n</ol>\n\n<p><strong>EDIT</strong>: to elaborate a little, the problem here is that Hibernate keeps a persistence context, which is the objects being monitored as part of each session. You can't do update() on a detached object (one not in the context) while there's an attached object in the context. This should work:</p>\n\n<pre><code>HibernateSession sess = ...;\nMyEntity oldEntity = (MyEntity) sess.load(...);\nsess.evict(oldEntity); // old is now not in the session's persistence context\nMyEntity newEntity = (MyEntity) sess.load(...); // new is the only one in the context now\nnewEntity.setProperty(\"new value\");\n// Evaluate differences\nsess.update(newEntity); // saving the one that's in the context anyway = fine\n</code></pre>\n\n<p>and so should this:</p>\n\n<pre><code>HibernateSession sess = ...;\nMyEntity newEntity = (MyEntity) sess.load(...);\nnewEntity.setProperty(\"new value\");\nsess.evict(newEntity); // otherwise load() will return the same object again from the context\nMyEntity oldEntity = (MyEntity) sess.load(...); // fresh copy into the context\nsess.merge(newEntity); // replaces old in the context with this one\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] |
I want to compare the current value of an in-memory Hibernate entity with the value in the database:
```
HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
sess.update(newEntity);
```
In **CODEBLOCK#1** I get that `newEntity.getProperty()="new value"` AND `oldEntity.getProperty()="new value"` (while I expected `oldEntity.getProperty()="old value"`, of course). In fact the two objects are exactly the same in memory.
I messed around with `HibernateSessionFactory.getSession().evict(newEntity)` and attempted to set `oldEntity=null` to get rid of it (I need it only for the comparison):
```
HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
HibernateSessionFactory.getSession().evict(newEntity);
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
oldEntity = null;
sess.update(newEntity);
```
and now the two entities are distinct, but of course I get the dreaded `org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session`.
Any idea?
**EDIT:** I tried the double session strategy; I modified my `HibernateSessionFactory` to implement a map of session and then...
```
Session session1 = HibernateSessionFactory.getSession(SessionKeys.DEFAULT);
Session session2 = HibernateSessionFactory.getSession(SessionKeys.ALTERNATE);
Entity newEntity = (Entity)entity;
newEntity.setNote("edited note");
Entity oldEntity = (Entity)session1.load(Entity.class, id);
System.out.println("NEW:" + newEntity.getNote());
System.out.println("OLD: " + oldEntity.getNote()); // HANGS HERE!!!
HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE);
```
My unit test hangs while attempting to print the oldEntity note... :-(
|
Two easy options spring to mind:
1. Evict oldEntity before saving newEntity
2. Use session.merge() on oldEntity to replace the version in the session cache (newEntity) with the original (oldEntity)
**EDIT**: to elaborate a little, the problem here is that Hibernate keeps a persistence context, which is the objects being monitored as part of each session. You can't do update() on a detached object (one not in the context) while there's an attached object in the context. This should work:
```
HibernateSession sess = ...;
MyEntity oldEntity = (MyEntity) sess.load(...);
sess.evict(oldEntity); // old is now not in the session's persistence context
MyEntity newEntity = (MyEntity) sess.load(...); // new is the only one in the context now
newEntity.setProperty("new value");
// Evaluate differences
sess.update(newEntity); // saving the one that's in the context anyway = fine
```
and so should this:
```
HibernateSession sess = ...;
MyEntity newEntity = (MyEntity) sess.load(...);
newEntity.setProperty("new value");
sess.evict(newEntity); // otherwise load() will return the same object again from the context
MyEntity oldEntity = (MyEntity) sess.load(...); // fresh copy into the context
sess.merge(newEntity); // replaces old in the context with this one
```
|
183,016 |
<p>I'm making a report in Access 2003 that contains a sub report of related records. Within the sub report, I want the top two records only. When I add "TOP 2" to the sub report's query, it seems to select the top two records before it filters on the link fields. How do I get the top two records of only those records that apply to the corresponding link field? Thanks.</p>
|
[
{
"answer_id": 183544,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 2,
"selected": true,
"text": "<p>I've got two suggestions:<br>\n1) Pass your master field (on the parent form) to the query as a parameter (you could reference a field on the parent form directly as well)<br>\n2) You could fake out rownumbers in Access and limit them to only rownum <= 2. E.g., </p>\n\n<pre><code>SELECT o1.order_number, o1.order_date,\n (SELECT COUNT(*) FROM orders AS o2\n WHERE o2.order_date <= o1.order_date) AS RowNum\n FROM\n orders AS o1\n ORDER BY o1.order_date \n</code></pre>\n\n<p>(from <a href=\"http://groups.google.com/group/microsoft.public.access.queries/msg/ec562cbc51f03b6e?pli=1\" rel=\"nofollow noreferrer\">http://groups.google.com/group/microsoft.public.access.queries/msg/ec562cbc51f03b6e?pli=1</a>)<br>\nHowever, this kind of query might return an read only record set, so it might not be appropriated if you needed to do the same thing on a Form instead of a Report.</p>\n"
},
{
"answer_id": 258114,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 2,
"selected": false,
"text": "<p>The sample query below is supposed to return a pair of most recent orders for each customer (instead of all orders):</p>\n\n<pre><code>select\n Order.ID,\n Order.Customer_ID,\n Order.PlacementDate\nfrom\n Order\nwhere\n Order.ID in \n (\n select top 2\n RecentOrder.ID\n from\n Order as RecentOrder\n where\n RecentOrder.Customer_ID = Order.Customer_ID\n order by\n RecentOrder.PlacementDate Desc\n )\n</code></pre>\n\n<p>A query like this could be used in your sub-report to avoid using a temporary table. </p>\n\n<p>CAVEAT EMPTOR: I did not test this sample query, and I don't know if this query would work for a report running against Jet database (we don't use Access to store data and we avoid Access reports like plague :-). But it should against SQL Server.</p>\n\n<p>I also don't know how well it would perform in your case. As usual, it depends. :-)</p>\n\n<p>BTW, speaking of performance and hacks. I would not consider usage of temporary table a hack. At worst, this trick can be considered as a more-complicated-than-necessary interface to the report. :-) And using such temporary table may actually be one of the good ways to improve performance. So, don't hurry writing it off. :-)</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7899/"
] |
I'm making a report in Access 2003 that contains a sub report of related records. Within the sub report, I want the top two records only. When I add "TOP 2" to the sub report's query, it seems to select the top two records before it filters on the link fields. How do I get the top two records of only those records that apply to the corresponding link field? Thanks.
|
I've got two suggestions:
1) Pass your master field (on the parent form) to the query as a parameter (you could reference a field on the parent form directly as well)
2) You could fake out rownumbers in Access and limit them to only rownum <= 2. E.g.,
```
SELECT o1.order_number, o1.order_date,
(SELECT COUNT(*) FROM orders AS o2
WHERE o2.order_date <= o1.order_date) AS RowNum
FROM
orders AS o1
ORDER BY o1.order_date
```
(from <http://groups.google.com/group/microsoft.public.access.queries/msg/ec562cbc51f03b6e?pli=1>)
However, this kind of query might return an read only record set, so it might not be appropriated if you needed to do the same thing on a Form instead of a Report.
|
183,018 |
<p>Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql_variant, presumably into object? </p>
<p>The aim is to read data stored as <a href="http://msdn.microsoft.com/en-us/library/ms173829.aspx" rel="nofollow noreferrer">sql_variant type</a> in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql_variant, if possible, would go into such type.</p>
|
[
{
"answer_id": 183027,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to put the data into a variable of type object then (simplified):</p>\n\n<pre><code>object result = null;\nresult = reader[\"columnNameGoesHere\"];\n</code></pre>\n\n<p>Should do the trick.</p>\n\n<p>There's also a good explanation of the various different methods of retrieving the contents of a given columns current record in <a href=\"http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=454\" rel=\"nofollow noreferrer\">this DevHood tutorial</a>. The summary table of data type mappings at the end may come in handy too!</p>\n"
},
{
"answer_id": 70103308,
"author": "JEuvin",
"author_id": 2926260,
"author_profile": "https://Stackoverflow.com/users/2926260",
"pm_score": 0,
"selected": false,
"text": "<p>Sql_Variant is of type object.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings\" rel=\"nofollow noreferrer\">Microsoft Docs</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23730/"
] |
Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql\_variant, presumably into object?
The aim is to read data stored as [sql\_variant type](http://msdn.microsoft.com/en-us/library/ms173829.aspx) in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql\_variant, if possible, would go into such type.
|
If you want to put the data into a variable of type object then (simplified):
```
object result = null;
result = reader["columnNameGoesHere"];
```
Should do the trick.
There's also a good explanation of the various different methods of retrieving the contents of a given columns current record in [this DevHood tutorial](http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=454). The summary table of data type mappings at the end may come in handy too!
|
183,032 |
<p>Is it possible to send a list of IDs to a stored procedure from c#?</p>
<pre><code>UPDATE Germs
SET Mutated = ~Mutated
WHERE (GermID IN (ids))
</code></pre>
|
[
{
"answer_id": 183045,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 1,
"selected": false,
"text": "<p>According to <a href=\"http://visualstudiomagazine.com/features/article.aspx?editorialsid=2438\" rel=\"nofollow noreferrer\">This</a> article, you could try the Table Value Parameter.</p>\n"
},
{
"answer_id": 183061,
"author": "Nick",
"author_id": 26161,
"author_profile": "https://Stackoverflow.com/users/26161",
"pm_score": 0,
"selected": false,
"text": "<p>Yep, you can use a chunk of XML to build your list of ID's. Then you can use OPENXML and select from that record set.</p>\n\n<p>Look up OPENXML, sp_preparexmldocument, sp_removexmldocument</p>\n"
},
{
"answer_id": 183073,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 2,
"selected": false,
"text": "<p>This may be a dirty hack, but you can create a temp table and then join to it from within your stored procedure (assuming they are accessed during the same connection). For example:</p>\n\n<pre><code>CREATE TABLE #ids (id int)\nINSERT INTO #ids VALUES ('123') -- your C# code would generate all of the inserts\n\n-- From within your stored procedure...\nUPDATE g\nSET Mutated = ~Mutated\nFROM Germs g\nJOIN #ids i ON g.GermID = i.id\n</code></pre>\n"
},
{
"answer_id": 183095,
"author": "Kevin Dark",
"author_id": 26151,
"author_profile": "https://Stackoverflow.com/users/26151",
"pm_score": 2,
"selected": false,
"text": "<p>You could try what i have made do with:-</p>\n\n<p>Create a function called Split_String</p>\n\n<pre><code>set ANSI_NULLS ON\nset QUOTED_IDENTIFIER ON\ngo\n\nCREATE FUNCTION [dbo].[Split_String] \n( \n @MyString varchar(5000)\n)\nRETURNS @Results TABLE\n(\n Value varchar(1000)\n) \nAS\n BEGIN\n DECLARE @Pos int\n DECLARE @StrLen int\n DECLARE @MyLen int\n DECLARE @MyVal varchar\n SET @pos = 1\n SET @MyLen = 1\n WHILE @MyString <> ''\n BEGIN\n SET @MyLen = charindex(',',@MyString) \n IF @MyLen = 0 SET @MyLen = Len(@MyString)\n INSERT @Results SELECT replace(substring(@MyString, @pos, @MyLen),',','')\n SET @MyString = SUBSTRING(@MyString,@MyLen+1,len(@MyString))\n END\n RETURN \n END\n</code></pre>\n\n<p>Then when you use IN() use in the following fashion with a comma separated string:-</p>\n\n<pre><code>SELECT * FROM [youDataBase].[dbo].[Split_String] (<@MyString, varchar(5000),>)\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible to send a list of IDs to a stored procedure from c#?
```
UPDATE Germs
SET Mutated = ~Mutated
WHERE (GermID IN (ids))
```
|
This may be a dirty hack, but you can create a temp table and then join to it from within your stored procedure (assuming they are accessed during the same connection). For example:
```
CREATE TABLE #ids (id int)
INSERT INTO #ids VALUES ('123') -- your C# code would generate all of the inserts
-- From within your stored procedure...
UPDATE g
SET Mutated = ~Mutated
FROM Germs g
JOIN #ids i ON g.GermID = i.id
```
|
183,035 |
<p>I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.</p>
<p>I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.</p>
<p>I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.</p>
<p>A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.</p>
<p>Anybody else had a similar problem, and managed to fix it?</p>
|
[
{
"answer_id": 697518,
"author": "Samuel Jack",
"author_id": 1727,
"author_profile": "https://Stackoverflow.com/users/1727",
"pm_score": 3,
"selected": true,
"text": "<p>Add-in Express looked into this for me, and it turns out to have something to do with the Window style of the Task Pane that gets added to Excel. If you turn off the WS_CHILD flag in the Windows CreateParams then Combo Boxes and other popups work as expected. </p>\n\n<p>They gave me this snippet of code to add to my ADXExcelTaskPane:</p>\n\n<pre><code>private const uint WS_CHILD = 0x40000000;\nprivate const uint WS_CLIPCHILDREN = 0x02000000;\nprivate const uint WS_CLIPSIBLINGS = 0x04000000;\n\nprivate CreateParams _CreateParams = new CreateParams();\nprotected override CreateParams CreateParams\n{\n get\n {\n _CreateParams = base.CreateParams;\n if (!DesignMode)\n _CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD\n\n return _CreateParams;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5191938,
"author": "Pacome",
"author_id": 644443,
"author_profile": "https://Stackoverflow.com/users/644443",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. I have a WPF user control hosted in a WinForm user control and the whole is an Excel AddIn. I work with Visual Studio 2010 and Excel 2007 and Excel 2010.</p>\n\n<p>My problem was that when I clicked once in the Excel sheet, the AddIn never gains focus again.\nI found a workaround. </p>\n\n<ol>\n<li>In the constructor of my WinForm user control, I register on the event MouseEnter of my WPF user control.</li>\n<li><p>In the MouseEnter event handler, I give the focus to myself (this.Focus())</p>\n\n<pre><code>public WpfContainerUserControl()\n{\n InitializeComponent();\n GpecsBrowserTabUserControl gpecBrowser = elementHost1.Child as GpecsBrowserTabUserControl;\n gpecBrowser.MouseEnter += new System.Windows.Input.MouseEventHandler(gpecBrowser_MouseEnter);\n}\n\nvoid gpecBrowser_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)\n{\n this.Focus();\n} \n</code></pre></li>\n</ol>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727/"
] |
I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.
I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.
I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.
A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.
Anybody else had a similar problem, and managed to fix it?
|
Add-in Express looked into this for me, and it turns out to have something to do with the Window style of the Task Pane that gets added to Excel. If you turn off the WS\_CHILD flag in the Windows CreateParams then Combo Boxes and other popups work as expected.
They gave me this snippet of code to add to my ADXExcelTaskPane:
```
private const uint WS_CHILD = 0x40000000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;
private CreateParams _CreateParams = new CreateParams();
protected override CreateParams CreateParams
{
get
{
_CreateParams = base.CreateParams;
if (!DesignMode)
_CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD
return _CreateParams;
}
}
```
|
183,042 |
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="noreferrer">UUID</a> in <a href="http://www.sqlalchemy.org/" rel="noreferrer">SQLAlchemy</a> if using <a href="http://www.postgresql.org/" rel="noreferrer">PostgreSQL</a> (Postgres)?</p>
|
[
{
"answer_id": 188427,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": -1,
"selected": false,
"text": "<p>You could try writing a <a href=\"http://www.sqlalchemy.org/docs/05/types.html#types_custom\" rel=\"nofollow noreferrer\">custom type</a>, for instance:</p>\n\n<pre><code>import sqlalchemy.types as types\n\nclass UUID(types.TypeEngine):\n def get_col_spec(self):\n return \"uuid\"\n\n def bind_processor(self, dialect):\n def process(value):\n return value\n return process\n\n def result_processor(self, dialect):\n def process(value):\n return value\n return process\n\ntable = Table('foo', meta,\n Column('id', UUID(), primary_key=True),\n)\n</code></pre>\n"
},
{
"answer_id": 812363,
"author": "Tom Willis",
"author_id": 67393,
"author_profile": "https://Stackoverflow.com/users/67393",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://blog.sadphaeton.com/2009/01/19/sqlalchemy-recipeuuid-column.html\" rel=\"noreferrer\">I wrote this</a> and the domain is gone but here's the guts....</p>\n\n<p>Regardless of how my colleagues who really care about proper database design feel about UUID's and GUIDs used for key fields. I often find I need to do it. I think it has some advantages over autoincrement that make it worth it. </p>\n\n<p>I've been refining a UUID column type for the past few months and I think I've finally got it solid.</p>\n\n<pre><code>from sqlalchemy import types\nfrom sqlalchemy.dialects.mysql.base import MSBinary\nfrom sqlalchemy.schema import Column\nimport uuid\n\n\nclass UUID(types.TypeDecorator):\n impl = MSBinary\n def __init__(self):\n self.impl.length = 16\n types.TypeDecorator.__init__(self,length=self.impl.length)\n\n def process_bind_param(self,value,dialect=None):\n if value and isinstance(value,uuid.UUID):\n return value.bytes\n elif value and not isinstance(value,uuid.UUID):\n raise ValueError,'value %s is not a valid uuid.UUID' % value\n else:\n return None\n\n def process_result_value(self,value,dialect=None):\n if value:\n return uuid.UUID(bytes=value)\n else:\n return None\n\n def is_mutable(self):\n return False\n\n\nid_column_name = \"id\"\n\ndef id_column():\n import uuid\n return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)\n\n# Usage\nmy_table = Table('test',\n metadata,\n id_column(),\n Column('parent_id',\n UUID(),\n ForeignKey(table_parent.c.id)))\n</code></pre>\n\n<p>I believe storing as binary(16 bytes) should end up being more efficient than the string representation(36 bytes?), And there seems to be some indication that indexing 16 byte blocks should be more efficient in mysql than strings. I wouldn't expect it to be worse anyway.</p>\n\n<p>One disadvantage I've found is that at least in phpymyadmin, you can't edit records because it implicitly tries to do some sort of character conversion for the \"select * from table where id =...\" and there's miscellaneous display issues.</p>\n\n<p>Other than that everything seems to work fine, and so I'm throwing it out there. Leave a comment if you see a glaring error with it. I welcome any suggestions for improving it.</p>\n\n<p>Unless I'm missing something the above solution will work if the underlying database has a UUID type. If it doesn't, you would likely get errors when the table is created. The solution I came up with I was targeting MSSqlServer originally and then went MySql in the end, so I think my solution is a little more flexible as it seems to work fine on mysql and sqlite. Haven't bothered checking postgres yet. </p>\n"
},
{
"answer_id": 19935248,
"author": "Nemeth",
"author_id": 370299,
"author_profile": "https://Stackoverflow.com/users/370299",
"pm_score": 2,
"selected": false,
"text": "<p>In case anyone is interested, I've been using Tom Willis answer, but found useful to add a string to uuid.UUID conversion in the process_bind_param method</p>\n\n<pre><code>class UUID(types.TypeDecorator):\n impl = types.LargeBinary\n\n def __init__(self):\n self.impl.length = 16\n types.TypeDecorator.__init__(self, length=self.impl.length)\n\n def process_bind_param(self, value, dialect=None):\n if value and isinstance(value, uuid.UUID):\n return value.bytes\n elif value and isinstance(value, basestring):\n return uuid.UUID(value).bytes\n elif value:\n raise ValueError('value %s is not a valid uuid.UUId' % value)\n else:\n return None\n\n def process_result_value(self, value, dialect=None):\n if value:\n return uuid.UUID(bytes=value)\n else:\n return None\n\n def is_mutable(self):\n return False\n</code></pre>\n"
},
{
"answer_id": 30604002,
"author": "zwirbeltier",
"author_id": 769486,
"author_profile": "https://Stackoverflow.com/users/769486",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an approach based on the <a href=\"http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type\" rel=\"noreferrer\">Backend agnostic GUID</a> from the SQLAlchemy docs, but using a BINARY field to store the UUIDs in non-postgresql databases.</p>\n\n<pre><code>import uuid\n\nfrom sqlalchemy.types import TypeDecorator, BINARY\nfrom sqlalchemy.dialects.postgresql import UUID as psqlUUID\n\nclass UUID(TypeDecorator):\n \"\"\"Platform-independent GUID type.\n\n Uses Postgresql's UUID type, otherwise uses\n BINARY(16), to store UUID.\n\n \"\"\"\n impl = BINARY\n\n def load_dialect_impl(self, dialect):\n if dialect.name == 'postgresql':\n return dialect.type_descriptor(psqlUUID())\n else:\n return dialect.type_descriptor(BINARY(16))\n\n def process_bind_param(self, value, dialect):\n if value is None:\n return value\n else:\n if not isinstance(value, uuid.UUID):\n if isinstance(value, bytes):\n value = uuid.UUID(bytes=value)\n elif isinstance(value, int):\n value = uuid.UUID(int=value)\n elif isinstance(value, str):\n value = uuid.UUID(value)\n if dialect.name == 'postgresql':\n return str(value)\n else:\n return value.bytes\n\n def process_result_value(self, value, dialect):\n if value is None:\n return value\n if dialect.name == 'postgresql':\n return uuid.UUID(value)\n else:\n return uuid.UUID(bytes=value)\n</code></pre>\n"
},
{
"answer_id": 32332765,
"author": "Berislav Lopac",
"author_id": 122033,
"author_profile": "https://Stackoverflow.com/users/122033",
"pm_score": 5,
"selected": false,
"text": "<p>I've used the <code>UUIDType</code> from the <a href=\"http://sqlalchemy-utils.readthedocs.org/en/latest/data_types.html#module-sqlalchemy_utils.types.uuid\" rel=\"noreferrer\"><code>SQLAlchemy-Utils</code> package</a>.</p>\n"
},
{
"answer_id": 41434923,
"author": "Kushal Ahmed",
"author_id": 7367289,
"author_profile": "https://Stackoverflow.com/users/7367289",
"pm_score": 5,
"selected": false,
"text": "<p>If you are happy with a 'String' column having UUID value, here goes a simple solution:</p>\n\n\n\n<pre><code>def generate_uuid():\n return str(uuid.uuid4())\n\nclass MyTable(Base):\n __tablename__ = 'my_table'\n\n uuid = Column(String, name=\"uuid\", primary_key=True, default=generate_uuid)\n</code></pre>\n"
},
{
"answer_id": 49398042,
"author": "JDiMatteo",
"author_id": 1007353,
"author_profile": "https://Stackoverflow.com/users/1007353",
"pm_score": 8,
"selected": false,
"text": "<p>The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so complicated.</p>\n<p>Here is an example:</p>\n<pre><code>from sqlalchemy.dialects.postgresql import UUID\nfrom flask_sqlalchemy import SQLAlchemy\nimport uuid\n\ndb = SQLAlchemy()\n\nclass Foo(db.Model):\n id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\n</code></pre>\n<p>Be careful not to miss passing the <code>callable</code> <code>uuid.uuid4</code> into the column definition, rather than calling the function itself with <code>uuid.uuid4()</code>. Otherwise, you will have the same scalar value for all instances of this class. More details <a href=\"https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.Column.params.default\" rel=\"noreferrer\">here</a>:</p>\n<blockquote>\n<p>A scalar, Python callable, or ColumnElement expression representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert.</p>\n</blockquote>\n"
},
{
"answer_id": 57919049,
"author": "Granat",
"author_id": 12061926,
"author_profile": "https://Stackoverflow.com/users/12061926",
"pm_score": 4,
"selected": false,
"text": "<p>Since you're using Postgres this should work:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from app.main import db\nfrom sqlalchemy.dialects.postgresql import UUID\n\nclass Foo(db.Model):\n id = db.Column(UUID(as_uuid=True), primary_key=True)\n name = db.Column(db.String, nullable=False)\n</code></pre>\n"
},
{
"answer_id": 69000211,
"author": "Atul Anand",
"author_id": 16687498,
"author_profile": "https://Stackoverflow.com/users/16687498",
"pm_score": 0,
"selected": false,
"text": "<p>We can use <code>UUIDType</code>,</p>\n<pre class=\"lang-py prettyprint-override\"><code>from sqlalchemy_utils import UUIDType\nfrom sqlalchemy import String\n\nclass User(Base):\n id = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)\n name = Column(String)\n</code></pre>\n<p>For more details we can refer to the <a href=\"https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#module-sqlalchemy_utils.types.uuid\" rel=\"nofollow noreferrer\">official documentation</a>.</p>\n"
},
{
"answer_id": 74367684,
"author": "gentiand",
"author_id": 11727882,
"author_profile": "https://Stackoverflow.com/users/11727882",
"pm_score": 1,
"selected": false,
"text": "<p>I encountered the same issue, this should work, it works for me:</p>\n<pre><code>from sqlalchemy import Column, text\nfrom sqlalchemy.dialects.postgresql import UUID\n\nColumn(\n "id", UUID(as_uuid=True),\n primary_key=True,\n server_default=text("gen_random_uuid()"),\n)\n</code></pre>\n<p>If you use PostgreSQL < 14, I think you need to add this EXTENSION pack:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE EXTENSION IF NOT EXISTS "pgcrypto";\n</code></pre>\n<p>You can use <code>uuid_generate_v4()</code> as well, you'd need to add the EXTENSION pack then:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE EXTENSION IF NOT EXISTS "uuid-ossp";\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
Is there a way to define a column (primary key) as a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) in [SQLAlchemy](http://www.sqlalchemy.org/) if using [PostgreSQL](http://www.postgresql.org/) (Postgres)?
|
The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so complicated.
Here is an example:
```
from sqlalchemy.dialects.postgresql import UUID
from flask_sqlalchemy import SQLAlchemy
import uuid
db = SQLAlchemy()
class Foo(db.Model):
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
```
Be careful not to miss passing the `callable` `uuid.uuid4` into the column definition, rather than calling the function itself with `uuid.uuid4()`. Otherwise, you will have the same scalar value for all instances of this class. More details [here](https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.Column.params.default):
>
> A scalar, Python callable, or ColumnElement expression representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert.
>
>
>
|
183,062 |
<p>How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?</p>
|
[
{
"answer_id": 183120,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>Cop-out line of the year: it depends.</p>\n\n<p>How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?</p>\n\n<p>My favorite place to go for information like this is <a href=\"http://www.csszengarden.com/\" rel=\"nofollow noreferrer\">CSS Zen Garden</a> & <a href=\"http://alistapart.com/\" rel=\"nofollow noreferrer\">A List Apart</a>.</p>\n"
},
{
"answer_id": 183129,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 2,
"selected": false,
"text": "<p>Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file. </p>\n\n<p>Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a> enough. </p>\n"
},
{
"answer_id": 183150,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "<p>There are a number of different things you can do to aid in the organisation of your CSS. For example:</p>\n\n<ul>\n<li>Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc. </li>\n<li>Comment your CSS code.</li>\n<li>Why not add a table of contents?</li>\n<li>Try using a CSS framework like <a href=\"http://960.gs\" rel=\"nofollow noreferrer\">960.gs</a> to get your started.</li>\n</ul>\n\n<p>It's all down to personal taste really. But here are a few links that you might find useful:</p>\n\n<ul>\n<li><a href=\"http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/</a></li>\n<li><a href=\"http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/</a></li>\n<li><a href=\"http://www.louddog.com/bloggity/2008/03/css-best-practices.php\" rel=\"nofollow noreferrer\">http://www.louddog.com/bloggity/2008/03/css-best-practices.php</a></li>\n<li><a href=\"http://natbat.net/2008/Sep/28/css-systems/\" rel=\"nofollow noreferrer\">http://natbat.net/2008/Sep/28/css-systems/</a></li>\n</ul>\n"
},
{
"answer_id": 183160,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 1,
"selected": false,
"text": "<p>There are two worlds:</p>\n\n<ol>\n<li><code>The human editor perspective:</code> Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...</li>\n<li><code>The consumer perspective:</code> The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.</li>\n</ol>\n\n<p>I recommend you to start with a <a href=\"http://en.wikipedia.org/wiki/CSS_framework\" rel=\"nofollow noreferrer\">CSS framework</a>:</p>\n\n<ul>\n<li><a href=\"http://www.blueprintcss.org/\" rel=\"nofollow noreferrer\">Blueprint</a> if you like smaller things</li>\n<li>or <a href=\"http://www.yaml.de/en/\" rel=\"nofollow noreferrer\">YAML</a> for a big and functional one</li>\n</ul>\n\n<p>There is also a <a href=\"http://en.wikipedia.org/wiki/List_of_CSS_frameworks\" rel=\"nofollow noreferrer\">list of CSS Frameworks</a>...</p>\n\n<p>And then bring it in shape (for the browser) with a <a href=\"http://www.google.ch/search?q=css+optimizer\" rel=\"nofollow noreferrer\">CSS Optimizer</a> (p.e. <a href=\"http://floele.flyspray.org/csstidy//css_optimiser.php\" rel=\"nofollow noreferrer\">CSS Form.&Opti.</a>)</p>\n\n<p>You can measure the Results (unpotimized <-> optimized) with <a href=\"http://developer.yahoo.com/yslow/\" rel=\"nofollow noreferrer\">YSlow</a>.</p>\n"
},
{
"answer_id": 183205,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:</p>\n\n<ul>\n<li><p>Make <code>class</code> names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than <code>left</code>, use something like <code>header_links_object2_left</code>.</p></li>\n<li><p>Use <code>id</code> rather than <code>class</code> <strong>only</strong> if you know there will only <strong>ever</strong> be one of an object on a page. Again, make the <code>id</code> unambiguous.</p></li>\n<li><p>Consider side effects. Rules like <code>margin</code> and <code>padding</code>, <code>float</code> and <code>clear</code>, and so on can all have unexpected consequences on other elements.</p></li>\n<li><p>If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.</p></li>\n</ul>\n\n<p>And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.</p>\n"
},
{
"answer_id": 183422,
"author": "Mathletics",
"author_id": 7469,
"author_profile": "https://Stackoverflow.com/users/7469",
"pm_score": 1,
"selected": false,
"text": "<p>A few more tips for keeping organized:</p>\n\n<ul>\n<li>Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip</li>\n<li>Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.</li>\n<li>Semantic HTML with good class names can help a lot with remembering what styles apply to which elements. </li>\n</ul>\n"
},
{
"answer_id": 300736,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 4,
"selected": true,
"text": "<p>I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational \"tabs\" would have class=\"tabs\". A header containing a date could be class=\"date\" or an ordered list containing a top 10 list could have class=\"chart\". Similarly, for IDs, one could give the page footer id=\"footer\" or the logo of the website id=\"mainLogo\". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific. </p>\n\n<p>Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this: </p>\n\n<pre><code> ul.tabs {\n list-style-type: none;\n }\n ul.tabs li {\n float: left;\n }\n ul.tabs li img {\n border: none;\n }\n</code></pre>\n\n<p>That way the \"parent\" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put \"body { font-size: 77%; }\" and \"a { color: #FFCC00; }\" etc. After that I would put selectors for the main framework parts of the page, for instance \"ul#mainMenu { float: left; }\" and \"div#footer { height: 4em; }\". Then on to common object classes, \"td.price { text-align: right; }\", finally followed by extra little bits like \".clear { clear: both; }\". Now that's just how I like to do it - I'm sure there are better ways but it works for me. </p>\n\n<p>Finally, a couple of tips: </p>\n\n<ol>\n<li>Make best use of cascades and don't \"overclass\" stuff. If you give a <ul> class=\"textNav\" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {} </li>\n<li><p>Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:</p>\n\n<pre><code><style>\ndiv.box {\nfloat: left;\nborder: 1px solid blue;\npadding: 1em;\n}\n\ndiv.wide {\nwidth: 15em; \n}\n\ndiv.narrow {\nwidth: 8em; \n}\n\ndiv#oddOneOut {\nfloat: right;\n}\n</style>\n\n<div class=\"box wide\">a wide box</div>\n<div class=\"box narrow\">a narrow box</div>\n<div class=\"box wide\" id=\"oddOneOut\">an odd box</div>\n</code></pre></li>\n<li><p>Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. \"body.signIn div#mainMenu form.signIn { display: none; }\" </p></li>\n</ol>\n\n<p>I hope you find at least some of my ramblings useful and wish you the best with your projects! </p>\n"
},
{
"answer_id": 300770,
"author": "One Crayon",
"author_id": 38666,
"author_profile": "https://Stackoverflow.com/users/38666",
"pm_score": 2,
"selected": false,
"text": "<p>The best organizational advice I've ever received came from a presentation at An Event Apart.</p>\n\n<p>Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:</p>\n\n<ol>\n<li>Reset rules (may be as simple as the\n<code>* {margin: 0; padding: 0}</code> rule,\nEric Meyer's reset, or the YUI\nreset)</li>\n<li>Basic element styling; this\nis the stuff like basic typography\nfor paragraphs, spacing for lists,\netc.</li>\n<li>Universal classes; this section\nfor me generally contains things\nlike <code>.error</code>, <code>.left</code> (I'm only 80%\nsemantic), etc.</li>\n<li>Universal\nlayout/IDs; <code>#content</code>, <code>#header</code>,\nor whatever you've cut your page up\ninto.</li>\n<li>Page-specific rules; if you\nneed to modify an existing style\njust for one or a few pages, stick a\nunique ID high up (body tag is\nusually good) and toss your\noverrides at the end of the document</li>\n</ol>\n\n<p>I don't recommend using a CSS framework unless you need to mock something up in HTML <em>fast</em>. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own \"framework\" as you figure out what code is shared by your projects over time.</p>\n\n<p>Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
|
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
```
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
```
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
1. Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
2. Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
```
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
```
3. Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
|
183,071 |
<p>My normal IDE is Visual Studio, but I'm currently doing some development in Eclipse for the first time. If you press Ctrl-X with text selected in either program, it cuts the text and puts on the clipboard exactly as you'd expect. If press Ctrl-X with no text selected in Visual Studio, it cuts the current line. In Eclipse it is ignored. Is there a way to get Eclipse to use Studio's behavior?</p>
|
[
{
"answer_id": 183120,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>Cop-out line of the year: it depends.</p>\n\n<p>How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?</p>\n\n<p>My favorite place to go for information like this is <a href=\"http://www.csszengarden.com/\" rel=\"nofollow noreferrer\">CSS Zen Garden</a> & <a href=\"http://alistapart.com/\" rel=\"nofollow noreferrer\">A List Apart</a>.</p>\n"
},
{
"answer_id": 183129,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 2,
"selected": false,
"text": "<p>Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file. </p>\n\n<p>Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a> enough. </p>\n"
},
{
"answer_id": 183150,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "<p>There are a number of different things you can do to aid in the organisation of your CSS. For example:</p>\n\n<ul>\n<li>Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc. </li>\n<li>Comment your CSS code.</li>\n<li>Why not add a table of contents?</li>\n<li>Try using a CSS framework like <a href=\"http://960.gs\" rel=\"nofollow noreferrer\">960.gs</a> to get your started.</li>\n</ul>\n\n<p>It's all down to personal taste really. But here are a few links that you might find useful:</p>\n\n<ul>\n<li><a href=\"http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/</a></li>\n<li><a href=\"http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/</a></li>\n<li><a href=\"http://www.louddog.com/bloggity/2008/03/css-best-practices.php\" rel=\"nofollow noreferrer\">http://www.louddog.com/bloggity/2008/03/css-best-practices.php</a></li>\n<li><a href=\"http://natbat.net/2008/Sep/28/css-systems/\" rel=\"nofollow noreferrer\">http://natbat.net/2008/Sep/28/css-systems/</a></li>\n</ul>\n"
},
{
"answer_id": 183160,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 1,
"selected": false,
"text": "<p>There are two worlds:</p>\n\n<ol>\n<li><code>The human editor perspective:</code> Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...</li>\n<li><code>The consumer perspective:</code> The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.</li>\n</ol>\n\n<p>I recommend you to start with a <a href=\"http://en.wikipedia.org/wiki/CSS_framework\" rel=\"nofollow noreferrer\">CSS framework</a>:</p>\n\n<ul>\n<li><a href=\"http://www.blueprintcss.org/\" rel=\"nofollow noreferrer\">Blueprint</a> if you like smaller things</li>\n<li>or <a href=\"http://www.yaml.de/en/\" rel=\"nofollow noreferrer\">YAML</a> for a big and functional one</li>\n</ul>\n\n<p>There is also a <a href=\"http://en.wikipedia.org/wiki/List_of_CSS_frameworks\" rel=\"nofollow noreferrer\">list of CSS Frameworks</a>...</p>\n\n<p>And then bring it in shape (for the browser) with a <a href=\"http://www.google.ch/search?q=css+optimizer\" rel=\"nofollow noreferrer\">CSS Optimizer</a> (p.e. <a href=\"http://floele.flyspray.org/csstidy//css_optimiser.php\" rel=\"nofollow noreferrer\">CSS Form.&Opti.</a>)</p>\n\n<p>You can measure the Results (unpotimized <-> optimized) with <a href=\"http://developer.yahoo.com/yslow/\" rel=\"nofollow noreferrer\">YSlow</a>.</p>\n"
},
{
"answer_id": 183205,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:</p>\n\n<ul>\n<li><p>Make <code>class</code> names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than <code>left</code>, use something like <code>header_links_object2_left</code>.</p></li>\n<li><p>Use <code>id</code> rather than <code>class</code> <strong>only</strong> if you know there will only <strong>ever</strong> be one of an object on a page. Again, make the <code>id</code> unambiguous.</p></li>\n<li><p>Consider side effects. Rules like <code>margin</code> and <code>padding</code>, <code>float</code> and <code>clear</code>, and so on can all have unexpected consequences on other elements.</p></li>\n<li><p>If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.</p></li>\n</ul>\n\n<p>And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.</p>\n"
},
{
"answer_id": 183422,
"author": "Mathletics",
"author_id": 7469,
"author_profile": "https://Stackoverflow.com/users/7469",
"pm_score": 1,
"selected": false,
"text": "<p>A few more tips for keeping organized:</p>\n\n<ul>\n<li>Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip</li>\n<li>Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.</li>\n<li>Semantic HTML with good class names can help a lot with remembering what styles apply to which elements. </li>\n</ul>\n"
},
{
"answer_id": 300736,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 4,
"selected": true,
"text": "<p>I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational \"tabs\" would have class=\"tabs\". A header containing a date could be class=\"date\" or an ordered list containing a top 10 list could have class=\"chart\". Similarly, for IDs, one could give the page footer id=\"footer\" or the logo of the website id=\"mainLogo\". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific. </p>\n\n<p>Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this: </p>\n\n<pre><code> ul.tabs {\n list-style-type: none;\n }\n ul.tabs li {\n float: left;\n }\n ul.tabs li img {\n border: none;\n }\n</code></pre>\n\n<p>That way the \"parent\" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put \"body { font-size: 77%; }\" and \"a { color: #FFCC00; }\" etc. After that I would put selectors for the main framework parts of the page, for instance \"ul#mainMenu { float: left; }\" and \"div#footer { height: 4em; }\". Then on to common object classes, \"td.price { text-align: right; }\", finally followed by extra little bits like \".clear { clear: both; }\". Now that's just how I like to do it - I'm sure there are better ways but it works for me. </p>\n\n<p>Finally, a couple of tips: </p>\n\n<ol>\n<li>Make best use of cascades and don't \"overclass\" stuff. If you give a <ul> class=\"textNav\" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {} </li>\n<li><p>Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:</p>\n\n<pre><code><style>\ndiv.box {\nfloat: left;\nborder: 1px solid blue;\npadding: 1em;\n}\n\ndiv.wide {\nwidth: 15em; \n}\n\ndiv.narrow {\nwidth: 8em; \n}\n\ndiv#oddOneOut {\nfloat: right;\n}\n</style>\n\n<div class=\"box wide\">a wide box</div>\n<div class=\"box narrow\">a narrow box</div>\n<div class=\"box wide\" id=\"oddOneOut\">an odd box</div>\n</code></pre></li>\n<li><p>Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. \"body.signIn div#mainMenu form.signIn { display: none; }\" </p></li>\n</ol>\n\n<p>I hope you find at least some of my ramblings useful and wish you the best with your projects! </p>\n"
},
{
"answer_id": 300770,
"author": "One Crayon",
"author_id": 38666,
"author_profile": "https://Stackoverflow.com/users/38666",
"pm_score": 2,
"selected": false,
"text": "<p>The best organizational advice I've ever received came from a presentation at An Event Apart.</p>\n\n<p>Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:</p>\n\n<ol>\n<li>Reset rules (may be as simple as the\n<code>* {margin: 0; padding: 0}</code> rule,\nEric Meyer's reset, or the YUI\nreset)</li>\n<li>Basic element styling; this\nis the stuff like basic typography\nfor paragraphs, spacing for lists,\netc.</li>\n<li>Universal classes; this section\nfor me generally contains things\nlike <code>.error</code>, <code>.left</code> (I'm only 80%\nsemantic), etc.</li>\n<li>Universal\nlayout/IDs; <code>#content</code>, <code>#header</code>,\nor whatever you've cut your page up\ninto.</li>\n<li>Page-specific rules; if you\nneed to modify an existing style\njust for one or a few pages, stick a\nunique ID high up (body tag is\nusually good) and toss your\noverrides at the end of the document</li>\n</ol>\n\n<p>I don't recommend using a CSS framework unless you need to mock something up in HTML <em>fast</em>. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own \"framework\" as you figure out what code is shared by your projects over time.</p>\n\n<p>Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9323/"
] |
My normal IDE is Visual Studio, but I'm currently doing some development in Eclipse for the first time. If you press Ctrl-X with text selected in either program, it cuts the text and puts on the clipboard exactly as you'd expect. If press Ctrl-X with no text selected in Visual Studio, it cuts the current line. In Eclipse it is ignored. Is there a way to get Eclipse to use Studio's behavior?
|
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
```
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
```
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
1. Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
2. Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
```
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
```
3. Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
|
183,075 |
<p>I am making numerous, minute changes to .php files in Eclipse PDT then committing them and testing on the server.</p>
<p>The repetitive six-step commit process is getting tedious:</p>
<pre><code>right-click
team
Commit...
click "choose previously selected comment"
select in list
click OK
</code></pre>
<p>Does anyone know of a hotkey or other process to expedite this?</p>
<p><b>UPDATE:</b> does anyone know of a general hotkey macro tool for windows applications which would allow me to program a macro that would make these 6 clicks for me?</p>
|
[
{
"answer_id": 183092,
"author": "Soraz",
"author_id": 24610,
"author_profile": "https://Stackoverflow.com/users/24610",
"pm_score": 1,
"selected": false,
"text": "<p>In eclipse you can choose to either commit one file or the entire project.</p>\n\n<p>To commit the entire project, right click on the project in your resource view, and choose Team->Commit.</p>\n\n<p>If you want to preview the changes choose Team->Synchronize, which will show you what files are changed, and gives you a quick preview of the diffs in both incoming and outgoing mode.</p>\n"
},
{
"answer_id": 183122,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 0,
"selected": false,
"text": "<p>In some versions of Eclipse (or maybe some versions of Subclipse -- are you using SVN?) there was a toolbar button that you could click. It would eliminate the first 2 or 3 steps of your commit process. Maybe you can find that button on the toolbar editor (or perspective editor, or whatever they call it... it's been a while since I've used it).</p>\n\n<p>Also, IMHO, you shouldn't be committing and THEN testing. You'll find things run a lot smoother if you test locally, then commit (and test again in a QA type system...). You probably already know that, so I'm going to assume there's a strange reason you can't test locally.</p>\n"
},
{
"answer_id": 183514,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 3,
"selected": true,
"text": "<p>The best I've been able to do is create a key binding for 'Commit' (under Preferences... General->Keys). Then you just need to click on the project and hit a key combination, which saves the whole right-click->Team->Commit... process.</p>\n\n<p>If you just want to check in the file you are editing, you don't have to click anywhere, just hit the key combination, and the commit dialog pops up to commit the current file.</p>\n"
},
{
"answer_id": 4401617,
"author": "David Mann",
"author_id": 274414,
"author_profile": "https://Stackoverflow.com/users/274414",
"pm_score": 0,
"selected": false,
"text": "<p>I find that right-clicking the project or file in the Package Explorer is the most time consuming part of this repetitive process.</p>\n\n<p>Mostly I make related changes in multiple files, then synchronize the whole project. The first step to making the whole process accelerated via hotkeys is to bind a key combination to \"Synchronize with repository...\". For Eclipse 3.5 on OSX, the hotkey can be bound by going to Eclipse->Preferences->General->Keys. Then search for \"Synchronize\" in the text filter. I bind control-s as synchronize.</p>\n\n<p>Once a hotkey is bound for Synchro... , hitting the hotkey will synchronize the file in your active editor, or the selected files in the project explorer, if the project explorer is active.</p>\n\n<p>To rapidly put focus in to the project explorer, hit, on OSX, command-F6 to cycle to the project explorer. Another way, if focus is in an editor view, is to hit cmd-alt-W (Show In...) and then select \"Project Explorer\" from the popup. Sorry for the OSX shortcuts. If you look in the Keys area mentioned earlier, you should be able to find the relevant hotkey for cycling views.</p>\n\n<p>So we've sped up part of the process, but it would still be nice to have a rapid way of selecting the whole project. The easiest way is a hack- just start typing the name of your project while in the project explorer. If the name isn't unique enough, prepend a 'Z' to it or something so that just they keystroke 'z' will select the whole project. Then hit your Synchro... hotkey to synch the whole project.</p>\n\n<p>Okay, so it takes quite a few hotkeys to synch the whole project, almost like playing a progression of guitar chords or doing a sweet combo in Tekken, but honestly the sequence of hotkeys can all be pushed in less than the time it takes to move your hand to the mouse. Perhaps binding a macro to the entire sequence would make it uber convenient.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
I am making numerous, minute changes to .php files in Eclipse PDT then committing them and testing on the server.
The repetitive six-step commit process is getting tedious:
```
right-click
team
Commit...
click "choose previously selected comment"
select in list
click OK
```
Does anyone know of a hotkey or other process to expedite this?
**UPDATE:** does anyone know of a general hotkey macro tool for windows applications which would allow me to program a macro that would make these 6 clicks for me?
|
The best I've been able to do is create a key binding for 'Commit' (under Preferences... General->Keys). Then you just need to click on the project and hit a key combination, which saves the whole right-click->Team->Commit... process.
If you just want to check in the file you are editing, you don't have to click anywhere, just hit the key combination, and the commit dialog pops up to commit the current file.
|
183,078 |
<p>I have data loaded and various transformations on the data complete, the problem is there is a parent/child relationship managed in the data - best explained by an example</p>
<p>each row has (column names are made up)</p>
<pre><code>row_key parent_row_key row_name parent_row_name
</code></pre>
<p>some rows have row_key == parent_row_key (their own parent)
some rows relate to another row
(row 25 is the parent to row 44 for example).</p>
<p>In this case, row 25 is parent to row 44. I need to put row 25's row_name in row 44's parent_row_name. How do I query the data in the pipeline for the value?</p>
|
[
{
"answer_id": 183159,
"author": "piers7",
"author_id": 26167,
"author_profile": "https://Stackoverflow.com/users/26167",
"pm_score": 2,
"selected": false,
"text": "<p>Can you not just split the data using a multicast and then do a merge-join against itself?</p>\n"
},
{
"answer_id": 233462,
"author": "Emil Rasmussen",
"author_id": 896,
"author_profile": "https://Stackoverflow.com/users/896",
"pm_score": 0,
"selected": false,
"text": "<p>You could write your data to a temp table in your database, a raw file destination or recordset destination (depending on the size of your dataset). Then you could run through you data again and query your temp data and find the correct parent.</p>\n"
},
{
"answer_id": 286896,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like the way Macola (Exact Software) handles transactions. In their situation, a transaction is added to a table and it includes the reference to the original transaction in the row - for example, if the original transaction was a purchase in january and there is a payment in febrary, the february payment will include the transaction number from the january payment in a column refering to the parent. Since there is no foreign key relationship, each initial transaction is given a guid that can move between ledgers across the system.</p>\n"
},
{
"answer_id": 8520780,
"author": "deroby",
"author_id": 357429,
"author_profile": "https://Stackoverflow.com/users/357429",
"pm_score": 0,
"selected": false,
"text": "<p>As you say </p>\n\n<blockquote>\n <p>I have data loaded and various transformations on the data complete</p>\n</blockquote>\n\n<p>can I then assume you already have all the data available in a temporary or staging table ?\nIf so, simply doing an UPDATE of the field should do the trick I guess ? Assuming not all info might be available in the staging table, you could do a cascaded search for the value from the staging table first and then from the actual table if nothing was found. Doing this in one update would easily outperform doing it row by row. (especially if you have proper indexes available)</p>\n\n<pre><code>UPDATE staging_table\n SET parent_row_name = COALESCE(new.row_name, old.row_name, '#N/A#')\n FROM staging_table upd\n LEFT OUTER JOIN staging_table new\n ON new.row_key = upd.parent_row_key\n LEFT OUTER JOIN destination_table old\n ON old.row_key = upd.parent_row_key\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10868/"
] |
I have data loaded and various transformations on the data complete, the problem is there is a parent/child relationship managed in the data - best explained by an example
each row has (column names are made up)
```
row_key parent_row_key row_name parent_row_name
```
some rows have row\_key == parent\_row\_key (their own parent)
some rows relate to another row
(row 25 is the parent to row 44 for example).
In this case, row 25 is parent to row 44. I need to put row 25's row\_name in row 44's parent\_row\_name. How do I query the data in the pipeline for the value?
|
Can you not just split the data using a multicast and then do a merge-join against itself?
|
183,083 |
<p>I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in <pre> [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.</pre></p>
<p>My class implements the BuildListener interface. Various postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...</p>
<p>Can anyone shed light on what I'm doing wrong?
Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.</p>
|
[
{
"answer_id": 188700,
"author": "ILikeCoffee",
"author_id": 25270,
"author_profile": "https://Stackoverflow.com/users/25270",
"pm_score": 2,
"selected": true,
"text": "<p>I had this problem when I had two plugins providing an <code>ant.jar</code>.</p>\n\n<p>Make sure you use the <code>org.apache.ant</code> plugin and that there is no other plugin providing another <code>ant.jar</code>.</p>\n\n<p>Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).</p>\n\n<p>See <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=34466\" rel=\"nofollow noreferrer\">Eclipse Bug 34466</a>.</p>\n"
},
{
"answer_id": 226734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Follow the instructions as for working with contributed tasks and types found here:\n<a href=\"http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/ant_developing.htm\" rel=\"nofollow noreferrer\">Developing Ant tasks</a> and <a href=\"http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/ant_contributing_task.htm\" rel=\"nofollow noreferrer\">Contributed Ant tasks</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460599/"
] |
I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in
```
[myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.
```
My class implements the BuildListener interface. Various postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...
Can anyone shed light on what I'm doing wrong?
Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.
|
I had this problem when I had two plugins providing an `ant.jar`.
Make sure you use the `org.apache.ant` plugin and that there is no other plugin providing another `ant.jar`.
Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).
See [Eclipse Bug 34466](https://bugs.eclipse.org/bugs/show_bug.cgi?id=34466).
|
183,093 |
<p>I'm looking for ideas and opinions here, not a "real answer", I guess...</p>
<p>Back in the old VB6 days, there was this property called "Tag" in all controls, that was a useful way to store custom information related to a control. Every single control had it, and all was bliss...</p>
<p>Now, in .Net (at least for WebForms), it's not there anymore...</p>
<p>Does anyone have a good replacement for that?</p>
<p>I find this problem very often, where I have different functions that run at different times in the lifecycle, and they do stuff with my controls, and I want to keep them as separate as they are, but one should pass information to the other about specific controls.</p>
<p>I can think of a million alternatives (starting with a module-level dictionary, obviously), but none as clean as the good ol' Tag.</p>
<p>(NOTE: I know I can subclass ALL the controls and use my version instead. I'd rather not)</p>
<p>Any suggestions?
How do you solve this normally?
Any ideas on why they removed this i the first place?</p>
<p>EDIT: I'm looking for something Intra-Request, not Inter-Request. I don't need this information to still be there on a PostBack. This is between the _Load and the _PreRender methods, for example.</p>
<p>EDIT2: I DO know my ASp.Net and I do know the difference between the desktop and the web, guys!. I 'm just trying to use the abstraction that .Net gives me to the maximum. I understand the tradeoffs, believe me, and please answer assuming that I do.</p>
|
[
{
"answer_id": 183109,
"author": "harriyott",
"author_id": 5744,
"author_profile": "https://Stackoverflow.com/users/5744",
"pm_score": 0,
"selected": false,
"text": "<p>You can add attributes to some controls, but that seems to add some nasty HTML around the rendered control, something like <code><div attrName=\"attrValue\"></code>... (it might be a span though)</p>\n"
},
{
"answer_id": 183121,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what the tag property did in VB6, but maybe you're looking for the <code>Attributes</code> property of Web controls:</p>\n\n<pre><code>MyImgCtrl.Attributes[\"myCustomTagAttribute\"] = \"myVal\";\n</code></pre>\n"
},
{
"answer_id": 183126,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>You asked about ASP.Net, but vb6 was a desktop language, and so were it's 'tagged' controls. The VBScript used for classic asp didn't really have a concept of a control. </p>\n\n<p>Now in .Net, for desktop controls you can use inheritance, which is much more powerful than the old Tag property anyway. Inheritance applies to web controls as well, though you do have to be careful about using it to hold state.</p>\n"
},
{
"answer_id": 183142,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": -1,
"selected": false,
"text": "<p>You can use asp:Hidden controls to store data between posts. Like will says, there's no sense to have a tag property if you lose it's value.</p>\n"
},
{
"answer_id": 183262,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": true,
"text": "<p>No, there's no direct equivalent, but if you're using v3.5 of the Framework, you can add this functionality quite easily using an extension method. For example:</p>\n\n<pre><code>Imports System.Runtime.CompilerServices\n\nPublic Module Extensions\n <Extension()> _\n Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)\n If SessionTagDictionary.ContainsKey(TagName(ctl)) Then\n SessionTagDictionary(TagName(ctl)) = tagValue\n Else\n SessionTagDictionary.Add(TagName(ctl), tagValue)\n End If\n End Sub\n\n <Extension()> _\n Public Function GetTag(ByVal ctl As Control) As String\n If SessionTagDictionary.ContainsKey(TagName(ctl)) Then\n Return SessionTagDictionary(TagName(ctl))\n Else\n Return String.Empty\n End If\n End Function\n\n Private Function TagName(ByVal ctl As Control) As String\n Return ctl.Page.ClientID & \".\" & ctl.ClientID\n End Function\n\n Private Function SessionTagDictionary() As Dictionary(Of String, String)\n If HttpContext.Current.Session(\"TagDictionary\") Is Nothing Then\n SessionTagDictionary = New Dictionary(Of String, String)\n HttpContext.Current.Session(\"TagDictionary\") = SessionTagDictionary\n Else\n SessionTagDictionary = DirectCast(HttpContext.Current.Session(\"TagDictionary\"), _ \n Dictionary(Of String, String))\n End If\n End Function\nEnd Module\n</code></pre>\n\n<p>Then, in your ASP.NET pages, first bring your extensions into scope, e.g:</p>\n\n<pre><code>Imports WebApplication1.Extensions\n</code></pre>\n\n<p>...and then use it your controls as desired:</p>\n\n<pre><code>TextBox1.SetTag(\"Test\")\n\nLabel1.Text = TextBox1.GetTag\n</code></pre>\n\n<p>LATER EDIT: and if you really, really don't want to store your tags in the Session object, it's possible to stuff them into your Viewstate instead. This will of course mean that your tags <i>will</i> be exposed in the page markup sent to the user (albeit in obfuscated form), and, unfortunately, that some reflection-fu is required, since the ViewState property of a Page is marked as 'protected' for some reason. </p>\n\n<p>So, this code should pretty much be considered for entertainment purposes only, unless you actually <i>like</i> to raise eyebrows during code reviews:</p>\n\n<pre><code><Extension()> _\n Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)\n ViewState.Add(ctl.ID & \"_Tag\", tagValue)\n End Sub\n\n<Extension()> _\n Public Function GetTag(ByVal ctl As Control) As String\n Return ViewState(ctl.ID & \"_Tag\")\n End Function\n\nPrivate Function ViewState() As Web.UI.StateBag\n Return HttpContext.Current.Handler.GetType.InvokeMember(\"ViewState\", _\n Reflection.BindingFlags.GetProperty + _\n Reflection.BindingFlags.Instance + _\n Reflection.BindingFlags.NonPublic, _\n Nothing, HttpContext.Current.CurrentHandler, Nothing)\nEnd Function\n</code></pre>\n\n<p>FINAL EDIT (I promise...). And here's a way to get rid of the reflection: first, create a new class to expose the ViewState property with a usable protection level, then change your Code-Behind (.aspx.vb) classes to inherit that instead of Web.UI.Page, e.g.:</p>\n\n<pre><code>Public Class PageEx\n Inherits System.Web.UI.Page\n\n Friend ReadOnly Property ViewStateEx() As Web.UI.StateBag\n Get\n Return MyBase.ViewState\n End Get\n End Property\nEnd Class\n</code></pre>\n\n<p>Now, in your extensions module, you can access this newly defined property as:</p>\n\n<pre><code>Private Function ViewState() As Web.UI.StateBag\n Return DirectCast(HttpContext.Current.Handler, PageEx).ViewStateEx\nEnd Function\n</code></pre>\n\n<p>Still a bit of a hack, but much more acceptable than using reflection...</p>\n"
},
{
"answer_id": 183278,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": -1,
"selected": false,
"text": "<p>The <code>Tag</code> property was always a weird wart-like thing that <strong>was</strong> useful as something off of which you could hang any data you wanted. But it wasn't strongly-typed and it didn't really make for a coherent design. The property itself just hung off the control like a weird knob. They kept it in WinForms to facilitate porting code over from VB6. The new WPF <code>Control</code> class doesn't have a <code>Tag</code>. </p>\n\n<p>With .NET you have full object-orientation and adequate type polymorphism, so you can strongly-type whatever extra information you want to associate with a code, whether it's in a subclass or a <code>Dictionary<Control,TValue></code>.</p>\n\n<p>If it's in a single <code>Page</code> request and you want a general solution a Dictionary in the Page itself for each value type (e.g., <code>Dictionary<Control,string></code> and <code>Dictionary<Control,BusinessObject></code>) should be exactly what you need.</p>\n"
},
{
"answer_id": 183722,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the composite pattern instead of using inheritence:</p>\n\n<pre><code>public class TaggedControl<TControl, TTag> : Control \n where TControl : Control, new()\n { public TaggedControl() {this.Control= new TControl();}\n\n public TControl Control {get; private set;}\n public TTag Tag {get; set;} \n\n protected override void CreateChildControls(){Controls.Add(Control);}\n }\n\n var textBox = new TaggedControl<TextBox, string>();\n textBox.Tag = \"Test\";\n label.Text = textBox.Tag;\n</code></pre>\n"
},
{
"answer_id": 61001788,
"author": "Westley Bennett",
"author_id": 7308469,
"author_profile": "https://Stackoverflow.com/users/7308469",
"pm_score": 1,
"selected": false,
"text": "<p>I took mdb's brilliant solution, and ported it over to C# for my own needs. I also changed the Tags from a Dictionary of String, String, to a Dictionary of String, Object... since theoretically any type of object can be stored in the Session, not just strings:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Web;\nusing System.Web.UI;\n\npublic static class Extensions\n{\n public static void SetTag(this Control ctl, object tagValue)\n {\n if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))\n ctl.SessionTagDictionary()[TagName(ctl)] = tagValue;\n else\n ctl.SessionTagDictionary().Add(TagName(ctl), tagValue);\n }\n\n public static object GetTag(this Control ctl)\n {\n if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))\n return ctl.SessionTagDictionary()[TagName(ctl)];\n else\n return string.Empty;\n }\n\n private static string TagName(Control ctl)\n {\n return ctl.Page.ClientID + \".\" + ctl.ClientID;\n }\n\n private static Dictionary<string, object> SessionTagDictionary(this Control ctl)\n {\n Dictionary<string, object> SessionTagDictionary;\n if (HttpContext.Current.Session[\"TagDictionary\"] == null)\n {\n SessionTagDictionary = new Dictionary<string, object>();\n HttpContext.Current.Session[\"TagDictionary\"] = SessionTagDictionary;\n }\n else\n SessionTagDictionary = (Dictionary<string, object>)HttpContext.Current.Session[\"TagDictionary\"];\n return SessionTagDictionary;\n }\n}\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
I'm looking for ideas and opinions here, not a "real answer", I guess...
Back in the old VB6 days, there was this property called "Tag" in all controls, that was a useful way to store custom information related to a control. Every single control had it, and all was bliss...
Now, in .Net (at least for WebForms), it's not there anymore...
Does anyone have a good replacement for that?
I find this problem very often, where I have different functions that run at different times in the lifecycle, and they do stuff with my controls, and I want to keep them as separate as they are, but one should pass information to the other about specific controls.
I can think of a million alternatives (starting with a module-level dictionary, obviously), but none as clean as the good ol' Tag.
(NOTE: I know I can subclass ALL the controls and use my version instead. I'd rather not)
Any suggestions?
How do you solve this normally?
Any ideas on why they removed this i the first place?
EDIT: I'm looking for something Intra-Request, not Inter-Request. I don't need this information to still be there on a PostBack. This is between the \_Load and the \_PreRender methods, for example.
EDIT2: I DO know my ASp.Net and I do know the difference between the desktop and the web, guys!. I 'm just trying to use the abstraction that .Net gives me to the maximum. I understand the tradeoffs, believe me, and please answer assuming that I do.
|
No, there's no direct equivalent, but if you're using v3.5 of the Framework, you can add this functionality quite easily using an extension method. For example:
```
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)
If SessionTagDictionary.ContainsKey(TagName(ctl)) Then
SessionTagDictionary(TagName(ctl)) = tagValue
Else
SessionTagDictionary.Add(TagName(ctl), tagValue)
End If
End Sub
<Extension()> _
Public Function GetTag(ByVal ctl As Control) As String
If SessionTagDictionary.ContainsKey(TagName(ctl)) Then
Return SessionTagDictionary(TagName(ctl))
Else
Return String.Empty
End If
End Function
Private Function TagName(ByVal ctl As Control) As String
Return ctl.Page.ClientID & "." & ctl.ClientID
End Function
Private Function SessionTagDictionary() As Dictionary(Of String, String)
If HttpContext.Current.Session("TagDictionary") Is Nothing Then
SessionTagDictionary = New Dictionary(Of String, String)
HttpContext.Current.Session("TagDictionary") = SessionTagDictionary
Else
SessionTagDictionary = DirectCast(HttpContext.Current.Session("TagDictionary"), _
Dictionary(Of String, String))
End If
End Function
End Module
```
Then, in your ASP.NET pages, first bring your extensions into scope, e.g:
```
Imports WebApplication1.Extensions
```
...and then use it your controls as desired:
```
TextBox1.SetTag("Test")
Label1.Text = TextBox1.GetTag
```
LATER EDIT: and if you really, really don't want to store your tags in the Session object, it's possible to stuff them into your Viewstate instead. This will of course mean that your tags *will* be exposed in the page markup sent to the user (albeit in obfuscated form), and, unfortunately, that some reflection-fu is required, since the ViewState property of a Page is marked as 'protected' for some reason.
So, this code should pretty much be considered for entertainment purposes only, unless you actually *like* to raise eyebrows during code reviews:
```
<Extension()> _
Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)
ViewState.Add(ctl.ID & "_Tag", tagValue)
End Sub
<Extension()> _
Public Function GetTag(ByVal ctl As Control) As String
Return ViewState(ctl.ID & "_Tag")
End Function
Private Function ViewState() As Web.UI.StateBag
Return HttpContext.Current.Handler.GetType.InvokeMember("ViewState", _
Reflection.BindingFlags.GetProperty + _
Reflection.BindingFlags.Instance + _
Reflection.BindingFlags.NonPublic, _
Nothing, HttpContext.Current.CurrentHandler, Nothing)
End Function
```
FINAL EDIT (I promise...). And here's a way to get rid of the reflection: first, create a new class to expose the ViewState property with a usable protection level, then change your Code-Behind (.aspx.vb) classes to inherit that instead of Web.UI.Page, e.g.:
```
Public Class PageEx
Inherits System.Web.UI.Page
Friend ReadOnly Property ViewStateEx() As Web.UI.StateBag
Get
Return MyBase.ViewState
End Get
End Property
End Class
```
Now, in your extensions module, you can access this newly defined property as:
```
Private Function ViewState() As Web.UI.StateBag
Return DirectCast(HttpContext.Current.Handler, PageEx).ViewStateEx
End Function
```
Still a bit of a hack, but much more acceptable than using reflection...
|
183,101 |
<p>I use the MFC list control in report view with grid lines to display data in a vaguely spreadsheet manner.</p>
<p>Sometimes when the user scrolls vertically through the control, extra grid lines are drawn, which looks terrible.</p>
<p>This does not happen when the slider or the mousewheel are used to scroll, only when the little down arrow button at the bottom of the scroll control is used.</p>
<p>It seems that this occurs when the size of the list control window is not an exact even number of rows, so that a partial row is visible at the bottom.</p>
<p>If I adjust the size of the list control so that there is no partial rows visible, the problem is solved. However, it will appear when the program is run on another computer, presumably because the number of pixels occupied by a row changes. </p>
<p>I am assuming that it is an interaction between screen resolution, font size and "dialog units".</p>
<p>I guess that I need to programmatically force the size of the control when it is created. But what size?</p>
<p>I have tried using the ApproximateViewRect() method but I cannot get it to work. Perhaps this method does not know about report view?</p>
<p>The other method, I suppose, would be to create my own specialization of CListCtrl and over-ride whatever method is doing the scrolling. This seems likely to be a lot of work.</p>
<p>This screenshot shows a closely related problem where the grid lines go missing</p>
<p><img src="https://i.stack.imgur.com/K5XzV.jpg" alt="alt text"></p>
<p>and here is one with the extra grid lines</p>
<p><img src="https://i.stack.imgur.com/6pADr.jpg" alt="alt text"></p>
<p>The only difference between these two and between them and one which scrolls perfectly is a few pixels different in the vertical size of the control.</p>
|
[
{
"answer_id": 183151,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "<p>Is this happening with the stock listview, or is it custom draw? I've never seen redrawing issues with the standard windows controls.</p>\n\n<p>Maybe you can post a screenshot to illustrate the problem? I presume you'd prefer to fix the redraw issue and not size the control exactly?</p>\n"
},
{
"answer_id": 183845,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 1,
"selected": false,
"text": "<p>I recall this being a bug in the ListView (not just through MFC, but the common control in general) itself. A quick google on this seems to hit a lot of people coming to that same conclusion. I guess since Windows Explorer doesn't have gridlines they don't feel the need fix this? I remember this back in the late 90's.</p>\n\n<p>I guess the trick would be to invalidate the window after a scroll - maybe in response to a VSCROLL message? Just a guess.</p>\n"
},
{
"answer_id": 183926,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 3,
"selected": false,
"text": "<p>This is indeed a bug related to \"smooth scrolling,\" here's a workaround:</p>\n\n<pre><code>void CMyListCtrl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n __super::OnVScroll(nSBCode, nPos, pScrollBar);\n Invalidate();\n UpdateWindow();\n}\n</code></pre>\n"
},
{
"answer_id": 184315,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": -1,
"selected": true,
"text": "<p>To fix this bug in the MFC List Control you need to specialize the control, over-ride the method wich responds to the scroll, and force it to redraw the list completely after it has done the scroll.</p>\n\n<p>interface header</p>\n\n<pre><code>class cSmoothListControl : public CListCtrl\n{\npublic:\n DECLARE_MESSAGE_MAP()\n afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);\n};\n</code></pre>\n\n<p>implementation:</p>\n\n<pre><code>BEGIN_MESSAGE_MAP(cSmoothListControl, CListCtrl)\nON_WM_VSCROLL()\nEND_MESSAGE_MAP()\n\nvoid cSmoothListControl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n // call base class method to do scroll\n CListCtrl::OnVScroll(nSBCode, nPos, pScrollBar);\n\n // force redraw to cover any mess that may be created\n Invalidate();\n UpdateWindow();\n}\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582/"
] |
I use the MFC list control in report view with grid lines to display data in a vaguely spreadsheet manner.
Sometimes when the user scrolls vertically through the control, extra grid lines are drawn, which looks terrible.
This does not happen when the slider or the mousewheel are used to scroll, only when the little down arrow button at the bottom of the scroll control is used.
It seems that this occurs when the size of the list control window is not an exact even number of rows, so that a partial row is visible at the bottom.
If I adjust the size of the list control so that there is no partial rows visible, the problem is solved. However, it will appear when the program is run on another computer, presumably because the number of pixels occupied by a row changes.
I am assuming that it is an interaction between screen resolution, font size and "dialog units".
I guess that I need to programmatically force the size of the control when it is created. But what size?
I have tried using the ApproximateViewRect() method but I cannot get it to work. Perhaps this method does not know about report view?
The other method, I suppose, would be to create my own specialization of CListCtrl and over-ride whatever method is doing the scrolling. This seems likely to be a lot of work.
This screenshot shows a closely related problem where the grid lines go missing

and here is one with the extra grid lines

The only difference between these two and between them and one which scrolls perfectly is a few pixels different in the vertical size of the control.
|
To fix this bug in the MFC List Control you need to specialize the control, over-ride the method wich responds to the scroll, and force it to redraw the list completely after it has done the scroll.
interface header
```
class cSmoothListControl : public CListCtrl
{
public:
DECLARE_MESSAGE_MAP()
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
};
```
implementation:
```
BEGIN_MESSAGE_MAP(cSmoothListControl, CListCtrl)
ON_WM_VSCROLL()
END_MESSAGE_MAP()
void cSmoothListControl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// call base class method to do scroll
CListCtrl::OnVScroll(nSBCode, nPos, pScrollBar);
// force redraw to cover any mess that may be created
Invalidate();
UpdateWindow();
}
```
|
183,108 |
<p>I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.</p>
<p>Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?</p>
|
[
{
"answer_id": 183157,
"author": "Jeff B",
"author_id": 25879,
"author_profile": "https://Stackoverflow.com/users/25879",
"pm_score": 1,
"selected": false,
"text": "<p>Usually, yes.</p>\n\n<p>All the compiler really knows is that your program can create at least one instance of each class. But it doesn't know what you will do with those instances. So the code will almost certain be generated.</p>\n\n<p>That said, if the methods in question are <em>not</em> virtual, and are never called, the <em>linker</em> can remove them with its normal dead code removal features. So the generated (and compiled) code won't be in the final EXE.</p>\n\n<p>Also this will largely depend on the C++ compiler being used because they're not all the same.</p>\n"
},
{
"answer_id": 183235,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 6,
"selected": true,
"text": "<p>Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called.</p>\n\n<p>This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below)</p>\n\n<blockquote>\n <p>An implementation shall not implicitly instantiate a function template, a variable template, a member\n template, a non-virtual member function, a member class, a static data member of a class template, or\n a substatement of a <code>constexpr</code> if statement (9.4.1), unless such instantiation is required</p>\n</blockquote>\n\n<p>Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example:</p>\n\n<pre><code>template <class T>\nclass Xyzzy\n{\npublic:\n void CallFoo() { t.foo(); } // Invoke T::foo()\n void CallBar() { t.bar(); } // Invoke T::bar()\n\nprivate:\n T t;\n};\n\nclass FooBar\n{\npublic:\n void foo() { ... }\n void bar() { ... }\n};\n\nclass BarOnly\n{\npublic:\n void bar() { ... }\n};\n\nint main(int argc, const char** argv)\n{\n Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated\n Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated\n\n foobar.CallFoo(); // Calls FooBar::foo()\n foobar.CallBar(); // Calls FooBar::bar()\n\n baronly.CallBar(); // Calls BarOnly::bar()\n\n return 0;\n}\n</code></pre>\n\n<p>This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool.</p>\n\n<p>Note, however, that \"instantiation\" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.</p>\n"
},
{
"answer_id": 184233,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "<p>I think it depends on the compiler and settings. For example, I believe MSVC6 generated everything, but VS2005 does not. The spec says the compiler should not, but in the real world, it depends on the actual compiler (there are many work-arounds in boost for MSVC6, for example). The linker can remove unreferenced functions if /opt:ref is enabled (for VS, equivalent options exist for other compilers).</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18721/"
] |
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.
Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?
|
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called.
This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below)
>
> An implementation shall not implicitly instantiate a function template, a variable template, a member
> template, a non-virtual member function, a member class, a static data member of a class template, or
> a substatement of a `constexpr` if statement (9.4.1), unless such instantiation is required
>
>
>
Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example:
```
template <class T>
class Xyzzy
{
public:
void CallFoo() { t.foo(); } // Invoke T::foo()
void CallBar() { t.bar(); } // Invoke T::bar()
private:
T t;
};
class FooBar
{
public:
void foo() { ... }
void bar() { ... }
};
class BarOnly
{
public:
void bar() { ... }
};
int main(int argc, const char** argv)
{
Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated
Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated
foobar.CallFoo(); // Calls FooBar::foo()
foobar.CallBar(); // Calls FooBar::bar()
baronly.CallBar(); // Calls BarOnly::bar()
return 0;
}
```
This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool.
Note, however, that "instantiation" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.
|
183,115 |
<p>I'm writing a shell script to do some web server configuration. I need to disable all currently active virtual hosts. <code>a2dissite</code> doesn't accept multiple arguments, so I can't do</p>
<pre><code>a2dissite `ls /etc/apache2/sites-enabled`
</code></pre>
<p>Should I use <code>find</code>? Is it safe to manually delete the symlinks in <code>/etc/apache2/sites-enabled</code>?</p>
|
[
{
"answer_id": 183141,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": -1,
"selected": false,
"text": "<p>you can edit the httpd.conf and delete the include line for the virtual hosts (at the bottom of the file) </p>\n"
},
{
"answer_id": 183186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can just delete the symlinks, or move the entire directory away. There is no special database or other metadata besides those links.</p>\n"
},
{
"answer_id": 183188,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "<p>Is your script Debian only? If so, you can safely delete all the symlinks in sites-enabled, that will work as long as all sites have been written correctly, in the sites-available directory.</p>\n\n<p>For example:</p>\n\n<pre><code> find /etc/apache2/sites-enabled/ -type l -exec rm -i \"{}\" \\;\n</code></pre>\n\n<p>will protect you against someone who has actually written a file instead of a symlink in that directory.</p>\n\n<p>(remove the -i from rm for an automatic script, of course)</p>\n"
},
{
"answer_id": 183194,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 1,
"selected": false,
"text": "<p>I never use 'a2dissite ' and always delete and create the links in /etc/apache2/sites-enabled manually so yes, I'd say it's pretty safe.</p>\n"
},
{
"answer_id": 183195,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": -1,
"selected": false,
"text": "<p>Apparently, you can just install the latest Ubuntu ;)</p>\n"
},
{
"answer_id": 183210,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 4,
"selected": false,
"text": "<p>After a little more research, I found out that <code>a2dissite</code> is just a shell script, and it basically just calls <code>rm</code>. So, like other responses, I agree that it is safe to do</p>\n\n<pre><code>rm /etc/apache2/sites-enabled/*\n</code></pre>\n"
},
{
"answer_id": 24546177,
"author": "Rob",
"author_id": 491950,
"author_profile": "https://Stackoverflow.com/users/491950",
"pm_score": 5,
"selected": false,
"text": "<p>You can just do the following:</p>\n<pre><code>sudo a2dissite '*'\n</code></pre>\n<p>or:</p>\n<pre><code>sudo a2dissite\n</code></pre>\n<p>and it will prompt you for the ones you want to disable.</p>\n<p>When you have finished disabling sites, restart apache2 server:</p>\n<pre><code>sudo systemctl restart apache2\n</code></pre>\n<p>or just reload apache configuration without a full restart:</p>\n<pre><code>sudo service apache2 reload\n</code></pre>\n"
},
{
"answer_id": 27671518,
"author": "Supravat Mondal",
"author_id": 2460470,
"author_profile": "https://Stackoverflow.com/users/2460470",
"pm_score": 3,
"selected": false,
"text": "<p>To remove the host file just delete it.\nIf you just want to <strong>dissable</strong> the site, use</p>\n\n<pre><code>sudo a2dissite sitename\n</code></pre>\n\n<p>Restart apache2</p>\n\n<pre><code>sudo /etc/init.d/apache2 reload\n</code></pre>\n\n<p>Again to remove (delete)it completely from the system,</p>\n\n<pre><code>sudo rm /etc/apache2/sites-available/sitename\n</code></pre>\n\n<p>I would also disable it first before deleting the file</p>\n"
},
{
"answer_id": 45646505,
"author": "Telvin Nguyen",
"author_id": 1041471,
"author_profile": "https://Stackoverflow.com/users/1041471",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my workaround, first type:</p>\n\n<p><code># a2dissite</code> (type this command without any argument, it would prompt to ask you choose the next line)</p>\n\n<blockquote>\n <p>Your choices are: <strong>siteA siteB siteC siteD</strong></p>\n \n <p>Which site(s) do you want to disable (wildcards ok)?</p>\n</blockquote>\n\n<p>Now you just copy all of above list of sites (<strong>siteA siteB siteC siteD</strong>) and paste into as your answer, then Enter.</p>\n\n<p>The output result would be:</p>\n\n<pre><code>removing dangling symlink /etc/apache2/sites-enabled/siteA.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteB.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteC.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteD.conf\n</code></pre>\n\n<p>This approach will help us to optional to choose to a long list of names of site should be removed or intact.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
I'm writing a shell script to do some web server configuration. I need to disable all currently active virtual hosts. `a2dissite` doesn't accept multiple arguments, so I can't do
```
a2dissite `ls /etc/apache2/sites-enabled`
```
Should I use `find`? Is it safe to manually delete the symlinks in `/etc/apache2/sites-enabled`?
|
Is your script Debian only? If so, you can safely delete all the symlinks in sites-enabled, that will work as long as all sites have been written correctly, in the sites-available directory.
For example:
```
find /etc/apache2/sites-enabled/ -type l -exec rm -i "{}" \;
```
will protect you against someone who has actually written a file instead of a symlink in that directory.
(remove the -i from rm for an automatic script, of course)
|
183,118 |
<p>I've got an application that is very graphics intensive and built on DirectX and Windows Forms. It has an automation and replay framework around which is built an automated testing system. Unfortunately, when the tests run unattended during a nightly build, the display is inactive or tied up with the screensaver, and our IT security policies don't allow us to disable that.</p>
<p>So my question: is there a way to do a "screen" capture of an application that is running without the display? I'd like to ensure that the graphics card is engaged so that my rendering pipeline is the same, but the testing framework shouldn't need to care about the state of the display.</p>
<p>Any help wildly appreciated!</p>
|
[
{
"answer_id": 183331,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 0,
"selected": false,
"text": "<p>Install a VM and run the application in that. If you're running a screen saver I doubt your video card is even generating the GUI for the application.</p>\n"
},
{
"answer_id": 183354,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand correct, all you want to to is take a screen grab of a specific application and not have the result be affected by a possibly running screensaver? As far as I know, simply doing <code>GetDIBits</code> on the HDC of the correct window should do the trick and not care about the screensaver.</p>\n"
},
{
"answer_id": 186255,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 3,
"selected": true,
"text": "<p>Since you're mentioned rendering pipeline, so I'm assuming you're using Direct3d, if so, you can save the backbuffer of the frame. I did that when I was still using VB.Net + MDX</p>\n\n<pre><code>Dim tempSurface As Direct3D.Surface\ntempSurface = device.GetBackBuffer(0, 0, Direct3D.BackBufferType.Mono)\nDirect3D.SurfaceLoader.Save(tempFilename, Direct3D.ImageFileFormat.Png, tempSurface)\n</code></pre>\n\n<p>You can easily converted that do any programming language of you choice, it's basically calling Direct3d's API. Though, you need to configure you backbuffer and Present parameters as</p>\n\n<pre><code>' Need to use flip to enable screen capture\npresentParams.SwapEffect = Direct3D.SwapEffect.Flip \npresentParams.PresentationInterval = Direct3D.PresentInterval.One\n</code></pre>\n"
},
{
"answer_id": 5669804,
"author": "Paul",
"author_id": 708794,
"author_profile": "https://Stackoverflow.com/users/708794",
"pm_score": 0,
"selected": false,
"text": "<p>You might find this code to be really slow, however you can get a massive speedup by setting the <code>PresentParams.PresentFlag = PresentFlag.LockableBackBuffer</code></p>\n\n<p>Also, you don't need to set <code>PresentInterval.One</code> or <code>SwapEffect.Flip</code>, they can be left at .Default and .Discard repsectively.</p>\n\n<p>(Note that this speedup does not work if you are using multisampling, be sure that <code>PresentParams.Multisample = Multisample.None</code> . If you have an Nvidia card you can still get antialiasing by setting the option in the Nvidia control panel to override the application setting to what you want!)</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382162/"
] |
I've got an application that is very graphics intensive and built on DirectX and Windows Forms. It has an automation and replay framework around which is built an automated testing system. Unfortunately, when the tests run unattended during a nightly build, the display is inactive or tied up with the screensaver, and our IT security policies don't allow us to disable that.
So my question: is there a way to do a "screen" capture of an application that is running without the display? I'd like to ensure that the graphics card is engaged so that my rendering pipeline is the same, but the testing framework shouldn't need to care about the state of the display.
Any help wildly appreciated!
|
Since you're mentioned rendering pipeline, so I'm assuming you're using Direct3d, if so, you can save the backbuffer of the frame. I did that when I was still using VB.Net + MDX
```
Dim tempSurface As Direct3D.Surface
tempSurface = device.GetBackBuffer(0, 0, Direct3D.BackBufferType.Mono)
Direct3D.SurfaceLoader.Save(tempFilename, Direct3D.ImageFileFormat.Png, tempSurface)
```
You can easily converted that do any programming language of you choice, it's basically calling Direct3d's API. Though, you need to configure you backbuffer and Present parameters as
```
' Need to use flip to enable screen capture
presentParams.SwapEffect = Direct3D.SwapEffect.Flip
presentParams.PresentationInterval = Direct3D.PresentInterval.One
```
|
183,124 |
<p>I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work</p>
<pre><code>with Random(Value) as
(
select rand() Value
union all
select rand() from Random
)select top 10 * from Random
</code></pre>
<p>Whats the preffered workaround?</p>
|
[
{
"answer_id": 183138,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 0,
"selected": false,
"text": "<p>I'm currently using this:</p>\n\n<pre><code>with Random(Value) as\n(\n select rand(checksum(newid())) Value\n union all\n select rand(checksum(newid())) from Random \n)select top 10 * from Random\n</code></pre>\n\n<p>but that seems overly hackish :S\nWhy doesnt rand get reevaluated in the first version?</p>\n"
},
{
"answer_id": 183183,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 3,
"selected": true,
"text": "<p>have you tries something like this (found at <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2004/11/22/2927.aspx\" rel=\"nofollow noreferrer\">http://weblogs.sqlteam.com</a> ) :</p>\n\n<pre><code>CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\nGO\n</code></pre>\n\n<p>create a function </p>\n\n<pre><code>CREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\nGO\n</code></pre>\n\n<p>then you can call it in your selects as normal\nSelect dbo.RandNumber() , * from myTable</p>\n\n<p>or from their comments:</p>\n\n<pre><code>select RAND(CAST(NEWID() AS BINARY(6))), * from myTable\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21182/"
] |
I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work
```
with Random(Value) as
(
select rand() Value
union all
select rand() from Random
)select top 10 * from Random
```
Whats the preffered workaround?
|
have you tries something like this (found at [http://weblogs.sqlteam.com](http://weblogs.sqlteam.com/jeffs/archive/2004/11/22/2927.aspx) ) :
```
CREATE VIEW vRandNumber
AS
SELECT RAND() as RandNumber
GO
```
create a function
```
CREATE FUNCTION RandNumber()
RETURNS float
AS
BEGIN
RETURN (SELECT RandNumber FROM vRandNumber)
END
GO
```
then you can call it in your selects as normal
Select dbo.RandNumber() , \* from myTable
or from their comments:
```
select RAND(CAST(NEWID() AS BINARY(6))), * from myTable
```
|
183,158 |
<pre><code>public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
</code></pre>
<p>Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...</p>
<p>Edit:</p>
<p>Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.</p>
|
[
{
"answer_id": 183177,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 0,
"selected": false,
"text": "<p>At least put a comment that PrivateMethod must have a non-null FooBar and that PublicMethod checks this.</p>\n"
},
{
"answer_id": 183180,
"author": "Soraz",
"author_id": 24610,
"author_profile": "https://Stackoverflow.com/users/24610",
"pm_score": 2,
"selected": false,
"text": "<p>I would say no.</p>\n\n<p>While it certainly holds true that you in <em>this</em> case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write \nPublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.</p>\n"
},
{
"answer_id": 183203,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to also mark the \"private\" method as private or protected.</p>\n"
},
{
"answer_id": 183246,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Since the public method doesn't really use foobar, I'm not sure why it's checking. The current private method cares, but it's the private method's responsibility to care. Indeed, the whole point of a private method is to delegate all the responsibilities to it.</p>\n\n<p>A method checks the input it actually uses; it doesn't check stuff it's just passing through.</p>\n\n<p>If a different subclass has the same public method, but some different private method implementation -- one that can tolerate nulls -- what now? You have a public method that now has wrong constraints for the new subclass.</p>\n\n<p>You want to do as little as possible in the public method so that various private implementations are free to do the right thing. Don't \"over-check\" or \"just-in-case\" check. Delegate responsibility.</p>\n"
},
{
"answer_id": 183296,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 1,
"selected": false,
"text": "<p>I'd error check everything you can, you never know when something might happen that you didn't think about. (and its better safe than sorry)</p>\n"
},
{
"answer_id": 183549,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "<p>That depends if a null-value indicates an error for a method. Remember that methods could also be called messages to an object; they operate on the state of the object aswell. Parameters can specialize the kind of message sent.</p>\n\n<ul>\n<li>If publicMethod() does not use a parameter and changes the state of the instance while privateMethod() uses the parameter, do not consider it an error in publicMethod, but do in privateMethod().</li>\n<li>If publicMethod() does not change state, consider it an error.</li>\n</ul>\n\n<p>You could see the latter case as providing an interface to the internal functioning of an object.</p>\n"
},
{
"answer_id": 183574,
"author": "Vlad Gudim",
"author_id": 22088,
"author_profile": "https://Stackoverflow.com/users/22088",
"pm_score": 1,
"selected": false,
"text": "<p>When using design by contract (<a href=\"http://en.wikipedia.org/wiki/Design_by_contract\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Design_by_contract</a>) it’s normally client’s (public method) responsibility to make correct invocation, i.e. pass on valid parameters. In this particular scenario it depends whether null belongs to a set of valid input values, therefore there are 3 options: </p>\n\n<p>1) Null is valid value: throwing exceptions or errors would have meant breaking the contract, the server (private method) has to process the null and shouldn’t complain.</p>\n\n<p>2) Null is invalid value and passed by code within your control: it is up to the server (private method) to decide how to react. Obviously, throwing an exception is more graceful way of handling the situation, but it has a cost of having to handle that exception somewhere else up the stack. Exceptions are not the best way to deal with violation of contract caused by programming blunders. You really should throw exceptions not when a contract is already violated but when it cannot be fulfilled because of environmental problems what cannot be controlled in software. Blunders are better handled by sticking an assertion into the beginning of the private method to check that the parameter is not null. This will keep the complexity of your code down, there is no cost of having to handle the exception up the stack and it will achieve the goal of highlighting broken contracts during testing.</p>\n\n<p>3) Then there is defensive programming (<a href=\"http://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Defensive_programming</a>). When dealing with parameters passed by an external code outside your control the immediate layer of your code needs to run paranoid level of checks and return errors according to its communication contract with the external world. Then, going deeper into the code layers not exposed externally, it still makes more sense to stick to the programming by contract.</p>\n"
},
{
"answer_id": 183670,
"author": "Rhys",
"author_id": 22169,
"author_profile": "https://Stackoverflow.com/users/22169",
"pm_score": 0,
"selected": false,
"text": "<p>I'd consider the answer to be \"yes, do the check again\" because:-</p>\n\n<ul>\n<li>The private member could be reused again in the future from a different path through the code, so program defensively against that situation.</li>\n<li>If you perform unit tests on private methods</li>\n</ul>\n\n<p>My view might change if I had a static analyser that could pick this up and not flag the potential use of a null reference in the private method.</p>\n"
},
{
"answer_id": 183848,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>In cases where PrivateMethod will be called frequently with input that has already been verified, and only rarely with user input, Then I would use the PublicMethod/PrivateMethod concept with no error checking on PrivateMethod (and with PublicMethod doing nothing other then checking the parameters and calling PrivateMethod)</p>\n\n<p>I would also call the private method something like PublicMethod_impl (for \"implementation\") so it's clear that it's an internal use/ no checking method.</p>\n\n<p>I maintain that this design leads to <em>more</em> robust application, as it forces you to think about what's checked when. Too often people who always check parameters fall into the trap of \"I've checked something, therefore I've checked everything\".</p>\n\n<p>As an example of this, a former co-worker (programming in C) would, before using a pointer, always check to see if it was null. Generally, the pointers in his code were initialized as startup and never changed, so the chances of it being null were quite low. Moreover, the pointer has one correct value and 65535 possible wrong values, and he was only checking for one of those wrong values.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
```
public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
```
Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...
Edit:
Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.
|
I would say no.
While it certainly holds true that you in *this* case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write
PublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.
|
183,161 |
<p>What's the best way to break from nested loops in Javascript?</p>
<pre><code>//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
</code></pre>
|
[
{
"answer_id": 183168,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 8,
"selected": false,
"text": "<p>Wrap that up in a function and then just <code>return</code>.</p>\n"
},
{
"answer_id": 183197,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 11,
"selected": true,
"text": "<p>Just like Perl,</p>\n<pre><code>loop1:\n for (var i in set1) {\nloop2:\n for (var j in set2) {\nloop3:\n for (var k in set3) {\n break loop2; // breaks out of loop3 and loop2\n }\n }\n }\n</code></pre>\n<p>as defined in EMCA-262 section 12.12. <a href=\"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/label\" rel=\"noreferrer\">[MDN Docs]</a></p>\n<p>Unlike C, these labels can only be used for <a href=\"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/continue\" rel=\"noreferrer\"><code>continue</code></a> and <a href=\"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/break\" rel=\"noreferrer\"><code>break</code></a>, as Javascript does not have <code>goto</code>.</p>\n"
},
{
"answer_id": 184513,
"author": "harley.333",
"author_id": 26259,
"author_profile": "https://Stackoverflow.com/users/26259",
"pm_score": 5,
"selected": false,
"text": "<pre><code>var str = \"\";\nfor (var x = 0; x < 3; x++) {\n (function() { // here's an anonymous function\n for (var y = 0; y < 3; y++) {\n for (var z = 0; z < 3; z++) {\n // you have access to 'x' because of closures\n str += \"x=\" + x + \" y=\" + y + \" z=\" + z + \"<br />\";\n if (x == z && z == 2) {\n return;\n }\n }\n }\n })(); // here, you execute your anonymous function\n}\n</code></pre>\n\n<p>How's that? :)</p>\n"
},
{
"answer_id": 727811,
"author": "aleemb",
"author_id": 50475,
"author_profile": "https://Stackoverflow.com/users/50475",
"pm_score": 7,
"selected": false,
"text": "<p>I'm a little late to the party but the following is a language-agnostic approach which doesn't use GOTO/labels or function wrapping:</p>\n\n<pre><code>for (var x = Set1.length; x > 0; x--)\n{\n for (var y = Set2.length; y > 0; y--)\n {\n for (var z = Set3.length; z > 0; z--)\n {\n z = y = -1; // terminates second loop\n // z = y = x = -1; // terminate first loop\n }\n }\n}\n</code></pre>\n\n<p>On the upside it flows naturally which should please the non-GOTO crowd. On the downside, the inner loop needs to complete the current iteration before terminating so it might not be applicable in some scenarios.</p>\n"
},
{
"answer_id": 1138394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Quite simple:</p>\n\n<pre><code>var a = [1, 2, 3];\nvar b = [4, 5, 6];\nvar breakCheck1 = false;\n\nfor (var i in a) {\n for (var j in b) {\n breakCheck1 = true;\n break;\n }\n if (breakCheck1) break;\n}\n</code></pre>\n"
},
{
"answer_id": 11461531,
"author": "Triqui",
"author_id": 1522151,
"author_profile": "https://Stackoverflow.com/users/1522151",
"pm_score": -1,
"selected": false,
"text": "<pre><code>XXX.Validation = function() {\n var ok = false;\nloop:\n do {\n for (...) {\n while (...) {\n if (...) {\n break loop; // Exist the outermost do-while loop\n }\n if (...) {\n continue; // skips current iteration in the while loop\n }\n }\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n ok = true;\n break;\n } while(true);\n CleanupAndCallbackBeforeReturning(ok);\n return ok;\n};\n</code></pre>\n"
},
{
"answer_id": 19734110,
"author": "zord",
"author_id": 2381321,
"author_profile": "https://Stackoverflow.com/users/2381321",
"pm_score": 6,
"selected": false,
"text": "<p>I realize this is a really old topic, but since my standard approach is not here yet, I thought I post it for the future googlers.</p>\n\n<pre><code>var a, b, abort = false;\nfor (a = 0; a < 10 && !abort; a++) {\n for (b = 0; b < 10 && !abort; b++) {\n if (condition) {\n doSomeThing();\n abort = true;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30158489,
"author": "Drakes",
"author_id": 1938889,
"author_profile": "https://Stackoverflow.com/users/1938889",
"pm_score": 4,
"selected": false,
"text": "<p>How about using no breaks at all, no abort flags, and no extra condition checks. This version just blasts the loop variables (makes them <code>Number.MAX_VALUE</code>) when the condition is met and forces all the loops to terminate elegantly.</p>\n\n<pre><code>// No breaks needed\nfor (var i = 0; i < 10; i++) {\n for (var j = 0; j < 10; j++) {\n if (condition) {\n console.log(\"condition met\");\n i = j = Number.MAX_VALUE; // Blast the loop variables\n }\n }\n}\n</code></pre>\n\n<p>There was a similar-ish answer for decrementing-type nested loops, but this works for incrementing-type nested loops without needing to consider each loop's termination value for simple loops.</p>\n\n<p>Another example:</p>\n\n<pre><code>// No breaks needed\nfor (var i = 0; i < 89; i++) {\n for (var j = 0; j < 1002; j++) {\n for (var k = 0; k < 16; k++) {\n for (var l = 0; l < 2382; l++) {\n if (condition) {\n console.log(\"condition met\");\n i = j = k = l = Number.MAX_VALUE; // Blast the loop variables\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31928837,
"author": "Nick Perkins",
"author_id": 138939,
"author_profile": "https://Stackoverflow.com/users/138939",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Coffeescript, there is a convenient \"do\" keyword that makes it easier to define and immediately execute an anonymous function:</p>\n\n<pre><code>do ->\n for a in first_loop\n for b in second_loop\n if condition(...)\n return\n</code></pre>\n\n<p>...so you can simply use \"return\" to get out of the loops.</p>\n"
},
{
"answer_id": 32189353,
"author": "Zachary Ryan Smith",
"author_id": 4087001,
"author_profile": "https://Stackoverflow.com/users/4087001",
"pm_score": 2,
"selected": false,
"text": "<p>I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that <code>Object.keys()</code> enumerates only an object's own enumerable properties, whereas <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow\">\"a for-in loop enumerates properties in the prototype chain as well\"</a>.</p>\n\n<p>Close to the OP's solution:</p>\n\n<pre><code> Args.forEach(function (arg) {\n // This guard is not necessary,\n // since writing an empty string to document would not change it.\n if (!getAnchorTag(arg))\n return;\n\n document.write(getAnchorTag(arg));\n });\n\n function getAnchorTag (name) {\n var res = '';\n\n Object.keys(Navigation.Headings).some(function (Heading) {\n return Object.keys(Navigation.Headings[Heading]).some(function (Item) {\n if (name == Navigation.Headings[Heading][Item].Name) {\n res = (\"<a href=\\\"\"\n + Navigation.Headings[Heading][Item].URL + \"\\\">\"\n + Navigation.Headings[Heading][Item].Name + \"</a> : \");\n return true;\n }\n });\n });\n\n return res;\n }\n</code></pre>\n\n<p>Solution that reduces iterating over the Headings/Items:</p>\n\n<pre><code> var remainingArgs = Args.slice(0);\n\n Object.keys(Navigation.Headings).some(function (Heading) {\n return Object.keys(Navigation.Headings[Heading]).some(function (Item) {\n var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);\n\n if (i === -1)\n return;\n\n document.write(\"<a href=\\\"\"\n + Navigation.Headings[Heading][Item].URL + \"\\\">\"\n + Navigation.Headings[Heading][Item].Name + \"</a> : \");\n remainingArgs.splice(i, 1);\n\n if (remainingArgs.length === 0)\n return true;\n }\n });\n });\n</code></pre>\n"
},
{
"answer_id": 37998712,
"author": "Deepak Karma",
"author_id": 3483893,
"author_profile": "https://Stackoverflow.com/users/3483893",
"pm_score": -1,
"selected": false,
"text": "<p>the best way is -<br>\n1) Sort the both array which are used in first and second loop. <br>\n2) if item matched then break the inner loop and hold the index value.<br>\n3) when start next iteration start inner loop with hold index value.</p>\n"
},
{
"answer_id": 46424593,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 2,
"selected": false,
"text": "<p>How about pushing loops to their end limits</p>\n\n<pre><code> for(var a=0; a<data_a.length; a++){\n for(var b=0; b<data_b.length; b++){\n for(var c=0; c<data_c.length; c++){\n for(var d=0; d<data_d.length; d++){\n a = data_a.length;\n b = data_b.length;\n c = data_b.length;\n d = data_d.length;\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 53775094,
"author": "Matt Borja",
"author_id": 901156,
"author_profile": "https://Stackoverflow.com/users/901156",
"pm_score": 2,
"selected": false,
"text": "<p>Already mentioned previously by <strong>swilliams</strong>, but with an example below (Javascript):</p>\n\n<pre><code>// Function wrapping inner for loop\nfunction CriteriaMatch(record, criteria) {\n for (var k in criteria) {\n if (!(k in record))\n return false;\n\n if (record[k] != criteria[k])\n return false;\n }\n\n return true;\n}\n\n// Outer for loop implementing continue if inner for loop returns false\nvar result = [];\n\nfor (var i = 0; i < _table.length; i++) {\n var r = _table[i];\n\n if (!CriteriaMatch(r[i], criteria))\n continue;\n\n result.add(r);\n}\n</code></pre>\n"
},
{
"answer_id": 53981923,
"author": "Dan Bray",
"author_id": 2452680,
"author_profile": "https://Stackoverflow.com/users/2452680",
"pm_score": 6,
"selected": false,
"text": "<p>Here are five ways to break out of nested loops in JavaScript:</p>\n\n<p><strong>1) Set parent(s) loop to the end</strong></p>\n\n<pre><code>for (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n {\n i = 5;\n break;\n }\n }\n}\n</code></pre>\n\n<p><strong>2) Use label</strong></p>\n\n<pre><code>exit_loops:\nfor (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n break exit_loops;\n }\n}\n</code></pre>\n\n<p><strong>3) Use variable</strong></p>\n\n<pre><code>var exit_loops = false;\nfor (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n {\n exit_loops = true;\n break;\n }\n }\n if (exit_loops)\n break;\n}\n</code></pre>\n\n<p><strong>4) Use self executing function</strong></p>\n\n<pre><code>(function()\n{\n for (i = 0; i < 5; i++)\n {\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n return;\n }\n }\n})();\n</code></pre>\n\n<p><strong>5) Use regular function</strong></p>\n\n<pre><code>function nested_loops()\n{\n for (i = 0; i < 5; i++)\n {\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n return;\n }\n }\n}\nnested_loops();\n</code></pre>\n"
},
{
"answer_id": 56672159,
"author": "Azutanguy",
"author_id": 11504900,
"author_profile": "https://Stackoverflow.com/users/11504900",
"pm_score": 1,
"selected": false,
"text": "<p>Hmmm hi to the 10 years old party ?</p>\n\n<p>Why not put some condition in your for ?</p>\n\n<pre><code>var condition = true\nfor (var i = 0 ; i < Args.length && condition ; i++) {\n for (var j = 0 ; j < Args[i].length && condition ; j++) {\n if (Args[i].obj[j] == \"[condition]\") {\n condition = false\n }\n }\n}\n</code></pre>\n\n<p>Like this you stop when you want</p>\n\n<p>In my case, using Typescript, we can use some() which go through the array and stop when condition is met\nSo my code become like this :</p>\n\n<pre><code>Args.some((listObj) => {\n return listObj.some((obj) => {\n return !(obj == \"[condition]\")\n })\n})\n</code></pre>\n\n<p>Like this, the loop stopped right after the condition is met</p>\n\n<p><strong>Reminder : This code run in TypeScript</strong></p>\n"
},
{
"answer_id": 65605754,
"author": "Tom Chen",
"author_id": 7176037,
"author_profile": "https://Stackoverflow.com/users/7176037",
"pm_score": 2,
"selected": false,
"text": "<p>There are many excellent solutions above.\nIMO, if your break conditions are exceptions,\nyou can use try-catch:</p>\n<pre><code>try{ \n for (var i in set1) {\n for (var j in set2) {\n for (var k in set3) {\n throw error;\n }\n }\n }\n}catch (error) {\n\n}\n</code></pre>\n"
},
{
"answer_id": 69300047,
"author": "Pratik Khadtale",
"author_id": 6565662,
"author_profile": "https://Stackoverflow.com/users/6565662",
"pm_score": 1,
"selected": false,
"text": "<p>Assign the values which are in comparison condition</p>\n<pre><code>function test(){\n for(var i=0;i<10;i++)\n {\n for(var j=0;j<10;j++)\n {\n if(somecondition)\n {\n //code to Break out of both loops here\n i=10;\n j=10;\n }\n \n }\n }\n\n //Continue from here\n</code></pre>\n<p>}</p>\n"
},
{
"answer_id": 72521388,
"author": "Timo",
"author_id": 1705829,
"author_profile": "https://Stackoverflow.com/users/1705829",
"pm_score": 0,
"selected": false,
"text": "<h3>An example with <code>for .. of</code>, close to the <a href=\"https://stackoverflow.com/a/19734110/1705829\">example further up</a> which checks for the <code>abort</code> condition:</h3>\n<pre><code>test()\nfunction test() {\n var arr = [1, 2, 3,]\n var abort = false;\n for (var elem of arr) {\n console.log(1, elem)\n\n for (var elem2 of arr) {\n if (elem2 == 2) abort = true; \n if (!abort) {\n console.log(2, elem2)\n }\n }\n }\n}\n</code></pre>\n<ul>\n<li>Condition 1 - outer loop - will always run</li>\n<li>The top voted and accepted answer also works for this kind of for loop.</li>\n</ul>\n<h4>Result: the inner loop will run once as expected</h4>\n<pre><code>1 1\n2 1\n1 2\n1 3\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
What's the best way to break from nested loops in Javascript?
```
//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
```
|
Just like Perl,
```
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
```
as defined in EMCA-262 section 12.12. [[MDN Docs]](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/label)
Unlike C, these labels can only be used for [`continue`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/continue) and [`break`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/break), as Javascript does not have `goto`.
|
183,179 |
<p>I have a table that is created in a DataList in ASP.Net. This table has three fields of text, then a field with an edit button, and a field with a delete button. When a person clicks the delete button, it posts back, deletes the items, and then binds the DataList again. The DataList is in an UpdatePanel so the item smoothly disappears after a half of a second or maybe a little more, but what I'd really like is for the row to slide out (up) as soon as they hit the delete button, and then have it delete the item on the post back.</p>
<p>I can make the row slide out with jQuery, but the postback gets in the way. How do you deal with that? </p>
|
[
{
"answer_id": 183228,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 0,
"selected": false,
"text": "<p>have you tried looking at any of the Ajax control toolkit items? I believe there are some controls in there that will head with client side (java) code if your not extremely familiar</p>\n"
},
{
"answer_id": 183243,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 0,
"selected": false,
"text": "<p>I would use client side Javascript to manually scale the \"opacity\" CSS property down to zero, then mark the element as \"display: none\" then submit the post-back. </p>\n\n<p>I believe that in Internet Explorer, you need to use the \"Filter\" CSS property to do this as it does not support opacity.</p>\n\n<p>You could just code up a routine to set both properties and that should cover all the major browsers.</p>\n"
},
{
"answer_id": 183257,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 0,
"selected": false,
"text": "<p>Register the handler for form \"submit\" event. </p>\n\n<pre><code>$(\"form\").submit(function() {\n\n // if user initiated delete action \n // do your thing with deleted row (effects, etc.)\n\n // after you're done with it, submit the form from script\n // (you can queue the submission after the effect)\n // the submission from the script won't trigger this event handler\n\n return false; // prevent submission\n}\n</code></pre>\n\n<p>Preventing form submission is necessary to avoid interference with the effects you want to perform. After they are finished, you are free to proceed with submission.</p>\n"
},
{
"answer_id": 194181,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx\" rel=\"nofollow noreferrer\">page methods</a> in asp.net to send a request to the server without doing a postback. They are very simple to use and you can do whatever effect you like when the ajax call is completed (you get a function called on success).</p>\n\n<p>If you want to stick with the post back one solution is the following:</p>\n\n<pre><code><asp:Button id=\"myButton\" OnClientClick=\"return fadeThenAllowSubmit()\" ... />\n</code></pre>\n\n<p>and in js something like:</p>\n\n<pre><code>var allowSubmit = false;\nfunction fadeThenAllowSubmit() {\n if (allowSubmit) return true\n // do the jquery stuff that will be completed in, let's say, 1000ms\n setTimeout(function() {\n allowSubmit = true\n $(\"input[id$=myButton]\").click()\n allowSubmit = false\n }, 1000)\n return false\n}\n</code></pre>\n\n<p>It's a bit of a hack, the idea is to cancel the postback initially, do some stuff then set a timer where the postback will be enabled. The big problem with this approach is that the fade effect and the actual delete are independent (in case of an error you still get the fade effect).</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
] |
I have a table that is created in a DataList in ASP.Net. This table has three fields of text, then a field with an edit button, and a field with a delete button. When a person clicks the delete button, it posts back, deletes the items, and then binds the DataList again. The DataList is in an UpdatePanel so the item smoothly disappears after a half of a second or maybe a little more, but what I'd really like is for the row to slide out (up) as soon as they hit the delete button, and then have it delete the item on the post back.
I can make the row slide out with jQuery, but the postback gets in the way. How do you deal with that?
|
You can use [page methods](http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx) in asp.net to send a request to the server without doing a postback. They are very simple to use and you can do whatever effect you like when the ajax call is completed (you get a function called on success).
If you want to stick with the post back one solution is the following:
```
<asp:Button id="myButton" OnClientClick="return fadeThenAllowSubmit()" ... />
```
and in js something like:
```
var allowSubmit = false;
function fadeThenAllowSubmit() {
if (allowSubmit) return true
// do the jquery stuff that will be completed in, let's say, 1000ms
setTimeout(function() {
allowSubmit = true
$("input[id$=myButton]").click()
allowSubmit = false
}, 1000)
return false
}
```
It's a bit of a hack, the idea is to cancel the postback initially, do some stuff then set a timer where the postback will be enabled. The big problem with this approach is that the fade effect and the actual delete are independent (in case of an error you still get the fade effect).
|
183,185 |
<p>Is it possible to make hibernate do "the right thing" for some value of "right" in this situation?</p>
<pre><code>from ClassA a, ClassB b
where a.prop = b.prop
</code></pre>
<p>The thing is that prop is a UserType with different representation in the joined tables. In table A it is represented as an integer and in table B it is represented as a char. So the eq test translates to see if 1 == 'a' more or less, which is false but the object represented by 1 or 'a' should is the same so they should compare true.</p>
|
[
{
"answer_id": 183436,
"author": "Vineet Bhatia",
"author_id": 18716,
"author_profile": "https://Stackoverflow.com/users/18716",
"pm_score": -1,
"selected": false,
"text": "<p>(1) Change data-type of columns which map to \"prop\" to be the same. This will require \"Making DBA your friend\" but will result in consitent \"prop\" UserType usage.</p>\n\n<p>(2) Handle the type differences in equals() method</p>\n\n<pre><code>public boolean equals(Object x, Object y) throws HibernateException {\n boolean retValue = false;\n if (x == y) retValue = true;\n\n if (x!=null && y!=null){\n Character xChar = new Character(x);\n Character yChar = new Character(y);\n if (xChar.equals(ychar)){\n retValue = true;\n }\n }\n\n return retValue;\n}\n</code></pre>\n"
},
{
"answer_id": 188360,
"author": "Adam Hawkes",
"author_id": 6703,
"author_profile": "https://Stackoverflow.com/users/6703",
"pm_score": 0,
"selected": false,
"text": "<p>Do the join using a SQL expression. That way you can do the type conversion explicitly in the query itself.</p>\n"
},
{
"answer_id": 231225,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can do this using a <code><formula></code> tag on the relationship in your mapping file.</p>\n\n<p>For example:</p>\n\n<pre><code><many-to-one name=\"myClassB\" class=\"ClassB\">\n <formula>--Some SQL Expression that converts between ClassA.prop and ClassB.prop</formula>\n</many-to-one>\n</code></pre>\n\n<p>I've used this to associate two tables where one used an integer, but associated it to a char field in another table. This might not be exactly what you're looking for, but maybe it will put you on the right track.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24243/"
] |
Is it possible to make hibernate do "the right thing" for some value of "right" in this situation?
```
from ClassA a, ClassB b
where a.prop = b.prop
```
The thing is that prop is a UserType with different representation in the joined tables. In table A it is represented as an integer and in table B it is represented as a char. So the eq test translates to see if 1 == 'a' more or less, which is false but the object represented by 1 or 'a' should is the same so they should compare true.
|
I think you can do this using a `<formula>` tag on the relationship in your mapping file.
For example:
```
<many-to-one name="myClassB" class="ClassB">
<formula>--Some SQL Expression that converts between ClassA.prop and ClassB.prop</formula>
</many-to-one>
```
I've used this to associate two tables where one used an integer, but associated it to a char field in another table. This might not be exactly what you're looking for, but maybe it will put you on the right track.
|
183,190 |
<p>I have one question maybe someone here can help me. If i do "ps aux --sort user" on linux console I have one list of users and their processes runing on the machine. My question is how do I remove the users name and print that list like this <strong>in a C program</strong>:</p>
<p>for example:</p>
<pre><code>(…)
--------------------------------------------------------------------------
user: APACHE
--------------------------------------------------------------------------
3169 0.0 1.2 39752 12352 ? S 04:10 0:00 /usr/sbin/httpd
--------------------------------------------------------------------------
user: VASCO
--------------------------------------------------------------------------
23030 0.0 0.1 4648 1536 pts/1 Ss 20:02 0:00 –bash
(…)
</code></pre>
<p>I print the user name then I print his processes... any ideas ?</p>
<p>thx</p>
|
[
{
"answer_id": 183200,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ps aux --sort user | perl -npe 's/^(\\w+)//g; if ($user ne $1) {$user=$1; print \"user: \" . uc($user) . \"\\n\";}'\n</code></pre>\n"
},
{
"answer_id": 183500,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 0,
"selected": false,
"text": "<p>Not really an answer to your question, but user names are case-sensitive in unix, so capitalising them all probably isn't a good idea. If you want to make them stand out visually then \"USER: apache\" would be better.</p>\n\n<p>Apart from that bmdhacks' answer is good (but not quite right). You could do something similar in awk, but it would be rather more complicated.</p>\n"
},
{
"answer_id": 183538,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 0,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>ps haux --sort user | perl -npe 's/^(\\S+)\\s+//; if ($user ne $1) {$user=$1; print \"user: \" . uc($user) . \"\\n\";}'\n</code></pre>\n\n<p>Based on bmdhacks's answer, but with the following fixes:</p>\n\n<p>a) it counts any non-whitespace as part of the user name, \nb) it deletes any whitespace after the user name, like your example output had, otherwise things wouldn't line up\nc) I had to remove the g to get it to work. I think because with the g it can potentially match lots of times, so perl doesn't set $1 as it could be ambiguous.\nd) Added h to the ps command so that it doesn't output a header.</p>\n"
},
{
"answer_id": 186696,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>that's command line for linux to make what i said... but that's not what i want... i want to make that in some C program... I hav to wrote C program that makes that... so i use fork() to create one process that executes ps aux --sort user... and then i want with another process to control the print of the processes and users... sry, if i explain my problem rong. </p>\n\n<p>The command that i want to run is like this: ps aux --sort user | sort_by_user... this option sort_by_user doesn.t exists.. Make some process in C to run that command is simple with the commands fork() and execlp(), but create some option to that command in C i don´t hav any ideas. </p>\n"
},
{
"answer_id": 187553,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 1,
"selected": false,
"text": "<p>You have a number of options depending on how much of it you want to do in C.</p>\n\n<p>The simplest is to use system() to run a shell command (such as the one I posted earlier) to do the whole lot. system() will actually spawn a shell, so things like redirection will all work just as they do from the command line.</p>\n\n<p>If you want to avoid using system() you could do it yourself, spawning two processes and linking them together. Look up pipe() and dup2(). Probably a waste of time.</p>\n\n<p>You can run the ps program and parse its output in C. Again pipe() and dup2() are relevant. For the actual parsing, I'd just do it using the normal C string handling routines, as it's really quite straightforward. Obviously you could use a regex library instead but I think in this case it would result in more complicated code than without it.</p>\n\n<p>Of course, you could do the whole lot in C by looking at files in /proc.</p>\n"
},
{
"answer_id": 187574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use popen and manipulate the redirected stdout string in your C program</p>\n"
},
{
"answer_id": 190784,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I solved my problem by redirecting the stdout put and editing it.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have one question maybe someone here can help me. If i do "ps aux --sort user" on linux console I have one list of users and their processes runing on the machine. My question is how do I remove the users name and print that list like this **in a C program**:
for example:
```
(…)
--------------------------------------------------------------------------
user: APACHE
--------------------------------------------------------------------------
3169 0.0 1.2 39752 12352 ? S 04:10 0:00 /usr/sbin/httpd
--------------------------------------------------------------------------
user: VASCO
--------------------------------------------------------------------------
23030 0.0 0.1 4648 1536 pts/1 Ss 20:02 0:00 –bash
(…)
```
I print the user name then I print his processes... any ideas ?
thx
|
```
ps aux --sort user | perl -npe 's/^(\w+)//g; if ($user ne $1) {$user=$1; print "user: " . uc($user) . "\n";}'
```
|
183,201 |
<p>Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:</p>
<pre><code>int SimpleMultiplyBy2(int x)
{
return x * 2;
}
</code></pre>
<p>and</p>
<pre><code>int FastMultiplyBy2(int x)
{
return x << 1;
}
</code></pre>
<p>The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).</p>
<p>As a developer, which would be better as an initial attempt?</p>
|
[
{
"answer_id": 183215,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 6,
"selected": false,
"text": "<p>IMO the obvious readable version first, until performance is measured and a faster version is required.</p>\n"
},
{
"answer_id": 183217,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 3,
"selected": false,
"text": "<p>Readability. The time to optimize is when you get to beta testing. Otherwise you never really know what you need to spend the time on.</p>\n"
},
{
"answer_id": 183220,
"author": "Vijesh VP",
"author_id": 22016,
"author_profile": "https://Stackoverflow.com/users/22016",
"pm_score": 3,
"selected": false,
"text": "<p>I would go for <strong>readability</strong> first. Considering the fact that with the kind of optimized languages and hugely loaded machines we have in these days, most of the code we write in readable way will perform decently. </p>\n\n<p>In some very rare scenarios, where you are pretty sure you are going to have some performance bottle neck (may be from some past bad experiences), and you managed to find some weird trick which can give you huge performance advantage, you can go for that. But you should comment that code snippet very well, which will help to make it more readable.</p>\n"
},
{
"answer_id": 183221,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>Readability 100%</p>\n\n<p>If your compiler can't do the \"x*2\" => \"x <<1\" optimization for you -- get a new compiler!</p>\n\n<p>Also remember that 99.9% of your program's time is spent waiting for user input, waiting for database queries and waiting for network responses. Unless you are doing the multiple 20 bajillion times, it's not going to be noticeable.</p>\n"
},
{
"answer_id": 183230,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<p>In your given example, 99.9999% of the compilers out there will generate the same code for both cases. Which illustrates my general rule - write for readability and maintainability first, and optimize only when you need to.</p>\n"
},
{
"answer_id": 183237,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 6,
"selected": false,
"text": "<p>Take it from <a href=\"http://en.wikiquote.org/wiki/Donald_Knuth\" rel=\"noreferrer\">Don Knuth</a></p>\n\n<blockquote>\n <p>Premature optimization is the root of all evil (or at least most of it) in programming.</p>\n</blockquote>\n"
},
{
"answer_id": 183240,
"author": "mspmsp",
"author_id": 21724,
"author_profile": "https://Stackoverflow.com/users/21724",
"pm_score": 2,
"selected": false,
"text": "<p>The larger the codebase, the more readability is crucial. Trying to understand some tiny function isn't so bad. (Especially since the Method Name in the example gives you a clue.) Not so great for some epic piece of uber code written by the loner genius who just quit coding because he has finally seen the top of his ability's complexity and it's what he just wrote for you and you'll never ever understand it.</p>\n"
},
{
"answer_id": 183244,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 2,
"selected": false,
"text": "<p>A often overlooked factor in this debate is the extra time it takes for a programmer to navigate, understand and modify less readible code. Considering a programmer's time goes for a hundred dollars an hour or more, this is a very real cost.<br>\nAny performance gain is countered by this direct extra cost in development.</p>\n"
},
{
"answer_id": 183248,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 3,
"selected": false,
"text": "<p>Readability for sure. Don't worry about the speed unless someone complains</p>\n"
},
{
"answer_id": 183295,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 2,
"selected": false,
"text": "<p>Putting a comment there with an explanation would make it readable and fast.</p>\n\n<p>It really depends on the type of project, and how important performance is. If you're building a 3D game, then there are usually a lot of common optimizations that you'll want to throw in there along the way, and there's no reason not to (just don't get too carried away early). But if you're doing something tricky, comment it so anybody looking at it will know how and why you're being tricky.</p>\n"
},
{
"answer_id": 183307,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 0,
"selected": false,
"text": "<p>Write for readability first, but expect the readers to be <em>programmers</em>. Any programmer worth his or her salt should know the difference between a multiply and a bitshift, or be able to read the ternary operator where it is used appropriately, be able to look up and understand a complex algorithm (you are commenting your code right?), etc.</p>\n\n<p>Early over-optimization is, of course, quite bad at getting you into trouble later on when you need to refactor, but that doesn't really apply to the optimization of individual methods, code blocks, or statements.</p>\n"
},
{
"answer_id": 183340,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 2,
"selected": false,
"text": "<p>The answer depends on the context. In device driver programming or game development for example, the second form is an acceptable idiom. In business applications, not so much.</p>\n\n<p>Your best bet is to look around the code (or in similar <em>successful</em> applications) to check how other developers do it.</p>\n"
},
{
"answer_id": 183363,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 1,
"selected": false,
"text": "<p>The bitshift versus the multiplication is a <strong>trivial optimization that gains</strong> next to <strong>nothing</strong>. And, as has been pointed out, your compiler should do that for you. Other than that, the gain is neglectable anyhow as is the CPU this instruction runs on.</p>\n\n<p>On the other hand, if you need to perform serious computation, you will require the right data structures. But if your problem is complex, finding out about that is part of the solution. <strong>As an illustration, consider searching for an ID number in an array of 1000000 unsorted objects. Then reconsider using a binary tree or a hash map.</strong></p>\n\n<p>But optimizations like n << C are usually neglectible and trivial to change to at any point. Making code readable is not.</p>\n"
},
{
"answer_id": 183376,
"author": "akalenuk",
"author_id": 25459,
"author_profile": "https://Stackoverflow.com/users/25459",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the task needed to be solved. Usually readability is more importrant, but there are still some tasks when you shoul think of performance in the first place. And you can't just spend a day or to for profiling and optimization after everything works perfectly, because optimization itself may require rewriting sufficiant part of a code from scratch. But it is not common nowadays.</p>\n"
},
{
"answer_id": 183378,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "<p>Both. Your code should balance both; readability and performance. Because ignoring either one will screw the ROI of the project, which in the end of the day is all that matters to your boss.</p>\n\n<p>Bad readability results in decreased maintainability, which results in more resources spent on maintenance, which results in a lower ROI.</p>\n\n<p>Bad performance results in decreased investment and client base, which results in a lower ROI.</p>\n"
},
{
"answer_id": 183396,
"author": "Michael McCarty",
"author_id": 25007,
"author_profile": "https://Stackoverflow.com/users/25007",
"pm_score": 2,
"selected": false,
"text": "<p>If you're worried about readability of your code, don't hesitate to add a comment to remind yourself what and why you're doing this.</p>\n"
},
{
"answer_id": 183412,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 2,
"selected": false,
"text": "<p>using << would by a micro optimization.\nSo Hoare's (not Knuts) rule: </p>\n\n<p><a href=\"http://en.wikiquote.org/wiki/C._A._R._Hoare\" rel=\"nofollow noreferrer\">Premature optimization</a> is the root of all evil.</p>\n\n<p>applies and you should just use the more readable version in the first place. </p>\n\n<p>This is rule is IMHO often misused as an excuse to design software that can never scale, or perform well. </p>\n"
},
{
"answer_id": 183421,
"author": "Dan Soap",
"author_id": 25253,
"author_profile": "https://Stackoverflow.com/users/25253",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say go for readability.</p>\n\n<p>But in the given example, I think that the second version is already readable enough, since the name of the function exactly states, what is going on in the function.</p>\n\n<p>If we just always had functions that told us, what they do ...</p>\n"
},
{
"answer_id": 183448,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>How much does an hour of processor time cost?</p>\n\n<p>How much does an hour of programmer time cost?</p>\n"
},
{
"answer_id": 183603,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO both things have nothing to do. You should first go for code that works, as this is more important than performance or how well it reads. Regarding readability: your code should always be readable in any case.</p>\n\n<p>However I fail to see why code can't be readable and offer good performance at the same time. In your example, the second version is as readable as the first one to me. What is less readable about it? If a programmer doesn't know that shifting left is the same as multiplying by a power of two and shifting right is the same as dividing by a power of two... well, then you have much more basic problems than general readability.</p>\n"
},
{
"answer_id": 183688,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 1,
"selected": false,
"text": "<p><b>You should always maximally optimize, performance always counts.</b> The reason we have bloatware today, is that most programmers don't want to do the work of optimization.</p>\n\n<p>Having said that, you can always put comments in where slick coding needs clarification.</p>\n"
},
{
"answer_id": 183837,
"author": "nwahmaet",
"author_id": 18177,
"author_profile": "https://Stackoverflow.com/users/18177",
"pm_score": 3,
"selected": false,
"text": "<p>Readability.</p>\n\n<p>Coding for performance has it's own set of challenges. Joseph M. Newcomer said it <a href=\"http://www.codeproject.com/KB/tips/optimizationenemy.aspx\" rel=\"noreferrer\">well</a></p>\n\n<blockquote>\n <p>Optimization matters only when it\n matters. When it matters, it matters a\n lot, but until you know that it\n matters, don't waste a lot of time\n doing it. Even if you know it matters,\n you need to know where it matters.\n Without performance data, you won't\n know what to optimize, and you'll\n probably optimize the wrong thing.</p>\n \n <p>The result will be obscure, hard to\n write, hard to debug, and hard to\n maintain code that doesn't solve your\n problem. Thus it has the dual\n disadvantage of (a) increasing\n software development and software\n maintenance costs, and (b) having no\n performance effect at all.</p>\n</blockquote>\n"
},
{
"answer_id": 184241,
"author": "simon",
"author_id": 14143,
"author_profile": "https://Stackoverflow.com/users/14143",
"pm_score": 8,
"selected": true,
"text": "<p>You missed one.</p>\n\n<p>First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that.</p>\n\n<p>Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.</p>\n"
},
{
"answer_id": 184556,
"author": "DarthNoodles",
"author_id": 24854,
"author_profile": "https://Stackoverflow.com/users/24854",
"pm_score": 0,
"selected": false,
"text": "<p>Priority has to be readability. Then comes performance if it's well commented so that maintainers know why something is not standard.</p>\n"
},
{
"answer_id": 185096,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "<p>There is no point in optimizing if you don't know your bottlenecks. You may have made a function incredible efficient (usually at the expense of readability to some degree) only to find that portion of code hardly ever runs, or it's spending more time hitting the disk or database than you'll ever save twiddling bits.\nSo you can't micro-optimize until you have something to measure, and then you might as well start off for readability.\nHowever, you should be mindful of both speed and understandability when designing the overall architecture, as both can have a massive impact and be difficult to change (depending on coding style and methedologies).</p>\n"
},
{
"answer_id": 185200,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The vast majority of the time, I would agree with most of the world that readability is <strong>much</strong> more important. Computers are faster than you can imagine and only getting faster, compilers do the micro-optimzations for you, and you can optimize the bottlenecks later, once you find out where they are.</p>\n\n<p>On the other hand, though, sometimes, for example if you're writing a small program that will do some serious number crunching or other non-interactive, computationally intensive task, you might have to make some high-level design decisions with performance goals in mind. If you were to try to optimize the slow parts later in these cases, you'd basically end up rewriting large portions of the code. For example, you could try to encapsulate things well in small classes, etc, but if performance is a very high priority, you might have to settle for a less well-factored design that doesn't, for example, perform as many memory allocations.</p>\n"
},
{
"answer_id": 185346,
"author": "Craig Buchek",
"author_id": 26311,
"author_profile": "https://Stackoverflow.com/users/26311",
"pm_score": 0,
"selected": false,
"text": "<p>Readability. It will allow others (or yourself at a later date) to determine what you're trying to accomplish. If you later find that you do need to worry about performance, the readability will help you achieve performance.</p>\n\n<p>I also think that by concentrating on readability, you'll actually end up with simpler code, which will most likely achieve better performance than more complex code.</p>\n"
},
{
"answer_id": 185394,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>\"Performance always counts\" is not true. If you're I/O bound, then multiplication speed doesn't matter.</p>\n\n<p>Someone said \"The reason we have bloatware today, is that most programmers don't want to do the work of optimization,\" and that's certainly true. We have compilers to take care of those things.</p>\n\n<p>Any compiler these days is going to convert <code>x*2</code> into <code>x<<1</code>, if it's appropriate for that architecture. Here's a case where the compiler is SMARTER THAN THE PROGRAMMER.</p>\n"
},
{
"answer_id": 185845,
"author": "Peter Tomlins",
"author_id": 20874,
"author_profile": "https://Stackoverflow.com/users/20874",
"pm_score": 1,
"selected": false,
"text": "<p>It is estimated that about 70% of the cost of software is in maintenance. Readability makes a system easier to maintain and therefore brings down cost of the software over its life.</p>\n\n<p>There are cases where performance is more important the readability, that said they are few and far between.</p>\n\n<p>Before sacrifing readability, think \"Am I (or your company) prepared to deal with the extra cost I am adding to the system by doing this?\"</p>\n"
},
{
"answer_id": 197012,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": 1,
"selected": false,
"text": "<p>I don't work at google so I'd go for the evil option. (optimization)<p>\nIn Chapter 6 of Jon Bentley's \"Programming Pearls\", he describes how one system had a 400 times speed up by optimizing at 6 different design levels. I believe, that by not caring about performance at these 6 design levels, modern implementors can easily achieve 2-3 orders of magnitude of slow down in their programs. </p>\n"
},
{
"answer_id": 197044,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 1,
"selected": false,
"text": "<p>As almost everyone said in their answers, I favor <strong>readability</strong>. 99 out of 100 projects I run have no hard response time requirements, so it's an easy choice.</p>\n\n<p>Before you even start coding you should already know the answer. Some projects have certain performance requirements, like 'need to be able to run task X in Y (milli)seconds'. If that's the case, you have a goal to work towards and you know when you have to optimize or not. (hopefully) this is determined at the requirements stage of your project, not when writing the code.</p>\n\n<p>Good readability and the ability to optimize later on are a result of proper software design. If your software is of sound design, you should be able to isolate parts of your software and rewrite them if needed, without breaking other parts of the system. Besides, most true optimization cases I've encountered (ignoring some real low level tricks, those are incidental) have been in changing from one algorithm to another, or caching data to memory instead of disk/network.</p>\n"
},
{
"answer_id": 235061,
"author": "SystemSmith",
"author_id": 30987,
"author_profile": "https://Stackoverflow.com/users/30987",
"pm_score": 2,
"selected": false,
"text": "<p>Readability is the FIRST target. </p>\n\n<p>In the 1970's the army tested some of the then \"new\" techniques of software development (top down design, structured programming, chief programmer teams, to name a few) to determine which of these made a statistically significant difference.</p>\n\n<p>THe ONLY technique that made a statistically significant difference in development was...</p>\n\n<p>ADDING BLANK LINES to program code. </p>\n\n<p>The improvement in readability in those pre-structured, pre-object oriented code was the only technique in these studies that improved productivity.</p>\n\n<p>==============</p>\n\n<p>Optimization should only be addressed when the entire project is unit tested and ready for instrumentation. You never know WHERE you need to optimize the code. </p>\n\n<p>In their landmark books Kernigan and Plauger in the late 1970's SOFTWARE TOOLS (1976) and SOFTWARE TOOLS IN PASCAL (1981) showed ways to create structured programs using top down design. They created text processing programs: editors, search tools, code pre-processors. </p>\n\n<p>When the completed text formating function was INSTRUMENTED they discovered that most of the processing time was spent in three routines that performed text input and output ( In the original book, the i-o functions took 89% of the time. In the pascal book, these functions consumed 55%!)</p>\n\n<p>They were able to optimize these THREE routines and produced the results of increased performance with reasonable, manageable development time and cost.</p>\n"
},
{
"answer_id": 263776,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "<p>Readability first. But even more than readability is simplicity, <em>especially</em> in terms of data structure.</p>\n\n<p>I'm reminded of a student doing a vision analysis program, who couldn't understand why it was so slow. He merely followed good programming practice - each pixel was an object, and it worked by sending messages to its neighbors...</p>\n\n<p>check this out</p>\n"
},
{
"answer_id": 4721789,
"author": "Yuan",
"author_id": 577250,
"author_profile": "https://Stackoverflow.com/users/577250",
"pm_score": 2,
"selected": false,
"text": "<p>If there is no readability , it will be very hard to get performance improvement when you really need it.</p>\n\n<p>Performance should be only improved when it is a problem in your program, there are many places would be a bottle neck rather than this syntax. Say you are squishing 1ns improvement on a << but ignored that 10 mins IO time.</p>\n\n<p>Also, regarding readability, a professional programmer should be able to read/understand computer science terms. For example we can name a method enqueue rather than we have to say putThisJobInWorkQueue.</p>\n"
},
{
"answer_id": 14295610,
"author": "Triang3l",
"author_id": 962670,
"author_profile": "https://Stackoverflow.com/users/962670",
"pm_score": -1,
"selected": false,
"text": "<p>If you're going to release your software, you must care about the result, not the process.</p>\n\n<p>The users are not going to read your code, they are going to use your software, and they don't want to be frustrated by unnecessary long waiting. They will hate you if your well-indented properly-commented application runs slowly or eats a lot of memory.</p>\n\n<p>In short, think about the users, not yourself, so prefer performance over readability.</p>\n\n<p>One of the best examples of this rule is Quake video game. Its code is not well-structured and is often hardly readable, but it can render thousands of polygons at very high frame rates on 1995-1996 PCs. Quake, and a lot of other video games including Call of Duty (which is derived from Quake 3 engine), wouldn't exist if Carmack preferred readability over performance.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1674/"
] |
Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:
```
int SimpleMultiplyBy2(int x)
{
return x * 2;
}
```
and
```
int FastMultiplyBy2(int x)
{
return x << 1;
}
```
The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).
As a developer, which would be better as an initial attempt?
|
You missed one.
First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that.
Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.
|
183,209 |
<p>I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate. This delegate has the potential to throw an exception. I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code. The call stack is similar to this:</p>
<p>Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).</p>
<p>Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?</p>
|
[
{
"answer_id": 183241,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 2,
"selected": false,
"text": "<p>Catching from managed code with</p>\n\n<pre><code>try\n{\n throw gcnew InvalidOperationException();\n}\ncatch(InvalidOperationException^ e)\n{\n // Process e\n throw;\n}\n</code></pre>\n\n<p>And an</p>\n\n<pre><code>[assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];\n</code></pre>\n\n<p>on your assembly catches managed and unmanaged exceptions</p>\n"
},
{
"answer_id": 183291,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>One approach would be to use SEH, and do the cleanup in the exception filter before continuing the exception propagation. But I'm not sure that is overly legal since you would be doing a lot of work in the filter. You also wouldn't know anything about the managed exception being propagated.</p>\n\n<p>An alternative is to wrap the managed delegate with your own managed function that catches the exception and in turn throws an unmanaged exception ... which you can then catch in your unmanaged code.</p>\n\n<p>When the unmanaged code has done its cleanup use another helper managed function to re-throw the original managed exception</p>\n"
},
{
"answer_id": 6310027,
"author": "Alexandre C.",
"author_id": 373025,
"author_profile": "https://Stackoverflow.com/users/373025",
"pm_score": 1,
"selected": false,
"text": "<p>Don't even remotely try to make the \"unmanaged\" code aware of the fact that it will have to deal with .NET.</p>\n\n<p>Return a non-zero value from your callback to signal the presence of an error. Provide a (thread local) global string object describing the error so that you can retrieve a helpful error message for the user.</p>\n\n<p>This may involve wrapping your delegate into another function under the scenes, which will catch all the exceptions and return the error code.</p>\n"
},
{
"answer_id": 6310077,
"author": "Puppy",
"author_id": 298661,
"author_profile": "https://Stackoverflow.com/users/298661",
"pm_score": 0,
"selected": false,
"text": "<p>Managed code represents exceptions as hardware exceptions, unlike C++. You could use SEH. Remember that you always get the chance to run the exception filter.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms680657(v=VS.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms680657(v=VS.85).aspx</a></p>\n"
},
{
"answer_id": 32021865,
"author": "user5229464",
"author_id": 5229464,
"author_profile": "https://Stackoverflow.com/users/5229464",
"pm_score": -1,
"selected": false,
"text": "<p>I was told...{the vector can't show if variables a&b weren't declared in the scope process. After a bit of digging figured out that the loop hole was as follows--- weibull_distribution> unmanaged_code \n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24965/"
] |
I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate. This delegate has the potential to throw an exception. I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code. The call stack is similar to this:
Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).
Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?
|
Catching from managed code with
```
try
{
throw gcnew InvalidOperationException();
}
catch(InvalidOperationException^ e)
{
// Process e
throw;
}
```
And an
```
[assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];
```
on your assembly catches managed and unmanaged exceptions
|
183,214 |
<p>I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.</p>
<pre><code>function foo(id) {
this.dom = document.getElementById(id);
this.bar = 5;
var self = this;
this.dom.addEventListener("click", self.onclick, false);
}
foo.prototype = {
onclick : function() {
this.bar = 7;
}
};
</code></pre>
<p>Now when I create a new object (after the DOM has loaded, with a span#test)</p>
<pre><code>var x = new foo('test');
</code></pre>
<p>The 'this' inside the onclick function points to the span#test and not the foo object.</p>
<p>How do I get a reference to my foo object inside the onclick function?</p>
|
[
{
"answer_id": 183247,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 4,
"selected": false,
"text": "<pre><code>this.dom.addEventListener(\"click\", function(event) {\n self.onclick(event)\n}, false);\n</code></pre>\n"
},
{
"answer_id": 183303,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": -1,
"selected": false,
"text": "<p>this is one of the most confusing points of JS: the 'this' variable means to the most local object... but functions are also objects, so 'this' points there. There are other subtle points, but i don't remember them all.</p>\n\n<p>I usually avoid using 'this', just define a local 'me' variable and use that instead.</p>\n"
},
{
"answer_id": 193853,
"author": "hishadow",
"author_id": 7188,
"author_profile": "https://Stackoverflow.com/users/7188",
"pm_score": 7,
"selected": true,
"text": "<p><em>(extracted some explanation that was hidden in comments in other answer)</em></p>\n\n<p>The problem lies in the following line:</p>\n\n<pre><code>this.dom.addEventListener(\"click\", self.onclick, false);\n</code></pre>\n\n<p>Here, you pass a function object to be used as callback. When the event trigger, the function is called but now it has no association with any object (this).</p>\n\n<p>The problem can be solved by wrapping the function (with it's object reference) in a closure as follows:</p>\n\n<pre><code>this.dom.addEventListener(\n \"click\",\n function(event) {self.onclick(event)},\n false);\n</code></pre>\n\n<p>Since the variable self was assigned <em>this</em> when the closure was created, the closure function will remember the value of the self variable when it's called at a later time.</p>\n\n<p>An alternative way to solve this is to make an utility function (and avoid using variables for binding <em>this</em>):</p>\n\n<pre><code>function bind(scope, fn) {\n return function () {\n fn.apply(scope, arguments);\n };\n}\n</code></pre>\n\n<p>The updated code would then look like:</p>\n\n<pre><code>this.dom.addEventListener(\"click\", bind(this, this.onclick), false);\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"noreferrer\"><code>Function.prototype.bind</code></a> is part of ECMAScript 5 and provides the same functionality. So you can do:</p>\n\n<pre><code>this.dom.addEventListener(\"click\", this.onclick.bind(this), false);\n</code></pre>\n\n<p>For browsers which do not support ES5 yet, <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"noreferrer\">MDN provides the following shim</a>:</p>\n\n<pre><code>if (!Function.prototype.bind) { \n Function.prototype.bind = function (oThis) { \n if (typeof this !== \"function\") { \n // closest thing possible to the ECMAScript 5 internal IsCallable function \n throw new TypeError(\"Function.prototype.bind - what is trying to be bound is not callable\"); \n } \n\n var aArgs = Array.prototype.slice.call(arguments, 1), \n fToBind = this, \n fNOP = function () {}, \n fBound = function () { \n return fToBind.apply(this instanceof fNOP \n ? this \n : oThis || window, \n aArgs.concat(Array.prototype.slice.call(arguments))); \n }; \n\n fNOP.prototype = this.prototype; \n fBound.prototype = new fNOP(); \n\n return fBound; \n }; \n} \n</code></pre>\n"
},
{
"answer_id": 193913,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": false,
"text": "<p>The explanation is that <code>self.onclick</code> does not mean what you think it means in JavaScript. It actually means the <code>onclick</code> function in the prototype of the object <code>self</code> (without in any way referencing <code>self</code> itself).</p>\n\n<p>JavaScript only has functions and no delegates like C#, so it is not possible to pass a method AND the object it should be applied to as a callback.</p>\n\n<p>The only way to call a method in a callback is to call it yourself inside a callback function. Because JavaScript functions are closures, they are able to access the variables declared in the scope they were created in.</p>\n\n<pre><code>var obj = ...;\nfunction callback(){ return obj.method() };\nsomething.bind(callback);\n</code></pre>\n"
},
{
"answer_id": 758015,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote this plugin...</p>\n\n<p>i think it will be useful</p>\n\n<p><a href=\"http://code.google.com/p/jquerycallback/\" rel=\"nofollow noreferrer\">jquery.callback</a></p>\n"
},
{
"answer_id": 1809862,
"author": "tpk",
"author_id": 8437,
"author_profile": "https://Stackoverflow.com/users/8437",
"pm_score": 2,
"selected": false,
"text": "<p>A good explanation of the problem (I had problems understanding solutions described so far) is <a href=\"http://www.mail-archive.com/[email protected]/msg82906.html\" rel=\"nofollow noreferrer\">available here</a>.</p>\n"
},
{
"answer_id": 4689727,
"author": "Seldaek",
"author_id": 6512,
"author_profile": "https://Stackoverflow.com/users/6512",
"pm_score": 3,
"selected": false,
"text": "<p>For the <strong>jQuery</strong> users looking for a solution to this problem, you should use <a href=\"http://api.jquery.com/jQuery.proxy/\" rel=\"noreferrer\">jQuery.proxy</a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
] |
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.
```
function foo(id) {
this.dom = document.getElementById(id);
this.bar = 5;
var self = this;
this.dom.addEventListener("click", self.onclick, false);
}
foo.prototype = {
onclick : function() {
this.bar = 7;
}
};
```
Now when I create a new object (after the DOM has loaded, with a span#test)
```
var x = new foo('test');
```
The 'this' inside the onclick function points to the span#test and not the foo object.
How do I get a reference to my foo object inside the onclick function?
|
*(extracted some explanation that was hidden in comments in other answer)*
The problem lies in the following line:
```
this.dom.addEventListener("click", self.onclick, false);
```
Here, you pass a function object to be used as callback. When the event trigger, the function is called but now it has no association with any object (this).
The problem can be solved by wrapping the function (with it's object reference) in a closure as follows:
```
this.dom.addEventListener(
"click",
function(event) {self.onclick(event)},
false);
```
Since the variable self was assigned *this* when the closure was created, the closure function will remember the value of the self variable when it's called at a later time.
An alternative way to solve this is to make an utility function (and avoid using variables for binding *this*):
```
function bind(scope, fn) {
return function () {
fn.apply(scope, arguments);
};
}
```
The updated code would then look like:
```
this.dom.addEventListener("click", bind(this, this.onclick), false);
```
---
[`Function.prototype.bind`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind) is part of ECMAScript 5 and provides the same functionality. So you can do:
```
this.dom.addEventListener("click", this.onclick.bind(this), false);
```
For browsers which do not support ES5 yet, [MDN provides the following shim](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind):
```
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
```
|
183,249 |
<p>.Net contains a nice control called <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.documentviewer.aspx" rel="noreferrer"><code>DocumentViewer</code></a>. it also offers a subcontrol for finding text in the loaded document (that's at least what it is supposed to do).</p>
<p>When inserting <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.fixeddocument.aspx" rel="noreferrer"><code>FixedPage</code></a>'s objects as document source for the <code>DocumentViewer</code>, the find-functionality just does not find anything. Not even single letters. I haven't tried <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument.aspx" rel="noreferrer"><code>FlowDocument</code></a>'s yet,
as the documentation for <code>DocumentViewer</code> is not that useful and the resources on the net are not actually existing, I now want to ask the stackoverflow community:</p>
<p>What does it need to get the Find-Function of the WPF <code>DocumentViewer</code> working with <code>FixedPage</code> documents?</p>
<p>[btw, I don't use custom <code>ControlTemplates</code> for <code>DocumentViewer</code>]</p>
|
[
{
"answer_id": 183748,
"author": "Artur Carvalho",
"author_id": 1013,
"author_profile": "https://Stackoverflow.com/users/1013",
"pm_score": 1,
"selected": false,
"text": "<p>I had trouble with searching text in richtextbox, it was too slow. What I did was crunch the xaml every time I wanted to search. I improved several orders of magnitude.</p>\n\n<p>It's a big workaround based in a part of the Chris Anderson's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321374479\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">book</a>.</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 860709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>I had this same problem with FixedDocuments. If you convert your FixedDocument to an XPS document then it works fine.</p>\n\n<p>Example of creating an XPS Document in memory from a FixedDocument then displaying in a DocumentViewer. </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// Add to xaml: <DocumentViewer x:Name=\"documentViewer\" />\n// Add project references to \"ReachFramework\" and \"System.Printing\"\nusing System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.IO;\nusing System.IO.Packaging;\nusing System.Windows.Xps.Packaging;\n\nnamespace WpfApplication1\n{\n public partial class MainWindow : Window\n {\n public MainWindow()\n {\n InitializeComponent();\n\n // Set up demo FixedDocument containing text to be searched\n var fixedDocument = new FixedDocument();\n var pageContent = new PageContent();\n var fixedPage = new FixedPage();\n fixedPage.Children.Add(new TextBlock() { Text = \"Demo document text.\" });\n pageContent.Child = fixedPage;\n fixedDocument.Pages.Add(pageContent);\n\n // Set up fresh XpsDocument\n var stream = new MemoryStream();\n var uri = new Uri(\"pack://document.xps\");\n var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);\n PackageStore.AddPackage(uri, package);\n var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);\n\n // Write FixedDocument to the XpsDocument\n var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);\n docWriter.Write(fixedDocument);\n\n // Display XpsDocument in DocumentViewer\n documentViewer.Document = xpsDoc.GetFixedDocumentSequence();\n }\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/wrTWu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wrTWu.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
.Net contains a nice control called [`DocumentViewer`](http://msdn.microsoft.com/en-us/library/system.windows.controls.documentviewer.aspx). it also offers a subcontrol for finding text in the loaded document (that's at least what it is supposed to do).
When inserting [`FixedPage`](http://msdn.microsoft.com/en-us/library/system.windows.documents.fixeddocument.aspx)'s objects as document source for the `DocumentViewer`, the find-functionality just does not find anything. Not even single letters. I haven't tried [`FlowDocument`](http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument.aspx)'s yet,
as the documentation for `DocumentViewer` is not that useful and the resources on the net are not actually existing, I now want to ask the stackoverflow community:
What does it need to get the Find-Function of the WPF `DocumentViewer` working with `FixedPage` documents?
[btw, I don't use custom `ControlTemplates` for `DocumentViewer`]
|
I had this same problem with FixedDocuments. If you convert your FixedDocument to an XPS document then it works fine.
Example of creating an XPS Document in memory from a FixedDocument then displaying in a DocumentViewer.
```cs
// Add to xaml: <DocumentViewer x:Name="documentViewer" />
// Add project references to "ReachFramework" and "System.Printing"
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.IO;
using System.IO.Packaging;
using System.Windows.Xps.Packaging;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Set up demo FixedDocument containing text to be searched
var fixedDocument = new FixedDocument();
var pageContent = new PageContent();
var fixedPage = new FixedPage();
fixedPage.Children.Add(new TextBlock() { Text = "Demo document text." });
pageContent.Child = fixedPage;
fixedDocument.Pages.Add(pageContent);
// Set up fresh XpsDocument
var stream = new MemoryStream();
var uri = new Uri("pack://document.xps");
var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
PackageStore.AddPackage(uri, package);
var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);
// Write FixedDocument to the XpsDocument
var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
docWriter.Write(fixedDocument);
// Display XpsDocument in DocumentViewer
documentViewer.Document = xpsDoc.GetFixedDocumentSequence();
}
}
}
```
[](https://i.stack.imgur.com/wrTWu.png)
|
183,250 |
<p>I have a c# object with a property called Gender which is declared as a char.</p>
<pre><code>private char _Gender;
public char Gender
{
get{ return _Gender; }
set{ _Gender = value; }
}
</code></pre>
<p>What string is returned/created when I call MyObject.Gender.ToString()?</p>
<p>I ask because I am calling a webservice (which accepts a string rather than a char) so I am doing a ToString on the property as I pass it over. I was expecting it to send an empty string if the char is not set.</p>
<p>However this doesn't appear to be the case, so the question is what is the string?</p>
|
[
{
"answer_id": 183260,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>The default value of char is unicode 0, so I'd expect \"\\u0000\" to be returned.</p>\n"
},
{
"answer_id": 183270,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Fields are always initialized to their default value; 0/false/null - this this is the 0 character, \\0.</p>\n\n<p>If you want an empty string, use strings directly - i.e. \"\".</p>\n\n<p>You could use a conditional operator:</p>\n\n<pre><code>string s = c == 0 ? \"\" : c.ToString();\n</code></pre>\n\n<p>Alternatively, nullable types might help - i.e.</p>\n\n<pre><code>char? c; // a field\n...\nstring s = c.ToString(); // is \"\"\nc = 'a';\ns = c.ToString(); // is \"a\"\n</code></pre>\n"
},
{
"answer_id": 183283,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 0,
"selected": false,
"text": "<p>A char has a length of 1, so it never should return an empty string.</p>\n\n<p>If you want to distinguish between 0 and uninitialised, you would need to use the nullable form char?.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1970/"
] |
I have a c# object with a property called Gender which is declared as a char.
```
private char _Gender;
public char Gender
{
get{ return _Gender; }
set{ _Gender = value; }
}
```
What string is returned/created when I call MyObject.Gender.ToString()?
I ask because I am calling a webservice (which accepts a string rather than a char) so I am doing a ToString on the property as I pass it over. I was expecting it to send an empty string if the char is not set.
However this doesn't appear to be the case, so the question is what is the string?
|
The default value of char is unicode 0, so I'd expect "\u0000" to be returned.
|
183,316 |
<p>How do I go about the <code>[HandleError]</code> filter in asp.net MVC Preview 5?<br>
I set the customErrors in my Web.config file</p>
<pre><code><customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
</code></pre>
<p>and put [HandleError] above my Controller Class like this:</p>
<pre><code>[HandleError]
public class DSWebsiteController: Controller
{
[snip]
public ActionResult CrashTest()
{
throw new Exception("Oh Noes!");
}
}
</code></pre>
<p>Then I let my controllers inherit from this class and call CrashTest() on them.
Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller.
Off course the path cannot be found and I get "Server Error in '/' Application." 404.</p>
<p>This site was ported from preview 3 to 5.
Everything runs (wasn't that much work to port) except the error handling.
When I create a complete new project the error handling seems to work.</p>
<p>Ideas?</p>
<p><strong>--Note--</strong><br>
Since this question has over 3K views now, I thought it would be beneficial to put in what I'm currently (ASP.NET MVC 1.0) using.
In the <a href="http://www.codeplex.com/MVCContrib" rel="noreferrer">mvc contrib project</a> there is a brilliant attribute called "RescueAttribute"
You should probably check it out too ;)</p>
|
[
{
"answer_id": 183910,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<p>You are missing Error.aspx :) In preview 5, this is located in your Views/Shared folder. Just copy it over from a new Preview 5 project.</p>\n"
},
{
"answer_id": 192371,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 8,
"selected": true,
"text": "<pre><code>[HandleError]\n</code></pre>\n\n<p>When you provide only the HandleError attribute to your class (or to your action method for that matter), then when an unhandled exception occurs MVC will look for a corresponding View named \"Error\" first in the Controller's View folder. If it can't find it there then it will proceed to look in the Shared View folder (which should have an Error.aspx file in it by default)</p>\n\n<pre><code>[HandleError(ExceptionType = typeof(SqlException), View = \"DatabaseError\")]\n[HandleError(ExceptionType = typeof(NullReferenceException), View = \"LameErrorHandling\")]\n</code></pre>\n\n<p>You can also stack up additional attributes with specific information about the type of exception you are looking for. At that point, you can direct the Error to a specific view other than the default \"Error\" view.</p>\n\n<p>For more information, take a look at <a href=\"http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx\" rel=\"noreferrer\">Scott Guthrie's blog post</a> about it.</p>\n"
},
{
"answer_id": 1164402,
"author": "Corin Blaikie",
"author_id": 1736,
"author_profile": "https://Stackoverflow.com/users/1736",
"pm_score": 5,
"selected": false,
"text": "<p>It should also be noted that errors that don't set the http error code to 500 </p>\n\n<p>(e.g. UnauthorizedAccessException)</p>\n\n<p>will not be handled by the HandleError filter.</p>\n"
},
{
"answer_id": 2769307,
"author": "Raul",
"author_id": 332872,
"author_profile": "https://Stackoverflow.com/users/332872",
"pm_score": 4,
"selected": false,
"text": "<p>Solution for http error code to 500 \nthis is an attribute called [ERROR] put it on an action</p>\n\n<pre><code>public class Error: System.Web.Mvc.HandleErrorAttribute\n{\n public override void OnException(System.Web.Mvc.ExceptionContext filterContext)\n {\n\n if (filterContext.HttpContext.IsCustomErrorEnabled)\n {\n filterContext.ExceptionHandled = true;\n\n }\n base.OnException(filterContext);\n //OVERRIDE THE 500 ERROR \n filterContext.HttpContext.Response.StatusCode = 200;\n }\n\n private static void RaiseErrorSignal(Exception e)\n {\n var context = HttpContext.Current;\n // using.Elmah.ErrorSignal.FromContext(context).Raise(e, context);\n } \n\n}\n</code></pre>\n\n<p>//EXAMPLE:</p>\n\n<pre><code>[Error]\n[HandleError]\n[PopulateSiteMap(SiteMapName=\"Mifel1\", ViewDataKey=\"Mifel1\")]\npublic class ApplicationController : Controller\n{\n}\n</code></pre>\n"
},
{
"answer_id": 29246981,
"author": "Jack",
"author_id": 4710067,
"author_profile": "https://Stackoverflow.com/users/4710067",
"pm_score": -1,
"selected": false,
"text": "<pre><code> [HandleError]\n public class ErrorController : Controller\n { \n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult NotAuthorized()\n {\n //401\n Response.StatusCode = (int)HttpStatusCode.Unauthorized;\n\n return View();\n }\n\n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult Forbidden()\n {\n //403\n Response.StatusCode = (int)HttpStatusCode.Forbidden;\n\n return View();\n }\n\n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult NotFound()\n {\n //404\n Response.StatusCode = (int)HttpStatusCode.NotFound;\n return View();\n }\n\n public ViewResult ServerError()\n {\n //500\n Response.StatusCode = (int)HttpStatusCode.NotFound;\n return View();\n }\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 38450727,
"author": "Sandip - Frontend Developer",
"author_id": 6606630,
"author_profile": "https://Stackoverflow.com/users/6606630",
"pm_score": 4,
"selected": false,
"text": "<p>Attributes in MVC is very useful in error handling at <strong>get and post</strong> method, it also track for <strong>ajax call</strong>.</p>\n\n<p>Create a base controller in your application and inherit it in your main controller(EmployeeController).</p>\n\n<p><strong>public class EmployeeController : BaseController</strong></p>\n\n<h1>Add below code in base controller.</h1>\n\n<pre><code>/// <summary>\n/// Base Controller\n/// </summary>\npublic class BaseController : Controller\n{ \n protected override void OnException(ExceptionContext filterContext)\n {\n Exception ex = filterContext.Exception;\n\n //Save error log in file\n if (ConfigurationManager.AppSettings[\"SaveErrorLog\"].ToString().Trim().ToUpper() == \"TRUE\")\n {\n SaveErrorLog(ex, filterContext);\n }\n\n // if the request is AJAX return JSON else view.\n if (IsAjax(filterContext))\n {\n //Because its a exception raised after ajax invocation\n //Lets return Json\n filterContext.Result = new JsonResult()\n {\n Data = Convert.ToString(filterContext.Exception),\n JsonRequestBehavior = JsonRequestBehavior.AllowGet\n };\n }\n else\n {\n filterContext.ExceptionHandled = true;\n filterContext.HttpContext.Response.Clear();\n\n filterContext.Result = new ViewResult()\n {\n //Error page to load\n ViewName = \"Error\",\n ViewData = new ViewDataDictionary()\n };\n\n base.OnException(filterContext);\n }\n }\n\n /// <summary>\n /// Determines whether the specified filter context is ajax.\n /// </summary>\n /// <param name=\"filterContext\">The filter context.</param>\n private bool IsAjax(ExceptionContext filterContext)\n {\n return filterContext.HttpContext.Request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\";\n }\n\n /// <summary>\n /// Saves the error log.\n /// </summary>\n /// <param name=\"ex\">The ex.</param>\n /// <param name=\"filterContext\">The filter context.</param>\n void SaveErrorLog(Exception ex, ExceptionContext filterContext)\n {\n string logMessage = ex.ToString();\n\n string logDirectory = Server.MapPath(Url.Content(\"~/ErrorLog/\"));\n\n DateTime currentDateTime = DateTime.Now;\n string currentDateTimeString = currentDateTime.ToString();\n CheckCreateLogDirectory(logDirectory);\n string logLine = BuildLogLine(currentDateTime, logMessage, filterContext);\n logDirectory = (logDirectory + \"\\\\Log_\" + LogFileName(DateTime.Now) + \".txt\");\n\n StreamWriter streamWriter = null;\n try\n {\n streamWriter = new StreamWriter(logDirectory, true);\n streamWriter.WriteLine(logLine);\n }\n catch\n {\n }\n finally\n {\n if (streamWriter != null)\n {\n streamWriter.Close();\n }\n }\n }\n\n /// <summary>\n /// Checks the create log directory.\n /// </summary>\n /// <param name=\"logPath\">The log path.</param>\n bool CheckCreateLogDirectory(string logPath)\n {\n bool loggingDirectoryExists = false;\n DirectoryInfo directoryInfo = new DirectoryInfo(logPath);\n if (directoryInfo.Exists)\n {\n loggingDirectoryExists = true;\n }\n else\n {\n try\n {\n Directory.CreateDirectory(logPath);\n loggingDirectoryExists = true;\n }\n catch\n {\n }\n }\n\n return loggingDirectoryExists;\n }\n\n /// <summary>\n /// Builds the log line.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n /// <param name=\"logMessage\">The log message.</param>\n /// <param name=\"filterContext\">The filter context.</param> \n string BuildLogLine(DateTime currentDateTime, string logMessage, ExceptionContext filterContext)\n {\n string controllerName = filterContext.RouteData.Values[\"Controller\"].ToString();\n string actionName = filterContext.RouteData.Values[\"Action\"].ToString();\n\n RouteValueDictionary paramList = ((System.Web.Routing.Route)(filterContext.RouteData.Route)).Defaults;\n if (paramList != null)\n {\n paramList.Remove(\"Controller\");\n paramList.Remove(\"Action\");\n }\n\n StringBuilder loglineStringBuilder = new StringBuilder();\n\n loglineStringBuilder.Append(\"Log Time : \");\n loglineStringBuilder.Append(LogFileEntryDateTime(currentDateTime));\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"Username : \");\n loglineStringBuilder.Append(Session[\"LogedInUserName\"]);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"ControllerName : \");\n loglineStringBuilder.Append(controllerName);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"ActionName : \");\n loglineStringBuilder.Append(actionName);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"----------------------------------------------------------------------------------------------------------\");\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(logMessage);\n loglineStringBuilder.Append(System.Environment.NewLine);\n loglineStringBuilder.Append(\"==========================================================================================================\");\n\n return loglineStringBuilder.ToString();\n }\n\n /// <summary>\n /// Logs the file entry date time.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n string LogFileEntryDateTime(DateTime currentDateTime)\n {\n return currentDateTime.ToString(\"dd-MMM-yyyy HH:mm:ss\");\n }\n\n /// <summary>\n /// Logs the name of the file.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n string LogFileName(DateTime currentDateTime)\n {\n return currentDateTime.ToString(\"dd_MMM_yyyy\");\n }\n\n}\n</code></pre>\n\n<p>================================================</p>\n\n<p><strong>Finds the Directory : Root/App_Start/FilterConfig.cs</strong></p>\n\n<p>Add below code:</p>\n\n<pre><code>/// <summary>\n/// Filter Config\n/// </summary>\npublic class FilterConfig\n{\n /// <summary>\n /// Registers the global filters.\n /// </summary>\n /// <param name=\"filters\">The filters.</param>\n public static void RegisterGlobalFilters(GlobalFilterCollection filters)\n {\n filters.Add(new HandleErrorAttribute());\n }\n}\n</code></pre>\n\n<p><strong>Track AJAX Error:</strong></p>\n\n<p>Call CheckAJAXError function in layout page load.</p>\n\n<pre><code>function CheckAJAXError() {\n $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {\n\n var ex;\n if (String(thrownError).toUpperCase() == \"LOGIN\") {\n var url = '@Url.Action(\"Login\", \"Login\")';\n window.location = url;\n }\n else if (String(jqXHR.responseText).toUpperCase().indexOf(\"THE DELETE STATEMENT CONFLICTED WITH THE REFERENCE CONSTRAINT\") >= 0) {\n\n toastr.error('ReferanceExistMessage');\n }\n else if (String(thrownError).toUpperCase() == \"INTERNAL SERVER ERROR\") {\n ex = ajaxSettings.url;\n //var url = '@Url.Action(\"ErrorLog\", \"Home\")?exurl=' + ex;\n var url = '@Url.Action(\"ErrorLog\", \"Home\")';\n window.location = url;\n }\n });\n};\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
How do I go about the `[HandleError]` filter in asp.net MVC Preview 5?
I set the customErrors in my Web.config file
```
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
```
and put [HandleError] above my Controller Class like this:
```
[HandleError]
public class DSWebsiteController: Controller
{
[snip]
public ActionResult CrashTest()
{
throw new Exception("Oh Noes!");
}
}
```
Then I let my controllers inherit from this class and call CrashTest() on them.
Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller.
Off course the path cannot be found and I get "Server Error in '/' Application." 404.
This site was ported from preview 3 to 5.
Everything runs (wasn't that much work to port) except the error handling.
When I create a complete new project the error handling seems to work.
Ideas?
**--Note--**
Since this question has over 3K views now, I thought it would be beneficial to put in what I'm currently (ASP.NET MVC 1.0) using.
In the [mvc contrib project](http://www.codeplex.com/MVCContrib) there is a brilliant attribute called "RescueAttribute"
You should probably check it out too ;)
|
```
[HandleError]
```
When you provide only the HandleError attribute to your class (or to your action method for that matter), then when an unhandled exception occurs MVC will look for a corresponding View named "Error" first in the Controller's View folder. If it can't find it there then it will proceed to look in the Shared View folder (which should have an Error.aspx file in it by default)
```
[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]
```
You can also stack up additional attributes with specific information about the type of exception you are looking for. At that point, you can direct the Error to a specific view other than the default "Error" view.
For more information, take a look at [Scott Guthrie's blog post](http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx) about it.
|
183,325 |
<p>For some reason, Section 1 works but Section 2 does not. When run in the opposite order (2 before 1), Section 1 (Affiliation) is not run at all. All the data is the same.</p>
<pre><code>//Section 1
UserService.DsUserAttributes dsAffiliation = us_service.GetUserAttributeDropDown(systemId, "Affiliation");
Affiliation.DataSource = dsAffiliation.tblDropDownValues;
Affiliation.DataTextField = "AttrValue";
Affiliation.DataValueField = "Id";
Affiliation.DataBind();
//Section 2
UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
</code></pre>
|
[
{
"answer_id": 183337,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 0,
"selected": false,
"text": "<p>i guess this heavily depends on the \"Country\" and \"Affiliation\" objects...there could potentially happen anything. without any exceptions or something similar it's quite hard to remotely debugg this stuff ^^</p>\n"
},
{
"answer_id": 183357,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": true,
"text": "<p>It would certainly seem that either <code>us_service.GetUserAttributeDropDown(systemId, \"Country\")</code> or <code>dsCountry.tblDropDownValues</code> is throwing an exception. You'll need to walk through with the debugger to see which and why.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
For some reason, Section 1 works but Section 2 does not. When run in the opposite order (2 before 1), Section 1 (Affiliation) is not run at all. All the data is the same.
```
//Section 1
UserService.DsUserAttributes dsAffiliation = us_service.GetUserAttributeDropDown(systemId, "Affiliation");
Affiliation.DataSource = dsAffiliation.tblDropDownValues;
Affiliation.DataTextField = "AttrValue";
Affiliation.DataValueField = "Id";
Affiliation.DataBind();
//Section 2
UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
```
|
It would certainly seem that either `us_service.GetUserAttributeDropDown(systemId, "Country")` or `dsCountry.tblDropDownValues` is throwing an exception. You'll need to walk through with the debugger to see which and why.
|
183,338 |
<p>I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files).</p>
<p>Requirements:</p>
<ul>
<li>Notification on X increase in size over Y time</li>
<li>Notification on X increase in file count over Y time</li>
<li>Historical graphing (or at least saving snapshot data over time) of size and file count</li>
<li>All of this on a set of directories and their child directories</li>
</ul>
<p>I'd prefer a free solution but would also appreciate getting pointed in the right direction. If we were to write our own, how would we go about doing that? Available languages being Ruby, Groovy, Java, Perl, or PowerShell (since I'd be writing it).</p>
|
[
{
"answer_id": 183400,
"author": "Joel",
"author_id": 21987,
"author_profile": "https://Stackoverflow.com/users/21987",
"pm_score": 2,
"selected": false,
"text": "<p>There are several solutions out there, including some free ones. Some that I have worked with include:</p>\n\n<p><a href=\"http://www.nagios.org/\" rel=\"nofollow noreferrer\">Nagios</a>\nand\n<a href=\"http://bb4.com/\" rel=\"nofollow noreferrer\">Big Brother</a></p>\n\n<p>A quick google search can probably find more.</p>\n"
},
{
"answer_id": 183464,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 3,
"selected": true,
"text": "<p>You might want to take a look at <a href=\"http://www.codeplex.com/polymon\" rel=\"nofollow noreferrer\">PolyMon</a>, which is an open source systems monitoring solution. It allows you to write custom monitors in any .NET language, and allows you to create custom PowerShell monitors. </p>\n\n<p>It stores data on a SQL Server back end and provides graphing. For your purpose, you would just need a script that would get the directory size and file count.\nSomething like:</p>\n\n<pre><code>$size = 0\n$count = 0\n$path = '\\\\unc\\path\\to\\directory\\to\\monitor'\nget-childitem -path $path -recurse | Where-Object {$_ -is [System.IO.FileInfo]} | ForEach-Object {$size += $_.length; $count += 1}\n</code></pre>\n\n<p>In reply to Scott's comment:\nSure. you could wrap it in a while loop </p>\n\n<pre><code>$ESCkey = 27\nWrite-Host \"Press the ESC key to stop sniffing\" -foregroundcolor \"CYAN\"\n$Running=$true\n\nWhile ($Running)\n { \n if ($host.ui.RawUi.KeyAvailable) {\n $key = $host.ui.RawUI.ReadKey(\"NoEcho,IncludeKeyUp,IncludeKeyDown\")\n if ($key.VirtualKeyCode -eq $ESCkey) { \n $Running=$False\n }\n #rest of function here \n } \n</code></pre>\n\n<p>I would not do that for a PowerShell monitor, which you can schedule to run periodically, but for a script to run in the background, the above would work. You could even add some database access code to log the results to a database, or log it to a file.. what ever you want.</p>\n"
},
{
"answer_id": 184121,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://sourceforge.net/projects/dirviewer/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/dirviewer/</a> -- DirViewer is a light pure java application for directory tree view and recursive disk usage statistics, using JGoodies-Looks look and feel similar to windows XP.</p>\n"
},
{
"answer_id": 184232,
"author": "Jeffery Hicks",
"author_id": 25508,
"author_profile": "https://Stackoverflow.com/users/25508",
"pm_score": 1,
"selected": false,
"text": "<p>You can certainly accomplish this with PowerShell and WMI. You would need some sort of DB backend like SQL Express. But I agree that a tool like Polymon is a better approach. The one thing that might make a diffence is the issue of scale. Do you need to monitor 1 folder on 1 server or hundreds?</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861/"
] |
I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files).
Requirements:
* Notification on X increase in size over Y time
* Notification on X increase in file count over Y time
* Historical graphing (or at least saving snapshot data over time) of size and file count
* All of this on a set of directories and their child directories
I'd prefer a free solution but would also appreciate getting pointed in the right direction. If we were to write our own, how would we go about doing that? Available languages being Ruby, Groovy, Java, Perl, or PowerShell (since I'd be writing it).
|
You might want to take a look at [PolyMon](http://www.codeplex.com/polymon), which is an open source systems monitoring solution. It allows you to write custom monitors in any .NET language, and allows you to create custom PowerShell monitors.
It stores data on a SQL Server back end and provides graphing. For your purpose, you would just need a script that would get the directory size and file count.
Something like:
```
$size = 0
$count = 0
$path = '\\unc\path\to\directory\to\monitor'
get-childitem -path $path -recurse | Where-Object {$_ -is [System.IO.FileInfo]} | ForEach-Object {$size += $_.length; $count += 1}
```
In reply to Scott's comment:
Sure. you could wrap it in a while loop
```
$ESCkey = 27
Write-Host "Press the ESC key to stop sniffing" -foregroundcolor "CYAN"
$Running=$true
While ($Running)
{
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown")
if ($key.VirtualKeyCode -eq $ESCkey) {
$Running=$False
}
#rest of function here
}
```
I would not do that for a PowerShell monitor, which you can schedule to run periodically, but for a script to run in the background, the above would work. You could even add some database access code to log the results to a database, or log it to a file.. what ever you want.
|
183,352 |
<p>I want to copy text files and only text files from <code>src/</code> to <code>dst/</code></p>
<pre>
groovy:000> "cp src/*.txt dst/".execute().text
===>
groovy:000>
</pre>
<p>You can see the command executes w/out error but the file <code>src/test.txt</code> does not get copied to <code>dst/</code></p>
<p>This also fails: </p>
<pre>
groovy:000> "cp src/* dst/".execute().text
===>
groovy:000>
</pre>
<p>However...</p>
<pre>
"cp src/this.txt dst/".execute().text
</pre>
<p>works</p>
<p>Also,</p>
<pre>
"cp -R src/ dst".execute().text
</pre>
<p>works</p>
<p>Why dose the wild card seem to cause my command to silently fail?</p>
|
[
{
"answer_id": 183393,
"author": "user10392",
"author_id": 10392,
"author_profile": "https://Stackoverflow.com/users/10392",
"pm_score": 4,
"selected": true,
"text": "<p>Wildcard expansion is performed by the shell, not by cp (or groovy). Your first example is trying to copy a file named *. You could make your command \"sh -c 'cp ...'\"</p>\n"
},
{
"answer_id": 184057,
"author": "JJohnson",
"author_id": 25820,
"author_profile": "https://Stackoverflow.com/users/25820",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks tedu for getting me half way there.</p>\n\n<p>I believe the reason that his solution didn't work was because of an 'escaping' issue.</p>\n\n<p>For instance...</p>\n\n<pre>\n\"sh -c 'ls'\".execute()\n</pre>\n\n<p>works. But...</p>\n\n<pre>\n\"sh -c 'ls '\".execute()\n</pre>\n\n<p>does not.</p>\n\n<p>There is probably a way to escape it properly in line there but the workaround I'm using is to pass a string array to Runtime.getRuntime().exec</p>\n\n<pre>\ncommand = [\"sh\", \"-c\", \"cp src/*.txt dst/\"]\nRuntime.getRuntime().exec((String[]) command.toArray())\n</pre>\n\n<p>works beautifully!</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25820/"
] |
I want to copy text files and only text files from `src/` to `dst/`
```
groovy:000> "cp src/*.txt dst/".execute().text
===>
groovy:000>
```
You can see the command executes w/out error but the file `src/test.txt` does not get copied to `dst/`
This also fails:
```
groovy:000> "cp src/* dst/".execute().text
===>
groovy:000>
```
However...
```
"cp src/this.txt dst/".execute().text
```
works
Also,
```
"cp -R src/ dst".execute().text
```
works
Why dose the wild card seem to cause my command to silently fail?
|
Wildcard expansion is performed by the shell, not by cp (or groovy). Your first example is trying to copy a file named \*. You could make your command "sh -c 'cp ...'"
|
183,353 |
<p>Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound. How do I do this?</p>
|
[
{
"answer_id": 183356,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 4,
"selected": false,
"text": "<p>I found this:</p>\n\n<pre><code>Dim someArray() As Integer\n\nIf ((Not someArray) = -1) Then\n Debug.Print \"this array is NOT initialized\"\nEnd If\n</code></pre>\n\n<p><strong>Edit</strong>: RS Conley pointed out in his <a href=\"https://stackoverflow.com/questions/183353/how-do-i-determine-if-an-array-is-intialized-in-vb6#184407\">answer</a> that (Not someArray) will sometimes return 0, so you have to use ((Not someArray) = -1).</p>\n"
},
{
"answer_id": 183386,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Dim someArray() as Integer \n\nIf someArray Is Nothing Then\n Debug.print \"this array is not initialised\"\nEnd If\n</code></pre>\n"
},
{
"answer_id": 183553,
"author": "Perry Pederson",
"author_id": 26037,
"author_profile": "https://Stackoverflow.com/users/26037",
"pm_score": 0,
"selected": false,
"text": "<p><b><i>If</i></b> the array is a string array, you can use the Join() method as a test:<br></p>\n\n<pre><code>Private Sub Test()\n\n Dim ArrayToTest() As String\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"false\"\n\n ReDim ArrayToTest(1 To 10)\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"true\"\n\n ReDim ArrayToTest(0 To 0)\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"false\"\n\nEnd Sub\n\n\nFunction StringArrayCheck(o As Variant) As Boolean\n\n Dim x As String\n\n x = Join(o)\n\n StringArrayCheck = (Len(x) <> 0)\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 183668,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p><strong>Note:</strong> the code has been updated, the original version can be found in the <a href=\"https://stackoverflow.com/posts/183668/revisions\">revision history</a> (not that it is useful to find it). The updated code does not depend on the undocumented <code>GetMem4</code> function and <a href=\"https://stackoverflow.com/questions/183353/how-do-i-determine-if-an-array-is-initialized-in-vb6#comment16951398_183668\">correctly handles</a> arrays of all types.</p>\n</blockquote>\n\n\n\n<blockquote>\n <p><strong>Note for VBA users:</strong> This code is for VB6 which never got an x64 update. If you intend to use this code for VBA, see <a href=\"https://stackoverflow.com/a/32539884/11683\">https://stackoverflow.com/a/32539884/11683</a> for the VBA version. You will only need to take the <code>CopyMemory</code> declaration and the <code>pArrPtr</code> function, leaving the rest.</p>\n</blockquote>\n\n<p>I use this:</p>\n\n<pre><code>Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" _\n(ByRef Destination As Any, ByRef Source As Any, ByVal length As Long)\n\nPrivate Const VT_BYREF As Long = &H4000&\n\n' When declared in this way, the passed array is wrapped in a Variant/ByRef. It is not copied.\n' Returns *SAFEARRAY, not **SAFEARRAY\nPublic Function pArrPtr(ByRef arr As Variant) As Long\n 'VarType lies to you, hiding important differences. Manual VarType here.\n Dim vt As Integer\n CopyMemory ByVal VarPtr(vt), ByVal VarPtr(arr), Len(vt)\n\n If (vt And vbArray) <> vbArray Then\n Err.Raise 5, , \"Variant must contain an array\"\n End If\n\n 'see https://msdn.microsoft.com/en-us/library/windows/desktop/ms221627%28v=vs.85%29.aspx\n If (vt And VT_BYREF) = VT_BYREF Then\n 'By-ref variant array. Contains **pparray at offset 8\n CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->pparray;\n CopyMemory ByVal VarPtr(pArrPtr), ByVal pArrPtr, Len(pArrPtr) 'pArrPtr = *pArrPtr;\n Else\n 'Non-by-ref variant array. Contains *parray at offset 8\n CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->parray;\n End If\nEnd Function\n\nPublic Function ArrayExists(ByRef arr As Variant) As Boolean\n ArrayExists = pArrPtr(arr) <> 0\nEnd Function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>? ArrayExists(someArray)\n</code></pre>\n\n<p>Your code seems to do the same (testing for SAFEARRAY** being NULL), but in a way which I would consider a compiler bug :)</p>\n"
},
{
"answer_id": 184407,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 3,
"selected": false,
"text": "<p>Both methods by GSerg and Raven are undocumented hacks but since Visual BASIC 6 is no longer being developed then it is not a issue. However Raven's example doesn't work on all machines. You have to test like this.</p>\n\n<p>If (Not someArray) = -1 Then</p>\n\n<p>On some machines it will return a zero on others some large negative number.</p>\n"
},
{
"answer_id": 184909,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 5,
"selected": false,
"text": "<p>I just thought of this one. Simple enough, no API calls needed. Any problems with it?</p>\n\n<pre><code>Public Function IsArrayInitialized(arr) As Boolean\n\n Dim rv As Long\n\n On Error Resume Next\n\n rv = UBound(arr)\n IsArrayInitialized = (Err.Number = 0)\n\nEnd Function\n</code></pre>\n\n<p><strong>Edit</strong>: I did discover a flaw with this related to the behavior of the Split function (actually I'd call it a flaw in the Split function). Take this example:</p>\n\n<pre><code>Dim arr() As String\n\narr = Split(vbNullString, \",\")\nDebug.Print UBound(arr)\n</code></pre>\n\n<p>What is the value of Ubound(arr) at this point? It's -1! So, passing this array to this IsArrayInitialized function would return true, but attempting to access arr(0) would cause a subscript out of range error.</p>\n"
},
{
"answer_id": 444810,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 5,
"selected": true,
"text": "<p>Here's what I went with. This is similar to GSerg's <a href=\"https://stackoverflow.com/questions/183353/how-do-i-determine-if-an-array-is-initialized-in-vb6#183668\">answer</a>, but uses the better documented CopyMemory API function and is entirely self-contained (you can just pass the array rather than ArrPtr(array) to this function). It does use the VarPtr function, which Microsoft <a href=\"http://support.microsoft.com/kb/199824\" rel=\"nofollow noreferrer\">warns against</a>, but this is an XP-only app, and it works, so I'm not concerned.</p>\n\n<p>Yes, I know this function will accept anything you throw at it, but I'll leave the error checking as an exercise for the reader.</p>\n\n<pre><code>Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" _\n (pDst As Any, pSrc As Any, ByVal ByteLen As Long)\n\nPublic Function ArrayIsInitialized(arr) As Boolean\n\n Dim memVal As Long\n\n CopyMemory memVal, ByVal VarPtr(arr) + 8, ByVal 4 'get pointer to array\n CopyMemory memVal, ByVal memVal, ByVal 4 'see if it points to an address... \n ArrayIsInitialized = (memVal <> 0) '...if it does, array is intialized\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 8957426,
"author": "jorge",
"author_id": 1162901,
"author_profile": "https://Stackoverflow.com/users/1162901",
"pm_score": 2,
"selected": false,
"text": "<p>When you initialite the array put an integer or boolean with a flag = 1. and query this flag when you need.</p>\n"
},
{
"answer_id": 11036850,
"author": "SJ00",
"author_id": 1449954,
"author_profile": "https://Stackoverflow.com/users/1449954",
"pm_score": 2,
"selected": false,
"text": "<p>This is modification of raven's <a href=\"https://stackoverflow.com/a/184909/1449954\">answer</a>. Without using API's.</p>\n\n<pre><code>Public Function IsArrayInitalized(ByRef arr() As String) As Boolean\n'Return True if array is initalized\nOn Error GoTo errHandler 'Raise error if directory doesnot exist\n\n Dim temp As Long\n temp = UBound(arr)\n\n 'Reach this point only if arr is initalized i.e. no error occured\n If temp > -1 Then IsArrayInitalized = True 'UBound is greater then -1\n\nExit Function\nerrHandler:\n 'if an error occurs, this function returns False. i.e. array not initialized\nEnd Function\n</code></pre>\n\n<p>This one should also be working in case of split function.\nLimitation is you would need to define type of array (string in this example).</p>\n"
},
{
"answer_id": 11919682,
"author": "Tim.F",
"author_id": 1592985,
"author_profile": "https://Stackoverflow.com/users/1592985",
"pm_score": 0,
"selected": false,
"text": "<p>My only problem with API calls is moving from 32-bit to 64-bit OS's.<br>\nThis works with Objects, Strings, etc... </p>\n\n<pre><code>Public Function ArrayIsInitialized(ByRef arr As Variant) As Boolean\n On Error Resume Next\n ArrayIsInitialized = False\n If UBound(arr) >= 0 Then If Err.Number = 0 Then ArrayIsInitialized = True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 12571599,
"author": "iCodeInVB6",
"author_id": 1695378,
"author_profile": "https://Stackoverflow.com/users/1695378",
"pm_score": 3,
"selected": false,
"text": "<p>In VB6 there is a function called \"IsArray\", but it does not check if the array has been initialized. You will receive Error 9 - Subscript out of range if you attempt to use UBound on an uninitialized array. My method is very similar to S J's, except it works with all variable types and has error handling. If a non-array variable is checked, you will receive Error 13 - Type Mismatch.</p>\n\n<pre><code>Private Function IsArray(vTemp As Variant) As Boolean\n On Error GoTo ProcError\n Dim lTmp As Long\n\n lTmp = UBound(vTemp) ' Error would occur here\n\n IsArray = True: Exit Function\nProcError:\n 'If error is something other than \"Subscript\n 'out of range\", then display the error\n If Not Err.Number = 9 Then Err.Raise (Err.Number)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 24402027,
"author": "madhu_p",
"author_id": 2910423,
"author_profile": "https://Stackoverflow.com/users/2910423",
"pm_score": -1,
"selected": false,
"text": "<p>This worked for me, any bug in this?</p>\n\n<pre><code>If IsEmpty(a) Then\n Exit Function\nEnd If\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa445044%28v=vs.60%29.aspx\" rel=\"nofollow\">MSDN</a></p>\n"
},
{
"answer_id": 29521906,
"author": "Frodo",
"author_id": 4765386,
"author_profile": "https://Stackoverflow.com/users/4765386",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\nPrivate Declare Function ArrPtr Lib \"msvbvm60\" Alias \"VarPtr\" (arr() As Any) As Long\n\nPrivate Type SafeArray\n cDims As Integer\n fFeatures As Integer\n cbElements As Long\n cLocks As Long\n pvData As Long\nEnd Type\n\nPrivate Function ArrayInitialized(ByVal arrayPointer As Long) As Boolean\n Dim pSafeArray As Long\n\n CopyMemory pSafeArray, ByVal arrayPointer, 4\n\n Dim tArrayDescriptor As SafeArray\n\n If pSafeArray Then\n CopyMemory tArrayDescriptor, ByVal pSafeArray, LenB(tArrayDescriptor)\n\n If tArrayDescriptor.cDims > 0 Then ArrayInitialized = True\n End If\n\nEnd Function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Private Type tUDT\n t As Long\nEnd Type\n\nPrivate Sub Form_Load()\n Dim longArrayNotDimmed() As Long\n Dim longArrayDimmed(1) As Long\n\n Dim stringArrayNotDimmed() As String\n Dim stringArrayDimmed(1) As String\n\n Dim udtArrayNotDimmed() As tUDT\n Dim udtArrayDimmed(1) As tUDT\n\n Dim objArrayNotDimmed() As Collection\n Dim objArrayDimmed(1) As Collection\n\n\n Debug.Print \"longArrayNotDimmed \" & ArrayInitialized(ArrPtr(longArrayNotDimmed))\n Debug.Print \"longArrayDimmed \" & ArrayInitialized(ArrPtr(longArrayDimmed))\n\n Debug.Print \"stringArrayNotDimmed \" & ArrayInitialized(ArrPtr(stringArrayNotDimmed))\n Debug.Print \"stringArrayDimmed \" & ArrayInitialized(ArrPtr(stringArrayDimmed))\n\n Debug.Print \"udtArrayNotDimmed \" & ArrayInitialized(ArrPtr(udtArrayNotDimmed))\n Debug.Print \"udtArrayDimmed \" & ArrayInitialized(ArrPtr(udtArrayDimmed))\n\n Debug.Print \"objArrayNotDimmed \" & ArrayInitialized(ArrPtr(objArrayNotDimmed))\n Debug.Print \"objArrayDimmed \" & ArrayInitialized(ArrPtr(objArrayDimmed))\n\n Unload Me\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 29976878,
"author": "DarrenMB",
"author_id": 813266,
"author_profile": "https://Stackoverflow.com/users/813266",
"pm_score": 1,
"selected": false,
"text": "<p>Based on all the information I read in this existing post this works the best for me when dealing with a typed array that starts as uninitialized. </p>\n\n<p>It keeps the testing code consistent with the usage of UBOUND and It does not require the usage of error handling for testing.</p>\n\n<p>It IS dependent on Zero Based Arrays (which is the case in most development).</p>\n\n<p>Must not use \"Erase\" to clear the array. use alternative listed below.</p>\n\n<pre><code>Dim data() as string ' creates the untestable holder.\ndata = Split(vbNullString, \",\") ' causes array to return ubound(data) = -1\nIf Ubound(data)=-1 then ' has no contents\n ' do something\nEnd If\nredim preserve data(Ubound(data)+1) ' works to increase array size regardless of it being empty or not.\n\ndata = Split(vbNullString, \",\") ' MUST use this to clear the array again.\n</code></pre>\n"
},
{
"answer_id": 34247077,
"author": "omegastripes",
"author_id": 2165759,
"author_profile": "https://Stackoverflow.com/users/2165759",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve the issue with <code>Ubound()</code> function, check if the array is empty by retrieving total elements count using JScript's <code>VBArray()</code> object (works with arrays of variant type, single or multidimensional):</p>\n\n<pre><code>Sub Test()\n\n Dim a() As Variant\n Dim b As Variant\n Dim c As Long\n\n ' Uninitialized array of variant\n ' MsgBox UBound(a) ' gives 'Subscript out of range' error\n MsgBox GetElementsCount(a) ' 0\n\n ' Variant containing an empty array\n b = Array()\n MsgBox GetElementsCount(b) ' 0\n\n ' Any other types, eg Long or not Variant type arrays\n MsgBox GetElementsCount(c) ' -1\n\nEnd Sub\n\nFunction GetElementsCount(aSample) As Long\n\n Static oHtmlfile As Object ' instantiate once\n\n If oHtmlfile Is Nothing Then\n Set oHtmlfile = CreateObject(\"htmlfile\")\n oHtmlfile.parentWindow.execScript (\"function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}\"), \"jscript\"\n End If\n GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)\n\nEnd Function\n</code></pre>\n\n<p>For me it takes about 0.4 mksec for each element + 100 msec initialization, being compiled with VB 6.0.9782, so the array of 10M elements takes about 4.1 sec. The same functionality could be implemented via <code>ScriptControl</code> ActiveX.</p>\n"
},
{
"answer_id": 38333764,
"author": "Senchiu Peter",
"author_id": 6231641,
"author_profile": "https://Stackoverflow.com/users/6231641",
"pm_score": 0,
"selected": false,
"text": "<pre><code>If ChkArray(MyArray)=True then\n ....\nEnd If\n\nPublic Function ChkArray(ByRef b) As Boolean\n On Error goto 1\n If UBound(b) > 0 Then ChkArray = True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 39487795,
"author": "Bucket123",
"author_id": 6830358,
"author_profile": "https://Stackoverflow.com/users/6830358",
"pm_score": 0,
"selected": false,
"text": "<p>There are two slightly different scenarios to test:</p>\n\n<ol>\n<li>The array is initialised (effectively it is not a null pointer)</li>\n<li>The array is initialised and has at least one element</li>\n</ol>\n\n<p>Case 2 is required for cases like <code>Split(vbNullString, \",\")</code> which returns a <code>String</code> array with <code>LBound=0</code> and <code>UBound=-1</code>.\nHere are the simplest example code snippets I can produce for each test:</p>\n\n<pre><code>Public Function IsInitialised(arr() As String) As Boolean\n On Error Resume Next\n IsInitialised = UBound(arr) <> 0.5\nEnd Function\n\nPublic Function IsInitialisedAndHasElements(arr() As String) As Boolean\n On Error Resume Next\n IsInitialisedAndHasElements = UBound(arr) >= LBound(arr)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 46369161,
"author": "Kip Densley",
"author_id": 8657020,
"author_profile": "https://Stackoverflow.com/users/8657020",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to handle this is to insure that the array is initialized up front, before you need to check for the Ubound. I needed an array that was declared in the (General) area of the form code.\ni.e.</p>\n\n<pre><code>Dim arySomeArray() As sometype\n</code></pre>\n\n<p>Then in the form load routine I redim the array:</p>\n\n<pre><code>Private Sub Form_Load()\n\nReDim arySomeArray(1) As sometype 'insure that the array is initialized\n\nEnd Sub \n</code></pre>\n\n<p>This will allow the array to be re-defined at any point later in the program.\nWhen you find out how big the array needs to be just redim it.</p>\n\n<pre><code>ReDim arySomeArray(i) As sometype 'i is the size needed to hold the new data\n</code></pre>\n"
},
{
"answer_id": 48798482,
"author": "stenci",
"author_id": 1899628,
"author_profile": "https://Stackoverflow.com/users/1899628",
"pm_score": 1,
"selected": false,
"text": "<p>The title of the question asks how to determine if an array is initialized, but, after reading the question, it looks like the real problem is how to get the <code>UBound</code> of an array that is not initialized. </p>\n\n<p>Here is my solution (to the the actual problem, not to the title):</p>\n\n<pre><code>Function UBound2(Arr) As Integer\n On Error Resume Next\n UBound2 = UBound(Arr)\n If Err.Number = 9 Then UBound2 = -1\n On Error GoTo 0\nEnd Function\n</code></pre>\n\n<p>This function works in the following four scenarios, the first three that I have found when <code>Arr</code> is created by an external dll COM and the fourth when the <code>Arr</code> is not <code>ReDim</code>-ed (the subject of this question):</p>\n\n<ul>\n<li><code>UBound(Arr)</code> works, so calling <code>UBound2(Arr)</code> adds a little overhead, but doesn't hurt much</li>\n<li><code>UBound(Arr)</code> fails in in the function that defines <code>Arr</code>, but succeeds inside <code>UBound2()</code></li>\n<li><code>UBound(Arr)</code> fails both in the function that defines <code>Arr</code> and in <code>UBound2()</code>, so the error handling does the job</li>\n<li>After <code>Dim Arr() As Whatever</code>, before <code>ReDim Arr(X)</code></li>\n</ul>\n"
},
{
"answer_id": 52508629,
"author": "Evan TOder",
"author_id": 9499395,
"author_profile": "https://Stackoverflow.com/users/9499395",
"pm_score": -1,
"selected": false,
"text": "<p>I see a lot of suggestions online about <strong>how to tell if an array has been initialized</strong>. Below is a function that will take any array, check what the ubound of that array is, redimension the array to ubound +1 (with or without PRESERVER) and then return what the current ubound of the array is, without errors.</p>\n\n<pre><code>Function ifuncRedimUbound(ByRef byrefArr, Optional bPreserve As Boolean)\nOn Error GoTo err:\n\n1: Dim upp%: upp% = (UBound(byrefArr) + 1)\n\nerrContinue:\n\nIf bPreserve Then\n ReDim Preserve byrefArr(upp%)\nElse\n ReDim byrefArr(upp%)\nEnd If\n\nifuncRedimUbound = upp%\n\n\nExit Function\nerr:\nIf err.Number = 0 Then Resume Next\n If err.Number = 9 Then ' subscript out of range (array has not been initialized yet)\n If Erl = 1 Then\n upp% = 0\n GoTo errContinue:\n End If\n Else\n ErrHandler.ReportError \"modArray\", ifuncRedimUbound, \"1\", err.Number, err.Description\n End If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 54413405,
"author": "Scruff",
"author_id": 7099352,
"author_profile": "https://Stackoverflow.com/users/7099352",
"pm_score": 1,
"selected": false,
"text": "<p>For any variable declared as an array, you can easily check if the array is initialized by calling the SafeArrayGetDim API. If the array is initialized, then the return value will be non-zero, otherwise the function returns zero.</p>\n\n<p>Note that you can't use this function with variants that contain arrays. Doing so will cause a Compile error (Type mismatch).</p>\n\n<pre><code>Public Declare Function SafeArrayGetDim Lib \"oleaut32.dll\" (psa() As Any) As Long\n\nPublic Sub Main()\n Dim MyArray() As String\n\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(64)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Erase MyArray\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(31, 15, 63)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Erase MyArray\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(127)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Dim vArray As Variant\n vArray = MyArray\n ' If you uncomment the next line, the program won't compile or run.\n 'Debug.Print SafeArrayGetDim(vArray) ' <- Type mismatch\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 58472962,
"author": "Francisco Costa",
"author_id": 11554034,
"author_profile": "https://Stackoverflow.com/users/11554034",
"pm_score": 2,
"selected": false,
"text": "<p>Since wanted comment on here will post answer.</p>\n\n<p>Correct answer seems is from @raven:</p>\n\n<pre><code>Dim someArray() As Integer\n\nIf ((Not someArray) = -1) Then\n Debug.Print \"this array is NOT initialized\"\nEnd If\n</code></pre>\n\n<p>When documentation or Google does not immediately return an explanation people tend to call it a hack.\nAlthough what seems to be the explanation is that <strong>Not</strong> is not only a <strong>Logical, it is also a Bitwise operator, so it handles</strong> the bit representation of structures, rather than Booleans only.</p>\n\n<p>For example of another bitwise operation is here:</p>\n\n<pre><code>Dim x As Integer\nx = 3 And 5 'x=1\n</code></pre>\n\n<p>So the above And is also being treated as a bitwise operator.</p>\n\n<p>Furthermore, and worth to check, even if not the directly related with this,</p>\n\n<blockquote>\n <p>The Not operator can be overloaded, which means that a class or\n structure can redefine its behavior when its operand has the type of\n that class or structure.\n <a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/logical-and-bitwise-operators\" rel=\"nofollow noreferrer\">Overloading</a></p>\n</blockquote>\n\n<p>Accordingly, Not is interpreting the array as its bitwise representation and it distinguishes output when array is empty or not like differently in the form of signed number. So it can be considered this is not a hack, is just an undocumentation of the array bitwise representation, which Not here is exposing and taking advantage of.</p>\n\n<blockquote>\n <p>Not takes a single operand and inverts all the bits, including the\n sign bit, and assigns that value to the result. This means that for\n signed positive numbers, Not always returns a negative value, and for\n negative numbers, Not always returns a positive or zero value.\n <a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/not-operator\" rel=\"nofollow noreferrer\">Logical Bitwise</a></p>\n</blockquote>\n\n<p>Having decided to post since this offered a new approach which is welcome to be expanded, completed or adjusted by anyone who has access to how arrays are being represented in their structure. So if anyone offers proof it is actually not intended for arrays to be treated by Not bitwise we should accept it as not a hack and actually as best clean answer, if they do or do not offer any support for this theory, if it is constructive comment on this is welcome of course.</p>\n"
},
{
"answer_id": 74490992,
"author": "Uno Buscando",
"author_id": 12421921,
"author_profile": "https://Stackoverflow.com/users/12421921",
"pm_score": 0,
"selected": false,
"text": "<p>Either of these two ways is valid to detect an uninitialized array, but they must include the parentheses:</p>\n<pre><code>(Not myArray) = -1\n(Not Not myArray) = 0\n</code></pre>\n"
},
{
"answer_id": 74564243,
"author": "Ardax",
"author_id": 15565257,
"author_profile": "https://Stackoverflow.com/users/15565257",
"pm_score": 0,
"selected": false,
"text": "<pre><code>' Function CountElements return counted elements of an array.\n' Returns:\n' [ -1]. If the argument is not an array.\n' [ 0]. If the argument is a not initialized array.\n' [Count of elements]. If the argument is an initialized array.\nPrivate Function CountElements(ByRef vArray As Variant) As Integer\n\n ' Check whether the argument is an array.\n If (VarType(vArray) And vbArray) <> vbArray Then\n \n ' Not an array. CountElements is set to -1.\n Let CountElements = -1\n \n Else\n \n On Error Resume Next\n \n ' Calculate number of elements in array.\n ' Scenarios:\n ' - Array is initialized. CountElements is set to counted elements.\n ' - Array is NOT initialized. CountElements is never set and keeps its\n ' initial value of zero (since an error is\n ' raised).\n Let CountElements = (UBound(vArray) - LBound(vArray)) + 1\n \n End If\n \nEnd Function\n\n\n' Test of function CountElements.\n\n Dim arrStr() As String\n Dim arrV As Variant\n \n Let iCount = CountElements(arrStr) ' arrStr is not initialized, returns 0.\n ReDim arrStr(2)\n Let iCount = CountElements(arrStr) ' arrStr is initialized, returns 3.\n ReDim arrStr(5 To 8)\n Let iCount = CountElements(arrStr) ' arrStr is initialized, returns 4.\n Let arrV = arrStr\n Let iCount = CountElements(arrV) ' arrV contains a boxed arrStr which is initialized, returns 4\n Erase arrStr\n Let iCount = CountElements(arrStr) ' arrStr size is erased, returns 0.\n \n Let iCount = CountElements(Nothing) ' Nothing is not an array, returns -1.\n Let iCount = CountElements(Null) ' Null is not an array, returns -1.\n Let iCount = CountElements(5) ' Figure is not an array, returns -1.\n Let iCount = CountElements("My imaginary array") ' Text is not an array, returns -1.\n Let iCount = CountElements(Array(1, 2, 3, 4, 5)) ' Created array of Integer elements, returns 5.\n Let iCount = CountElements(Array("A", "B", "C")) ' Created array of String elements, returns 3.\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound. How do I do this?
|
Here's what I went with. This is similar to GSerg's [answer](https://stackoverflow.com/questions/183353/how-do-i-determine-if-an-array-is-initialized-in-vb6#183668), but uses the better documented CopyMemory API function and is entirely self-contained (you can just pass the array rather than ArrPtr(array) to this function). It does use the VarPtr function, which Microsoft [warns against](http://support.microsoft.com/kb/199824), but this is an XP-only app, and it works, so I'm not concerned.
Yes, I know this function will accept anything you throw at it, but I'll leave the error checking as an exercise for the reader.
```
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(pDst As Any, pSrc As Any, ByVal ByteLen As Long)
Public Function ArrayIsInitialized(arr) As Boolean
Dim memVal As Long
CopyMemory memVal, ByVal VarPtr(arr) + 8, ByVal 4 'get pointer to array
CopyMemory memVal, ByVal memVal, ByVal 4 'see if it points to an address...
ArrayIsInitialized = (memVal <> 0) '...if it does, array is intialized
End Function
```
|
183,366 |
<p>I have a SEAM app with some JPA/Hibernate entities. And I now wonder where to put my query, persistence methods.</p>
<p>The default choice seems to put them in a session bean layer with injected </p>
<pre><code>@PersistenceContext(...) @Inject EntityManager entityManager;
</code></pre>
<p>But I think I would rather have the methods on the entities themselves. What are the pro's/con's? </p>
<ol>
<li>Testablity?</li>
<li>Niceness?</li>
<li>Performance?</li>
</ol>
<p>And does anyone have links to best practices for interacting with the EntityManager etc. from methods on the Entities rather than session beans?</p>
<p>Best,
Anders</p>
|
[
{
"answer_id": 183388,
"author": "Rolf",
"author_id": 3540161,
"author_profile": "https://Stackoverflow.com/users/3540161",
"pm_score": 3,
"selected": true,
"text": "<p>I have no experience with SEAM, but from my experience with Java projects, I found it easiest to keep beans clear of persist methods. What we usually do:</p>\n\n<ul>\n<li>Have beans for business objects (like \"User\" and \"Setting\" for example)</li>\n<li>Have a DAO layer which can persist and retrieve these beans (simple CRUD)</li>\n<li>Have a Service Layer which nows how to handle the beans, and maybe even how to build an aggregate of beans</li>\n</ul>\n\n<p>This way, everything is pretty separated, and is easy to unittest. Performance is usually not an issue with this setup.</p>\n"
},
{
"answer_id": 183413,
"author": "anders.norgaard",
"author_id": 8805,
"author_profile": "https://Stackoverflow.com/users/8805",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, that is also what I have done before.</p>\n\n<p>In general, I think, EJB is insanely verbose and boilerplate'y, but SEAM actually helps a bit, so that is why, in my current project, the extra layer of session beans just to query and persist annoys me. I have the feeling that I could make a reasonably concise app if I could kill this layer...</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8805/"
] |
I have a SEAM app with some JPA/Hibernate entities. And I now wonder where to put my query, persistence methods.
The default choice seems to put them in a session bean layer with injected
```
@PersistenceContext(...) @Inject EntityManager entityManager;
```
But I think I would rather have the methods on the entities themselves. What are the pro's/con's?
1. Testablity?
2. Niceness?
3. Performance?
And does anyone have links to best practices for interacting with the EntityManager etc. from methods on the Entities rather than session beans?
Best,
Anders
|
I have no experience with SEAM, but from my experience with Java projects, I found it easiest to keep beans clear of persist methods. What we usually do:
* Have beans for business objects (like "User" and "Setting" for example)
* Have a DAO layer which can persist and retrieve these beans (simple CRUD)
* Have a Service Layer which nows how to handle the beans, and maybe even how to build an aggregate of beans
This way, everything is pretty separated, and is easy to unittest. Performance is usually not an issue with this setup.
|
183,367 |
<p>Is it possible to unsubscribe an anonymous method from an event?</p>
<p>If I subscribe to an event like this:</p>
<pre><code>void MyMethod()
{
Console.WriteLine("I did it!");
}
MyEvent += MyMethod;
</code></pre>
<p>I can un-subscribe like this:</p>
<pre><code>MyEvent -= MyMethod;
</code></pre>
<p>But if I subscribe using an anonymous method:</p>
<pre><code>MyEvent += delegate(){Console.WriteLine("I did it!");};
</code></pre>
<p>is it possible to unsubscribe this anonymous method? If so, how?</p>
|
[
{
"answer_id": 183380,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>From memory, the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods.</p>\n\n<p>If you need to unsubscribe, you should either use a \"normal\" method or retain the delegate somewhere else so you can unsubscribe with exactly the same delegate you used to subscribe.</p>\n"
},
{
"answer_id": 183389,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 3,
"selected": false,
"text": "<p>Kind of lame approach:</p>\n\n<pre><code>public class SomeClass\n{\n private readonly IList<Action> _eventList = new List<Action>();\n\n ...\n\n public event Action OnDoSomething\n {\n add {\n _eventList.Add(value);\n }\n remove {\n _eventList.Remove(value);\n }\n }\n}\n</code></pre>\n\n<ol>\n<li>Override the event add/remove methods.</li>\n<li>Keep a list of those event handlers.</li>\n<li>When needed, clear them all and re-add the others.</li>\n</ol>\n\n<p>This may not work or be the most efficient method, but should get the job done.</p>\n"
},
{
"answer_id": 183408,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 9,
"selected": true,
"text": "<pre><code>Action myDelegate = delegate(){Console.WriteLine(\"I did it!\");};\n\nMyEvent += myDelegate;\n\n\n// .... later\n\nMyEvent -= myDelegate;\n</code></pre>\n\n<p>Just keep a reference to the delegate around.</p>\n"
},
{
"answer_id": 183417,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 7,
"selected": false,
"text": "<p>One technique is to declare a variable to hold the anonymous method which would then be available inside the anonymous method itself. This worked for me because the desired behavior was to unsubscribe after the event was handled.</p>\n\n<p>Example:</p>\n\n<pre><code>MyEventHandler foo = null;\nfoo = delegate(object s, MyEventArgs ev)\n {\n Console.WriteLine(\"I did it!\");\n MyEvent -= foo;\n };\nMyEvent += foo;\n</code></pre>\n"
},
{
"answer_id": 1169186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>In 3.0 can be shortened to:</p>\n\n<pre><code>MyHandler myDelegate = ()=>Console.WriteLine(\"I did it!\");\nMyEvent += myDelegate;\n...\nMyEvent -= myDelegate;\n</code></pre>\n"
},
{
"answer_id": 1747285,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to be able to control unsubscription then you need to go the route indicated in your accepted answer. However, if you are just concerned about clearing up references when your subscribing class goes out of scope, then there is another (slightly convoluted) solution which involves using weak references. I've just posted a <a href=\"https://stackoverflow.com/questions/1747235/weak-event-handler-model-for-use-with-lambdas/1747236#1747236\">question and answer</a> on this topic.</p>\n"
},
{
"answer_id": 6461687,
"author": "hemme",
"author_id": 249992,
"author_profile": "https://Stackoverflow.com/users/249992",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of keeping a reference to any delegate you can instrument your class in order to give the event's invocation list back to the caller. Basically you can write something like this (assuming that MyEvent is declared inside MyClass):</p>\n\n<pre><code>public class MyClass \n{\n public event EventHandler MyEvent;\n\n public IEnumerable<EventHandler> GetMyEventHandlers() \n { \n return from d in MyEvent.GetInvocationList() \n select (EventHandler)d; \n } \n}\n</code></pre>\n\n<p>So you can access the whole invocation list from outside MyClass and unsubscribe any handler you want. For instance:</p>\n\n<pre><code>myClass.MyEvent -= myClass.GetMyEventHandlers().Last();\n</code></pre>\n\n<p>I've written a full post about this tecnique <a href=\"http://www.h3mm3.com/2011/06/unsubscribing-to-events-in-c.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 21248480,
"author": "user3217549",
"author_id": 3217549,
"author_profile": "https://Stackoverflow.com/users/3217549",
"pm_score": 0,
"selected": false,
"text": "<p>if you want refer to some object with this delegate, may be you can use Delegate.CreateDelegate(Type, Object target, MethodInfo methodInfo)\n.net consider the delegate equals by target and methodInfo</p>\n"
},
{
"answer_id": 24713749,
"author": "Manuel Marhold",
"author_id": 3832406,
"author_profile": "https://Stackoverflow.com/users/3832406",
"pm_score": 2,
"selected": false,
"text": "<p>One simple solution:</p>\n\n<p>just pass the eventhandle variable as parameter to itself.\nEvent if you have the case that you cannot access the original created variable because of multithreading, you can use this:</p>\n\n<pre><code>MyEventHandler foo = null;\nfoo = (s, ev, mehi) => MyMethod(s, ev, foo);\nMyEvent += foo;\n\nvoid MyMethod(object s, MyEventArgs ev, MyEventHandler myEventHandlerInstance)\n{\n MyEvent -= myEventHandlerInstance;\n Console.WriteLine(\"I did it!\");\n}\n</code></pre>\n"
},
{
"answer_id": 40013967,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 0,
"selected": false,
"text": "<p>If the best way is to keep a reference on the subscribed eventHandler, this can be achieved using a Dictionary.</p>\n\n<p>In this example, I have to use a anonymous method to include the mergeColumn parameter for a set of DataGridViews.</p>\n\n<p>Using the MergeColumn method with the enable parameter set to true enables the event while using it with false disables it.</p>\n\n<pre><code>static Dictionary<DataGridView, PaintEventHandler> subscriptions = new Dictionary<DataGridView, PaintEventHandler>();\n\npublic static void MergeColumns(this DataGridView dg, bool enable, params ColumnGroup[] mergedColumns) {\n\n if(enable) {\n subscriptions[dg] = (s, e) => Dg_Paint(s, e, mergedColumns);\n dg.Paint += subscriptions[dg];\n }\n else {\n if(subscriptions.ContainsKey(dg)) {\n dg.Paint -= subscriptions[dg];\n subscriptions.Remove(dg);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45686903,
"author": "mazharenko",
"author_id": 3237954,
"author_profile": "https://Stackoverflow.com/users/3237954",
"pm_score": 5,
"selected": false,
"text": "<p>Since <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions\" rel=\"noreferrer\">C# 7.0 local functions</a> feature has been released, the approach <a href=\"https://stackoverflow.com/a/183417/3237954\">suggested</a> by <a href=\"https://stackoverflow.com/users/25837\">J c</a> becomes really neat.</p>\n\n<pre><code>void foo(object s, MyEventArgs ev)\n{\n Console.WriteLine(\"I did it!\");\n MyEvent -= foo;\n};\nMyEvent += foo;\n</code></pre>\n\n<p>So, honestly, you do not have an anonymous function as a variable here. But I suppose the motivation to use it in your case can be applied to local functions.</p>\n"
},
{
"answer_id": 67039790,
"author": "unggyu",
"author_id": 8910867,
"author_profile": "https://Stackoverflow.com/users/8910867",
"pm_score": 0,
"selected": false,
"text": "<p>There is a way to solve this by implementing the closure yourself instead of a lambda expression.</p>\n<p>Assume that the class to be used as a capture variable is as follows.</p>\n<pre><code>public class A\n{\n public void DoSomething()\n {\n ...\n }\n}\n\npublic class B\n{\n public void DoSomething()\n {\n ...\n }\n}\n\npublic class C\n{\n public void DoSomething()\n {\n ...\n }\n}\n</code></pre>\n<p>These classes will be used as capture variables, so we instantiate them.</p>\n<pre><code>A a = new A();\nB b = new B();\nC c = new C();\n</code></pre>\n<p>Implement the closure class as shown below.</p>\n<pre><code>private class EventHandlerClosure\n{\n public A a;\n public B b;\n public C c;\n\n public event EventHandler Finished;\n\n public void MyMethod(object, MyEventArgs args)\n {\n a.DoSomething();\n b.DoSomething();\n c.DoSomething();\n Console.WriteLine("I did it!");\n\n Finished?.Invoke(this, EventArgs.Empty);\n }\n}\n</code></pre>\n<p>Instantiate the closure class, create a handler, then subscribe to the event and subscribe to the lambda expression that unsubscribes from the closure class's Finished event.</p>\n<pre><code>var closure = new EventHandlerClosure\n{\n a = a,\n b = b,\n c = c\n};\nvar handler = new MyEventHandler(closure.MyMethod);\nMyEvent += handler;\nclosure.Finished += (s, e)\n{\n MyEvent -= handler;\n}\n</code></pre>\n"
},
{
"answer_id": 68340973,
"author": "Bobby Oster",
"author_id": 974053,
"author_profile": "https://Stackoverflow.com/users/974053",
"pm_score": 0,
"selected": false,
"text": "<p>I discovered this quite old thread recently for a C# project and found all the answers very useful. However, there was one aspect that didn't work well for my particular use case - they all put the burden of unsubscribing from an event on the subscriber. I understand that one could make the argument that it's the subscribers job to handle this, however that isn't realistic for my project.</p>\n<p>My primary use case for events is for listening to timers to sequence animations (it's a game). In this scenario, I use a lot of anonymous delegates to chain together sequences. Storing a reference to these isn't very practical.</p>\n<p>In order to solve this, I've created a wrapper class around an event that lets you subscribe for a single invocation.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>internal class EventWrapper<TEventArgs> {\n \n private event EventHandler<TEventArgs> Event;\n private readonly HashSet<EventHandler<TEventArgs>> _subscribeOnces;\n \n internal EventWrapper() {\n _subscribeOnces = new HashSet<EventHandler<TEventArgs>>();\n }\n\n internal void Subscribe(EventHandler<TEventArgs> eventHandler) {\n Event += eventHandler;\n }\n\n internal void SubscribeOnce(EventHandler<TEventArgs> eventHandler) {\n _subscribeOnces.Add(eventHandler);\n Event += eventHandler;\n }\n\n internal void Unsubscribe(EventHandler<TEventArgs> eventHandler) {\n Event -= eventHandler;\n }\n\n internal void UnsubscribeAll() {\n foreach (EventHandler<TEventArgs> eventHandler in Event?.GetInvocationList()) {\n Event -= eventHandler;\n }\n }\n\n internal void Invoke(Object sender, TEventArgs e) {\n Event?.Invoke(sender, e);\n if(_subscribeOnces.Count > 0) {\n foreach (EventHandler<TEventArgs> eventHandler in _subscribeOnces) {\n Event -= eventHandler;\n }\n _subscribeOnces.Clear();\n }\n }\n\n internal void Remove() {\n UnsubscribeAll();\n _subscribeOnces.Clear();\n }\n}\n</code></pre>\n\n<p>The side benefit of having this in a class is that you can make it private and expose only the functionality you want. For example, only expose the SubscribeOnce (and not the Subscribe) method.</p>\n<pre class=\"lang-sharp prettyprint-override\"><code>public class MyClass {\n \n private EventWrapper<MyEventEventArgs> myEvent = new EventWrapper<MyEventEventArgs>();\n \n public void FireMyEvent() {\n myEvent.Invoke(this, new MyEventEventArgs(1000, DateTime.Now));\n }\n \n public void SubscribeOnce(EventHandler<MyEventEventArgs> eventHandler) {\n myEvent.SubscribeOnce(eventHandler);\n }\n \n public class MyEventEventArgs : EventArgs {\n public int MyInt;\n public DateTime MyDateTime;\n \n public MyEventEventArgs(int myInt, DateTime myDateTime) {\n MyInt = myInt;\n MyDateTime = myDateTime;\n }\n }\n}\n</code></pre>\n\n<p>The tradeoff here is more overhead for having an instance of this for each event, however in my scenario - this is an acceptable tradeoff to ensure that garbage gets collected efficiently and the code is more maintainable on the subscriber side. <a href=\"https://dotnetfiddle.net/uTot06\" rel=\"nofollow noreferrer\">Full example here</a>.</p>\n"
},
{
"answer_id": 73151101,
"author": "Beauty",
"author_id": 789423,
"author_profile": "https://Stackoverflow.com/users/789423",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a simple solution, which <strong>removes all assigned methods</strong> from an event. Also anonymous methods.</p>\n<p>Use this code and adjust the names.</p>\n<pre><code>if (MyEvent != null)\n foreach (Delegate del in MyEvent.GetInvocationList())\n MyEvent -= (EventHandler<MyEventHandlerType>)del;\n</code></pre>\n<p>Example usage</p>\n<pre><code>public class SomeClass\n{\n public event EventHandler<NiceEventArgs> NiceEvent;\n\n public void RemoveHandlers()\n {\n if (NiceEvent != null)\n foreach (Delegate del in NiceEvent.GetInvocationList())\n NiceEvent -= (EventHandler<NiceEventArgs>)del;\n }\n}\n</code></pre>\n<p>Thanks to <a href=\"https://stackoverflow.com/a/6461687/789423\">hemme's answer</a>, which I used as inspiration.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610/"
] |
Is it possible to unsubscribe an anonymous method from an event?
If I subscribe to an event like this:
```
void MyMethod()
{
Console.WriteLine("I did it!");
}
MyEvent += MyMethod;
```
I can un-subscribe like this:
```
MyEvent -= MyMethod;
```
But if I subscribe using an anonymous method:
```
MyEvent += delegate(){Console.WriteLine("I did it!");};
```
is it possible to unsubscribe this anonymous method? If so, how?
|
```
Action myDelegate = delegate(){Console.WriteLine("I did it!");};
MyEvent += myDelegate;
// .... later
MyEvent -= myDelegate;
```
Just keep a reference to the delegate around.
|
183,391 |
<p>I have a project where I am taking some particularly ugly "live" HTML and forcing it into a formal XML DOM with the HTML Agility Pack. What I would like to be able to do is then query over this with Linq to XML so that I can scrape out the bits I need. I'm using the method described <a href="http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx" rel="nofollow noreferrer">here</a> to parse the HtmlDocument into an XDocument, but when trying to query over this I'm not sure how to handle namespaces. In one particular document the original HTML was actually poorly formatted XHTML with the following tag:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
</code></pre>
<p>When trying to query from this document it seems that the namespace attribute is preventing me from doing something like:</p>
<pre><code>var x = xDoc.Descendants("div");
// returns null
</code></pre>
<p>Apparently for those "div" tags only the LocalName is "div", but the proper tag name is the namespace plus "div". I have tried to do some research on the issue of XML namespaces and it seems that I can bypass the namespace by querying this way:</p>
<pre><code>var x =
(from x in xDoc.Descendants()
where x.Name.LocalName == "div"
select x);
// works
</code></pre>
<p>However, this seems like a rather hacky solution and does not properly address the namespace issue. As I understand it a proper XML document can contain multiple namespaces and therefore the proper way to handle it should be to parse out the namespaces I'm querying under. Has anyone else ever had to do this? Am I just making it way to complicated? I know that I could avoid all this by just sticking with HtmlDocument and querying with XPath, but I would rather stick to what I know (Linq) if possible and I would also prefer to know that I am not setting myself up for further namespace-related issues down the road.</p>
<p>What is the proper way to deal with namespaces in this situation?</p>
|
[
{
"answer_id": 183403,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>Using <code>LocalName</code> should be okay. I wouldn't consider it a hack at all if you don't care what namespace it's in. </p>\n\n<p>If you know the namespace you want and you want to specify it, you can:</p>\n\n<pre><code>var ns = \"{http://www.w3.org/1999/xhtml}\";\nvar x = xDoc.Root.Descendants(ns + \"div\");\n</code></pre>\n\n<p>(<a href=\"http://msdn.microsoft.com/en-us/library/bb669152.aspx\" rel=\"nofollow noreferrer\">MSDN reference</a>)</p>\n\n<p>You can also get a list of all the namespaces used in the document:</p>\n\n<pre><code>var namespaces = (from x in xDoc.Root.DescendantsAndSelf()\n select x.Name.Namespace).Distinct();\n</code></pre>\n\n<p>I suppose you could use that to do this but it's not really any less of a hack:</p>\n\n<pre><code>var x = namespaces.SelectMany(ns=>xDoc.Root.Descendants(ns+\"div\"));\n</code></pre>\n"
},
{
"answer_id": 183414,
"author": "piers7",
"author_id": 26167,
"author_profile": "https://Stackoverflow.com/users/26167",
"pm_score": -1,
"selected": false,
"text": "<p>I think your Google-fu fails you:</p>\n\n<p><a href=\"http://www.google.com.au/search?hl=en&q=linq+xml+namespaces\" rel=\"nofollow noreferrer\">http://www.google.com.au/search?hl=en&q=linq+xml+namespaces</a></p>\n"
},
{
"answer_id": 11832644,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 2,
"selected": false,
"text": "<p>If you know that the namespace is going to be declared by the root element of the XML, as is most often the case, you can do this:</p>\n\n<pre><code>var ns = xDoc.Root.Name.Namespace;\nvar x = xDoc.Descendants(ns + \"div\");\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24608/"
] |
I have a project where I am taking some particularly ugly "live" HTML and forcing it into a formal XML DOM with the HTML Agility Pack. What I would like to be able to do is then query over this with Linq to XML so that I can scrape out the bits I need. I'm using the method described [here](http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx) to parse the HtmlDocument into an XDocument, but when trying to query over this I'm not sure how to handle namespaces. In one particular document the original HTML was actually poorly formatted XHTML with the following tag:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
```
When trying to query from this document it seems that the namespace attribute is preventing me from doing something like:
```
var x = xDoc.Descendants("div");
// returns null
```
Apparently for those "div" tags only the LocalName is "div", but the proper tag name is the namespace plus "div". I have tried to do some research on the issue of XML namespaces and it seems that I can bypass the namespace by querying this way:
```
var x =
(from x in xDoc.Descendants()
where x.Name.LocalName == "div"
select x);
// works
```
However, this seems like a rather hacky solution and does not properly address the namespace issue. As I understand it a proper XML document can contain multiple namespaces and therefore the proper way to handle it should be to parse out the namespaces I'm querying under. Has anyone else ever had to do this? Am I just making it way to complicated? I know that I could avoid all this by just sticking with HtmlDocument and querying with XPath, but I would rather stick to what I know (Linq) if possible and I would also prefer to know that I am not setting myself up for further namespace-related issues down the road.
What is the proper way to deal with namespaces in this situation?
|
Using `LocalName` should be okay. I wouldn't consider it a hack at all if you don't care what namespace it's in.
If you know the namespace you want and you want to specify it, you can:
```
var ns = "{http://www.w3.org/1999/xhtml}";
var x = xDoc.Root.Descendants(ns + "div");
```
([MSDN reference](http://msdn.microsoft.com/en-us/library/bb669152.aspx))
You can also get a list of all the namespaces used in the document:
```
var namespaces = (from x in xDoc.Root.DescendantsAndSelf()
select x.Name.Namespace).Distinct();
```
I suppose you could use that to do this but it's not really any less of a hack:
```
var x = namespaces.SelectMany(ns=>xDoc.Root.Descendants(ns+"div"));
```
|
183,406 |
<p>How can I add a line break to text when it is being set as an attribute i.e.:</p>
<pre><code><TextBlock Text="Stuff on line1 \n Stuff on line2" />
</code></pre>
<p>Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following:</p>
<pre><code><TextBlock>
<TextBlock.Text>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock.Text>
<TextBlock/>
</code></pre>
|
[
{
"answer_id": 183435,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 10,
"selected": true,
"text": "<pre><code><TextBlock Text=\"Stuff on line1&#x0a;Stuff on line 2\"/>\n</code></pre>\n\n<p>You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do \"classic\" <code>vbCrLf</code>, then you can use <code>&#x0d;&#x0a;</code></p>\n\n<p>By the way, note the syntax: It's the ampersand, a pound, the letter <em>x</em>, then the hex value of the character you want, and then finally a semi-colon.</p>\n\n<p>ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.</p>\n"
},
{
"answer_id": 541600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Note that to do this you need to do it in the Text attribute you cannot use the content like</p>\n\n<pre><code><TextBlock>Stuff on line1&#x0a;Stuff on line 2</TextBlock>\n</code></pre>\n"
},
{
"answer_id": 2189267,
"author": "Batgar",
"author_id": 149910,
"author_profile": "https://Stackoverflow.com/users/149910",
"pm_score": 2,
"selected": false,
"text": "<p>Also doesn't work with </p>\n\n<pre><code><TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>\n</code></pre>\n\n<p>No big deal, just needed to use </p>\n\n<pre><code><TextBlock Text=\"Cool &#x0a;Newline trick\" />\n</code></pre>\n\n<p>instead.</p>\n"
},
{
"answer_id": 3977700,
"author": "scrat789",
"author_id": 155622,
"author_profile": "https://Stackoverflow.com/users/155622",
"pm_score": 6,
"selected": false,
"text": "<p>May be you can use the attribute xml:space=\"preserve\" for preserving whitespace in the source XAML</p>\n\n<pre><code><TextBlock xml:space=\"preserve\">\nStuff on line 1\nStuff on line 2\n</TextBlock>\n</code></pre>\n"
},
{
"answer_id": 4081192,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 6,
"selected": false,
"text": "<p>When you need to do it in a string (eg: in your resources) you need to use <code>xml:space=\"preserve\"</code> <em>and</em> the ampersand character codes:</p>\n\n<pre><code><System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">First line&#10;Second line</System:String>\n</code></pre>\n\n<p>Or literal newlines in the text:</p>\n\n<pre><code><System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">First line \nSecond line</System:String>\n</code></pre>\n\n<p>Warning: if you write code like the second example, you have inserted <em>either</em> a newline, or a carriage return and newline, depending on the line endings your operating system and/or text editor use. For instance, if you write that and commit it to git from a linux systems, everything may seem fine -- but if someone clones it to Windows, git will convert your line endings to <code>\\r\\n</code> and depending on what your string is for ... you might break the world.</p>\n\n<p>Just be aware of that when you're preserving whitespace. If you write something like this:</p>\n\n<pre><code><System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">\nFirst line \nSecond line \n</System:String>\n</code></pre>\n\n<p>You've actually added four line breaks, possibly four carriage-returns, and potentially trailing white space that's invisible...</p>\n"
},
{
"answer_id": 5774785,
"author": "Ahmed Ghoneim",
"author_id": 713777,
"author_profile": "https://Stackoverflow.com/users/713777",
"pm_score": 1,
"selected": false,
"text": "<pre><code><TextBox \n Name=\"myTextBox\" \n TextWrapping=\"Wrap\" \n AcceptsReturn=\"True\" \n VerticalScrollBarVisibility=\"Visible\" />\n</code></pre>\n"
},
{
"answer_id": 6592048,
"author": "Neville",
"author_id": 304960,
"author_profile": "https://Stackoverflow.com/users/304960",
"pm_score": 3,
"selected": false,
"text": "<p>I have found this helpful, but ran into some errors when adding it to a \"Content=...\" tag in XAML.</p>\n\n<p>I had multiple lines in the content, and later found out that the content kept white spaces even though I didn't specify that. so to get around that and having it \"ignore\" the whitespace, I implemented such as this.</p>\n\n<pre><code><ToolTip Width=\"200\" Style=\"{StaticResource ToolTip}\" \n Content=\"'Text Line 1' \n &#x0a;&#x0d;'Text Line 2' \n &#x0a;&#x0d;'Text Line 3'\"/>\n</code></pre>\n\n<p>hope this helps someone else.</p>\n\n<p>(The output is has the three text lines with an empty line in between each.)</p>\n"
},
{
"answer_id": 10823343,
"author": "dparker",
"author_id": 245545,
"author_profile": "https://Stackoverflow.com/users/245545",
"pm_score": 3,
"selected": false,
"text": "<p>I realize this is on older question but just wanted to add that </p>\n\n<blockquote>\n <p>Environment.NewLine</p>\n</blockquote>\n\n<p>also works if doing this through code.</p>\n"
},
{
"answer_id": 12300618,
"author": "LPL",
"author_id": 620360,
"author_profile": "https://Stackoverflow.com/users/620360",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe someone prefers</p>\n\n<pre><code><TextBlock Text=\"{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',\n Source={x:Static s:Environment.NewLine}}\" />\n</code></pre>\n\n<p>with <code>xmlns:s=\"clr-namespace:System;assembly=mscorlib\"</code>.</p>\n"
},
{
"answer_id": 17761816,
"author": "S.M.Mousavi",
"author_id": 1074799,
"author_profile": "https://Stackoverflow.com/users/1074799",
"pm_score": 4,
"selected": false,
"text": "<p>You need just removing <code><TextBlock.Text></code> and simply adding your content as following: </p>\n\n<pre><code> <Grid Margin=\"20\">\n <TextBlock TextWrapping=\"Wrap\" TextAlignment=\"Justify\" FontSize=\"17\">\n <Bold FontFamily=\"Segoe UI Light\" FontSize=\"70\">I.R. Iran</Bold><LineBreak/>\n <Span FontSize=\"35\">I</Span>ran or Persia, officially the <Italic>Islamic Republic of Iran</Italic>, \n is a country in Western Asia. The country is bordered on the \n north by Armenia, Azerbaijan and Turkmenistan, with Kazakhstan and Russia \n to the north across the Caspian Sea.<LineBreak/>\n <Span FontSize=\"10\">For more information about Iran see <Hyperlink NavigateUri=\"http://en.WikiPedia.org/wiki/Iran\">WikiPedia</Hyperlink></Span>\n <LineBreak/>\n <LineBreak/>\n <Span FontSize=\"12\">\n <Span>Is this page helpful?</Span>\n <Button Content=\"No\"/>\n <Button Content=\"Yes\"/>\n </Span>\n </TextBlock>\n </Grid>\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/VRqGh.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 21709226,
"author": "Code Maverick",
"author_id": 682480,
"author_profile": "https://Stackoverflow.com/users/682480",
"pm_score": 4,
"selected": false,
"text": "<p>For those that have tried every answer to this question and are <em>still</em> scratching their heads as to why none of them work for you, you might have ran into a form of the issue I ran into.</p>\n\n<p>My <code>TextBlock.Text</code> property was inside of a <code>ToolTipService.ToolTip</code> element and it was databound to a property of an object whose data was being pulled from a SQL stored procedure. Now the data from this particular property within the stored procedure was being pulled from a SQL function.</p>\n\n<p>Since nothing had worked for me, I gave up my search and created the converter class below: </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class NewLineConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n var s = string.Empty;\n\n if (value.IsNotNull())\n {\n s = value.ToString();\n\n if (s.Contains(\"\\\\r\\\\n\"))\n s = s.Replace(\"\\\\r\\\\n\", Environment.NewLine);\n\n if (s.Contains(\"\\\\n\"))\n s = s.Replace(\"\\\\n\", Environment.NewLine);\n\n if (s.Contains(\"&#x0a;&#x0d;\"))\n s = s.Replace(\"&#x0a;&#x0d;\", Environment.NewLine);\n\n if (s.Contains(\"&#x0a;\"))\n s = s.Replace(\"&#x0a;\", Environment.NewLine);\n\n if (s.Contains(\"&#x0d;\"))\n s = s.Replace(\"&#x0d;\", Environment.NewLine);\n\n if (s.Contains(\"&#10;&#13;\"))\n s = s.Replace(\"&#10;&#13;\", Environment.NewLine);\n\n if (s.Contains(\"&#10;\"))\n s = s.Replace(\"&#10;\", Environment.NewLine);\n\n if (s.Contains(\"&#13;\"))\n s = s.Replace(\"&#13;\", Environment.NewLine);\n\n if (s.Contains(\"<br />\"))\n s = s.Replace(\"<br />\", Environment.NewLine);\n\n if (s.Contains(\"<LineBreak />\"))\n s = s.Replace(\"<LineBreak />\", Environment.NewLine);\n }\n\n return s;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n\n<p>I ended up having to use the <code>Enivornment.NewLine</code> method from <a href=\"https://stackoverflow.com/a/10823343/682480\">@dparker's answer</a>. I instructed the converter to look for any possible textual representation of a newline and replace it with <code>Environment.NewLine</code>. </p>\n\n<p><strong>This worked!</strong> </p>\n\n<p><em>However, I was still perplexed as to why none of the other methods worked with databound properties.</em></p>\n\n<p>I left a comment on <a href=\"https://stackoverflow.com/a/183435/682480\">@BobKing's accepted answer</a>:</p>\n\n<blockquote>\n <p>@BobKing - This doesn't seem to work in the ToolTipService.ToolTip when binding to a field that has the line feeds embedded from a SQL sproc.</p>\n</blockquote>\n\n<p>He replied with:</p>\n\n<blockquote>\n <p>@CodeMaverick If you're binding to text with the new lines embedded, they should probably be real char 10 values (or 13's) and not the XML sentinels. This is only if you want to write literal new lines in XAML files.</p>\n</blockquote>\n\n<p><strong>A light bulb went off!</strong></p>\n\n<p>I went into my SQL function, replaced my textual representations of newlines with ...</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CHAR( 13 ) + CHAR( 10 )\n</code></pre>\n\n<p>... removed the converter from my <code>TextBlock.Text</code> binding, and just like that ... <strong><em>it worked!</em></strong></p>\n"
},
{
"answer_id": 47471125,
"author": "user829755",
"author_id": 829755,
"author_profile": "https://Stackoverflow.com/users/829755",
"pm_score": 2,
"selected": false,
"text": "<pre><code><TextBlock>\n Stuff on line1 <LineBreak/>\n Stuff on line2\n</TextBlock>\n</code></pre>\n\n<p>not that it's important to know but what you specify between the TextBlock tags is called inline content and goes into the TextBlock.Inlines property which is a InlineCollection and contains items of type Inline. \nSubclasses of Inline are Run and LineBreak, among others. \nsee <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.inlines\" rel=\"nofollow noreferrer\">TextBlock.Inlines</a></p>\n"
},
{
"answer_id": 62206459,
"author": "Danny Coleiro",
"author_id": 13075915,
"author_profile": "https://Stackoverflow.com/users/13075915",
"pm_score": -1,
"selected": false,
"text": "<p>Code behind solution</p>\n\n<pre><code>private void Button1_Click(object sender, RoutedEventArgs e)\n{\n System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();\n myStringBuilder.Append(\"Orange\").AppendLine();\n myStringBuilder.Append(\"\").AppendLine();\n myStringBuilder.Append(\"Apple\").AppendLine();\n myStringBuilder.Append(\"Banana\").AppendLine();\n myStringBuilder.Append(\"\").AppendLine();\n myStringBuilder.Append(\"Plum\").AppendLine();\n TextBox1.Text = myStringBuilder.ToString();\n}\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] |
How can I add a line break to text when it is being set as an attribute i.e.:
```
<TextBlock Text="Stuff on line1 \n Stuff on line2" />
```
Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following:
```
<TextBlock>
<TextBlock.Text>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock.Text>
<TextBlock/>
```
|
```
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
```
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" `vbCrLf`, then you can use `
`
By the way, note the syntax: It's the ampersand, a pound, the letter *x*, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
|
183,407 |
<p>Code and preview: <img src="https://i.stack.imgur.com/3J6CX.gif" alt="what i have"></p>
<pre><code><html>
<head>
<title>Testing some CSS</title>
<style type="text/css">
.dDay {
font-size:205%
}
.dMon {
font-weight:bold;
font-variant:small-caps;
font-size:130%;
margin-top:-.7em;
}
.detailContainer {
vertical-align:middle;
display:table-cell;
padding:0em 0em 0em 1em;
}
#dContainer {
border:1px solid green;
display:table;
height:3.25em;
}
</style>
<body>
<div id="dContainer">
<div class="dDay">31</div>
<div class="dMon">sep</div>
<div class="detailContainer">Test O.O</div>
</div>
</body>
</html>
</code></pre>
<p>My question is: is it possible to place another date section next to the first one, so it appears like this: <a href="http://img505.imageshack.us/img505/2787/previewsp2.gif" rel="nofollow noreferrer">what i want http://img505.imageshack.us/img505/2787/previewsp2.gif</a>
<hr>
EDIT: strange, I tried floating before I asked the question and it didn't work...thanks everyone :D</p>
|
[
{
"answer_id": 183418,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>use style=\"float:left\" on each DIV (either directly or via a stylesheet)</p>\n"
},
{
"answer_id": 183419,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 1,
"selected": false,
"text": "<p>float:left if you want block elements to sit next to each other.</p>\n"
},
{
"answer_id": 183424,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>Copy dContainer and place the copy immediately after it.</li>\n<li>Change the ID and the new ID to the #dContainer style.</li>\n<li>Add a new CSS block that has just #dContainer (not the new div) and put \"float:left;\" in the block.</li>\n</ol>\n"
},
{
"answer_id": 183425,
"author": "willasaywhat",
"author_id": 12234,
"author_profile": "https://Stackoverflow.com/users/12234",
"pm_score": 3,
"selected": true,
"text": "<pre><code><html>\n<head>\n<title>Testing some CSS</title>\n<style type=\"text/css\">\n.dDay {\n font-size:205%\n}\n.dMon {\n font-weight:bold;\n font-variant:small-caps;\n font-size:130%;\n margin-top:-.7em;\n}\n.detailContainer {\n vertical-align:middle;\n display:table-cell;\n padding:0em 0em 0em 1em;\n}\n#dContainer, #dContainer2 {\n border:1px solid green;\n display:table;\n height:3.25em;\n float: left;\n }\n</style>\n<body>\n<div id=\"dContainer\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n</div>\n<div id=\"dContainer2\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n <div class=\"detailContainer\">Test O.O</div>\n</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 183432,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<pre><code><html>\n<head>\n<title>Testing some CSS</title>\n<style type=\"text/css\">\n.dDay {\n font-size:205%\n}\n.dMon {\n font-weight:bold;\n font-variant:small-caps;\n font-size:130%;\n margin-top:-.7em;\n}\n.dDate {\n display:table-cell;\n}\n.detailContainer {\n vertical-align:middle;\n display:table-cell;\n padding-left:1em;\n}\n#dContainer {\n border:1px solid green;\n display:table;\n height:3.25em;\n}\n</style>\n<body>\n<div id=\"dContainer\">\n <div class=\"dDate\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n </div>\n <div class=\"dDate\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n </div>\n <div class=\"detailContainer\">Test O.O</div>\n</div>\n</body>\n</html>\n</code></pre>\n\n<p>[EDIT] Looking at the other answers:<br>\n- Float is of course the right answer, I just went with the initial logic, actually finishing it (making a real table might be actually the logical final step...)<br>\n- Note: doesn't look nice in IE (6, 7).</p>\n"
},
{
"answer_id": 186432,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "<p>Is there any reason why you can't use <span> tags instead of <div>'s? That way your page would still make sense when read without CSS.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
Code and preview: 
```
<html>
<head>
<title>Testing some CSS</title>
<style type="text/css">
.dDay {
font-size:205%
}
.dMon {
font-weight:bold;
font-variant:small-caps;
font-size:130%;
margin-top:-.7em;
}
.detailContainer {
vertical-align:middle;
display:table-cell;
padding:0em 0em 0em 1em;
}
#dContainer {
border:1px solid green;
display:table;
height:3.25em;
}
</style>
<body>
<div id="dContainer">
<div class="dDay">31</div>
<div class="dMon">sep</div>
<div class="detailContainer">Test O.O</div>
</div>
</body>
</html>
```
My question is: is it possible to place another date section next to the first one, so it appears like this: [what i want http://img505.imageshack.us/img505/2787/previewsp2.gif](http://img505.imageshack.us/img505/2787/previewsp2.gif)
---
EDIT: strange, I tried floating before I asked the question and it didn't work...thanks everyone :D
|
```
<html>
<head>
<title>Testing some CSS</title>
<style type="text/css">
.dDay {
font-size:205%
}
.dMon {
font-weight:bold;
font-variant:small-caps;
font-size:130%;
margin-top:-.7em;
}
.detailContainer {
vertical-align:middle;
display:table-cell;
padding:0em 0em 0em 1em;
}
#dContainer, #dContainer2 {
border:1px solid green;
display:table;
height:3.25em;
float: left;
}
</style>
<body>
<div id="dContainer">
<div class="dDay">31</div>
<div class="dMon">sep</div>
</div>
<div id="dContainer2">
<div class="dDay">31</div>
<div class="dMon">sep</div>
<div class="detailContainer">Test O.O</div>
</div>
</body>
</html>
```
|
183,409 |
<p>Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket. However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.</p>
<p>Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr_reader.read() only ever returns -1.</p>
<pre><code>try{
connection = new Socket("SomeServer", port);
con_out = connection.getOutputStream();
con_in = connection.getInputStream();
PrintWriter out_writer = new PrintWriter(con_out, false);
out_writer.print("GET http://somesite HTTP/1.1\r\n");
out_writer.print("Host: thehost\r\n");
//out_writer.print("Content-Length: 0\r\n");
out_writer.print("\r\n");
out_writer.flush();
// If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.
InputStreamReader isr_reader = new InputStreamReader(con_in);
char[] streamBuf = new char[8192];
int amountRead;
StringBuilder receivedData = new StringBuilder();
while((amountRead = isr_reader.read(streamBuf)) > 0){
receivedData.append(streamBuf, 0, amountRead);
}
// Response is processed here.
if(connection != null && !connection.isClosed()){
//System.out.println("Connection Still Open...");
out_writer.print("GET http://someSite2\r\n");
out_writer.print("Host: somehost\r\n");
out_writer.print("Connection: close\r\n");
out_writer.print("\r\n");
out_writer.flush();
streamBuf = new char[8192];
amountRead = 0;
receivedData.setLength(0);
while((amountRead = isr_reader.read(streamBuf)) > 0 || amountRead < 1){
if (amountRead > 0)
receivedData.append(streamBuf, 0, amountRead);
}
}
// Process response here
}
</code></pre>
<p>Responses to questions:
Yes, I'm receiving chunked responses from the server.
I'm using raw sockets because of an outside restriction.</p>
<p>Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.</p>
<p>So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream <em>isn't</em> closed.</p>
|
[
{
"answer_id": 183457,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you have a <code>Connection: keep-alive</code> in your request. This may be a moot point though.</p>\n\n<p>What kind of response is the server returning? Are you using chunked transfer? If the server doesn't know the size of the response body, it can't provide a <code>Content-Length</code> header and has to close the connection at the end of the response body to indicate to the client that the content has ended. In this case, the keep-alive won't work. If you're generating content on-the-fly with PHP, JSP etc., you can enable output buffering, check the size of the accumulated body, push the <code>Content-Length</code> header and flush the output buffer.</p>\n"
},
{
"answer_id": 183504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Is there a particular reason you're using raw sockets and not Java's URL Connection or <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"nofollow noreferrer\">Commons HTTPClient</a>?</p>\n\n<p>HTTP isn't easy to get right. I know Commons HTTP Client can re-use connections like you're trying to do.</p>\n\n<p>If there isn't a specific reason for you using Sockets this is what I would recommend :)</p>\n"
},
{
"answer_id": 185281,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": true,
"text": "<p>According to your code, the only time you'll even reach the statements dealing with sending the second request is when the server closes the output stream (your input stream) after receiving/responding to the first request.</p>\n\n<p>The reason for that is that your code that is supposed to read only the first response</p>\n\n<pre><code>while((amountRead = isr_reader.read(streamBuf)) > 0) {\n receivedData.append(streamBuf, 0, amountRead);\n}\n</code></pre>\n\n<p>will block until the server closes the output stream (i.e., when <code>read</code> returns <code>-1</code>) or until the read timeout on the socket elapses. In the case of the read timeout, an exception will be thrown and you won't even get to sending the second request.</p>\n\n<p>The problem with HTTP responses is that they don't tell you how many bytes to read from the stream until the end of the response. This is not a big deal for HTTP 1.0 responses, because the server simply closes the connection after the response thus enabling you to obtain the response (status line + headers + body) by simply reading everything until the end of the stream.</p>\n\n<p>With HTTP 1.1 persistent connections you can no longer simply read everything until the end of the stream. You first need to read the status line and the headers, line by line, and then, based on the status code and the headers (such as Content-Length) decide how many bytes to read to obtain the response body (if it's present at all). If you do the above properly, your read operations will complete before the connection is closed or a timeout happens, and you will have read exactly the response the server sent. This will enable you to send the next request and then read the second response in exactly the same manner as the first one.</p>\n\n<p>P.S. Request, request, read might be \"working\" in the sense that your server supports request pipelining and thus, receives and processes both request, and you, as a result, read both responses into one buffer as your \"first\" response.</p>\n\n<p>P.P.S Make sure your <code>PrintWriter</code> is using the <code>US-ASCII</code> encoding. Otherwise, depending on your system encoding, the request line and headers of your HTTP requests might be malformed (wrong encoding).</p>\n"
},
{
"answer_id": 195228,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>Writing your own correct client HTTP/1.1 implementation is nontrivial; historically most people who I've seen attempt it have got it wrong. Their implementation usually ignores the spec and just does what appears to work with one particular test server - in particular, they usually ignore the requirement to be able to handle chunked responses.</p>\n\n<p>Writing your own HTTP client is probably a bad idea, unless you have some VERY strange requirements.</p>\n"
},
{
"answer_id": 3300994,
"author": "Matthieu Peschaud",
"author_id": 398154,
"author_profile": "https://Stackoverflow.com/users/398154",
"pm_score": 2,
"selected": false,
"text": "<p>Writing a simple http/1.1 client respecting the RFC is not such a difficult task.\nTo solve the problem of the blocking i/o access where reading a socket in java, you must use java.nio classes.\nSocketChannels give the possibility to perform a non-blocking i/o access.</p>\n\n<p>This is necessary to send HTTP request on a persistent connection.</p>\n\n<p>Furthermore, nio classes will give better performances.</p>\n\n<p>My stress test give to following results :</p>\n\n<ul>\n<li><p>HTTP/1.0 (java.io) -> HTTP/1.0 (java.nio) = +20% faster</p></li>\n<li><p>HTTP/1.0 (java.io) -> HTTP/1.1 (java.nio with persistent connection) = +110% faster</p></li>\n</ul>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4924/"
] |
Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket. However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.
Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr\_reader.read() only ever returns -1.
```
try{
connection = new Socket("SomeServer", port);
con_out = connection.getOutputStream();
con_in = connection.getInputStream();
PrintWriter out_writer = new PrintWriter(con_out, false);
out_writer.print("GET http://somesite HTTP/1.1\r\n");
out_writer.print("Host: thehost\r\n");
//out_writer.print("Content-Length: 0\r\n");
out_writer.print("\r\n");
out_writer.flush();
// If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.
InputStreamReader isr_reader = new InputStreamReader(con_in);
char[] streamBuf = new char[8192];
int amountRead;
StringBuilder receivedData = new StringBuilder();
while((amountRead = isr_reader.read(streamBuf)) > 0){
receivedData.append(streamBuf, 0, amountRead);
}
// Response is processed here.
if(connection != null && !connection.isClosed()){
//System.out.println("Connection Still Open...");
out_writer.print("GET http://someSite2\r\n");
out_writer.print("Host: somehost\r\n");
out_writer.print("Connection: close\r\n");
out_writer.print("\r\n");
out_writer.flush();
streamBuf = new char[8192];
amountRead = 0;
receivedData.setLength(0);
while((amountRead = isr_reader.read(streamBuf)) > 0 || amountRead < 1){
if (amountRead > 0)
receivedData.append(streamBuf, 0, amountRead);
}
}
// Process response here
}
```
Responses to questions:
Yes, I'm receiving chunked responses from the server.
I'm using raw sockets because of an outside restriction.
Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.
So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream *isn't* closed.
|
According to your code, the only time you'll even reach the statements dealing with sending the second request is when the server closes the output stream (your input stream) after receiving/responding to the first request.
The reason for that is that your code that is supposed to read only the first response
```
while((amountRead = isr_reader.read(streamBuf)) > 0) {
receivedData.append(streamBuf, 0, amountRead);
}
```
will block until the server closes the output stream (i.e., when `read` returns `-1`) or until the read timeout on the socket elapses. In the case of the read timeout, an exception will be thrown and you won't even get to sending the second request.
The problem with HTTP responses is that they don't tell you how many bytes to read from the stream until the end of the response. This is not a big deal for HTTP 1.0 responses, because the server simply closes the connection after the response thus enabling you to obtain the response (status line + headers + body) by simply reading everything until the end of the stream.
With HTTP 1.1 persistent connections you can no longer simply read everything until the end of the stream. You first need to read the status line and the headers, line by line, and then, based on the status code and the headers (such as Content-Length) decide how many bytes to read to obtain the response body (if it's present at all). If you do the above properly, your read operations will complete before the connection is closed or a timeout happens, and you will have read exactly the response the server sent. This will enable you to send the next request and then read the second response in exactly the same manner as the first one.
P.S. Request, request, read might be "working" in the sense that your server supports request pipelining and thus, receives and processes both request, and you, as a result, read both responses into one buffer as your "first" response.
P.P.S Make sure your `PrintWriter` is using the `US-ASCII` encoding. Otherwise, depending on your system encoding, the request line and headers of your HTTP requests might be malformed (wrong encoding).
|
183,415 |
<p>A table row is generated using an asp:Repeater:</p>
<pre><code><asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server">
<itemtemplate>
<tr id="announcementRow" class="announcementItem" runat="server">...</tr>
</itemtemplate>
</asp:repeater>
</code></pre>
<p>Now in the data-bind i want to mark "unread" announcements with a different css class, so that the web-guy can perform whatever styling he wants to differentiate between read and unread announcements:</p>
<pre><code>protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
// get the associated data item
Announcement announcement = (Announcement)e.Item.DataItem;
WebControl row = (WebControl)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
}
</code></pre>
<p>except the cast fails at runtime: </p>
<pre><code>System.InvalidCastException occurred
Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'."
</code></pre>
<p>It turns out that <code>HtmlTableRow</code> has a different parent heirarchy than <code>WebControl</code>:</p>
<pre><code>HtmlTableRow
: HtmlContainerControl
: HtmlControl
: System.Web.UI.Control
</code></pre>
<p>which is ultimately where WebControl comes from</p>
<pre><code>WebControl
: System.Web.UI.Control
</code></pre>
<p>So i changed the code to try to use a System.Web.UI.Control instead:</p>
<pre><code>Control row = (Control)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
</code></pre>
<p>But <code>Control</code> doesn't contain a definition for <code>CssClass</code>:</p>
<pre><code>'System.Web.UI.Control' does not contain a definition for 'CssClass'
</code></pre>
<p>so how do i set the css class name for a <code><TR></code> element during DataBind?</p>
|
[
{
"answer_id": 183438,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 0,
"selected": false,
"text": "<p>Cast it to HtmlTableRow</p>\n\n<pre><code>HtmlTableRow row = (HtmlTableRow)e.Item.FindControl(\"announcementRow\");\n</code></pre>\n"
},
{
"answer_id": 183460,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "<pre><code> HtmlControl htmlRow = (HtmlControl)row; \n htmlRow.Attributes[\"class\"] = htmlRow.Attributes[\"class\"] + \" announcementItemUnread\";\n</code></pre>\n"
},
{
"answer_id": 183463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just bind in the declaration?</p>\n\n<pre><code><tr id=\"announcementRow\" runat=\"server\" class=\"<#% functionToDetermineWhichtoShow(ItemInBoundSetToPass) %>\">...</tr>\n</code></pre>\n"
},
{
"answer_id": 282305,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>HtmlTableRow htmlRow = (HtmlTableRow)row;<br>\n htmlRow.Attributes.Add(\"class\",\"announcementItemUnread\");</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
A table row is generated using an asp:Repeater:
```
<asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server">
<itemtemplate>
<tr id="announcementRow" class="announcementItem" runat="server">...</tr>
</itemtemplate>
</asp:repeater>
```
Now in the data-bind i want to mark "unread" announcements with a different css class, so that the web-guy can perform whatever styling he wants to differentiate between read and unread announcements:
```
protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
// get the associated data item
Announcement announcement = (Announcement)e.Item.DataItem;
WebControl row = (WebControl)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
}
```
except the cast fails at runtime:
```
System.InvalidCastException occurred
Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'."
```
It turns out that `HtmlTableRow` has a different parent heirarchy than `WebControl`:
```
HtmlTableRow
: HtmlContainerControl
: HtmlControl
: System.Web.UI.Control
```
which is ultimately where WebControl comes from
```
WebControl
: System.Web.UI.Control
```
So i changed the code to try to use a System.Web.UI.Control instead:
```
Control row = (Control)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
```
But `Control` doesn't contain a definition for `CssClass`:
```
'System.Web.UI.Control' does not contain a definition for 'CssClass'
```
so how do i set the css class name for a `<TR>` element during DataBind?
|
```
HtmlControl htmlRow = (HtmlControl)row;
htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread";
```
|
183,426 |
<p>By default, cocoa progress bars are slightly fat and I want something a little slimmer, like the progress bars seen in the Finder copy dialog. However, Interface Builder locks the <code>NSProgressIndicator</code> control height to 20 pixels and my programmatic attempts to slim down aren't working, as calls to</p>
<pre><code>[progressBar setControlSize:NSMiniControlSize];
</code></pre>
<p>and</p>
<pre><code>[progressBar setControlSize:NSSmallControlSize];
</code></pre>
<p>in <code>awakeFromNib</code> don't do anything, and the suggestive looking <code>NSProgressIndicatorThickness</code> seen in the header file doesn't seem to plug into any methods that I can see.</p>
<p>What's the trick?</p>
|
[
{
"answer_id": 183890,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 4,
"selected": true,
"text": "<p>Those calls should have worked. In Interface Builder, in the Geometry pane (the one whose icon is a ruler), there is an equivalent control size selector that offers \"Regular\" and \"Small\" sizes.</p>\n"
},
{
"answer_id": 43712182,
"author": "Hofi",
"author_id": 472790,
"author_profile": "https://Stackoverflow.com/users/472790",
"pm_score": 1,
"selected": false,
"text": "<p>in IB</p>\n\n<ol>\n<li>select your NSProgressIndicator control</li>\n<li>in the utilities view select the View Effects inspector</li>\n<li>press + in Content Filters</li>\n<li>select Lanczos Scale Transform filter</li>\n<li>set the appropriate scale value in the Scale row</li>\n<li>set the Aspect Ratio too if you need to change the height only</li>\n</ol>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22147/"
] |
By default, cocoa progress bars are slightly fat and I want something a little slimmer, like the progress bars seen in the Finder copy dialog. However, Interface Builder locks the `NSProgressIndicator` control height to 20 pixels and my programmatic attempts to slim down aren't working, as calls to
```
[progressBar setControlSize:NSMiniControlSize];
```
and
```
[progressBar setControlSize:NSSmallControlSize];
```
in `awakeFromNib` don't do anything, and the suggestive looking `NSProgressIndicatorThickness` seen in the header file doesn't seem to plug into any methods that I can see.
What's the trick?
|
Those calls should have worked. In Interface Builder, in the Geometry pane (the one whose icon is a ruler), there is an equivalent control size selector that offers "Regular" and "Small" sizes.
|
183,428 |
<p>I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:</p>
<pre><code>FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B
</code></pre>
<p>(There's a tab character after <code>delims=</code>)</p>
<p>This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),<br>
it fails with <code>'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName'</code> is not recognized as an internal or external command, operable program or batch file.' Running the "<code>reg query</code>" command alone works fine. <code>Reg.exe</code> is present in <code>C:\Windows\System32</code>. </p>
<p>I was able to work around the problem by changing the code to</p>
<pre><code>REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims= " %%A IN (temp.txt) DO SET MyVariable=%%B
</code></pre>
<p>This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.</p>
<p>Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.</p>
|
[
{
"answer_id": 183465,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>/F</code> switch needs command extensions to be turned on. Usually they are turned on by default, but I'd check that. On XP systems you can turn them on doing something like</p>\n\n<pre><code>cmd /e:on\n</code></pre>\n\n<p>or checking the registry under </p>\n\n<pre><code>HKCU\\Software\\Microsoft\\Command Processor\\EnableExtensions\n</code></pre>\n\n<p>Dunno about Windows Server.</p>\n\n<p>Doing <code>help for</code> and <code>help cmd</code> could provide some hints as well.</p>\n"
},
{
"answer_id": 183545,
"author": "Mark Allen",
"author_id": 5948,
"author_profile": "https://Stackoverflow.com/users/5948",
"pm_score": 1,
"selected": false,
"text": "<p>I would check:</p>\n\n<ol>\n<li>The customer's role on the machine - are they an admin?</li>\n<li>Where is reg.exe on the box - is there more than one copy of copy of reg.exe in the path? </li>\n<li>Is there any locale difference on the customer's machine from the machines where this normally works? </li>\n</ol>\n\n<p>Basically, enumerate everything that differs between this machine and machines where it works as expected. Include service packs, domain membership, etc. </p>\n"
},
{
"answer_id": 185907,
"author": "Eric Tuttleman",
"author_id": 25677,
"author_profile": "https://Stackoverflow.com/users/25677",
"pm_score": 1,
"selected": false,
"text": "<p>Wow, that is odd.</p>\n\n<p>If the same commands work when split into two lines, then I'd guess it has something to do with the way the command gets run in a subshell in the FOR command.</p>\n\n<p>If you were really dying to figure out why it's dying in this particular case, you could run commands like \"SET > envvars.txt\" as the FOR command and compare that with the top shell.</p>\n\n<p>Or maybe start off simple and try running the REG command via CMD /C to see if that does anything?</p>\n\n<p>One quick guess here, what's the values of COMSPEC and SHELL ?</p>\n"
},
{
"answer_id": 8528339,
"author": "Paul Keusemann",
"author_id": 1101000,
"author_profile": "https://Stackoverflow.com/users/1101000",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar situation to this. In my case it was a bad value in COMSPEC. I fixed that and the script started working as expected.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13012/"
] |
I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:
```
FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B
```
(There's a tab character after `delims=`)
This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),
it fails with `'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName'` is not recognized as an internal or external command, operable program or batch file.' Running the "`reg query`" command alone works fine. `Reg.exe` is present in `C:\Windows\System32`.
I was able to work around the problem by changing the code to
```
REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims= " %%A IN (temp.txt) DO SET MyVariable=%%B
```
This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.
Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.
|
I would check:
1. The customer's role on the machine - are they an admin?
2. Where is reg.exe on the box - is there more than one copy of copy of reg.exe in the path?
3. Is there any locale difference on the customer's machine from the machines where this normally works?
Basically, enumerate everything that differs between this machine and machines where it works as expected. Include service packs, domain membership, etc.
|
183,443 |
<p>I have an <em>extremely</em> simple <code>routes.rb</code> in my Rails app:</p>
<pre><code>ActionController::Routing::Routes.draw do |map|
map.resources :tags
end
</code></pre>
<p>Starting up my app with <code>script/server</code> and pointing my browser to <code>localhost:3000/tags/</code> yields:</p>
<h3>ActionController::MethodNotAllowed</h3>
<pre><code>Only get and post requests are allowed.
</code></pre>
<p>...</p>
<p>Starting up my app with <code>script/server webrick</code>, however, solves the problem.</p>
<p><em>Later</em>: in case it matters, I'm running Mongrel 1.1.5 on OSX 10.5.5.</p>
|
[
{
"answer_id": 184146,
"author": "Pete",
"author_id": 13472,
"author_profile": "https://Stackoverflow.com/users/13472",
"pm_score": 0,
"selected": false,
"text": "<p>I have seen this happen with older versions of mongrel, but 1.1.5 is not old. I have also seen some similar problems when the browser double-posts a request to a URL. Is that happening here?</p>\n\n<p>I'd need some more information to be able to help you: What browser are you using? Are you using the firebug plugin on Firefox? What does the server log say about the request, other than the MethodNotAllowed exception?</p>\n"
},
{
"answer_id": 194486,
"author": "danpickett",
"author_id": 21788,
"author_profile": "https://Stackoverflow.com/users/21788",
"pm_score": 0,
"selected": false,
"text": "<p>Somethings to check:</p>\n\n<ul>\n<li>sometimes you need to restart your server to load new routes. </li>\n<li>TagsController exists?</li>\n<li>index action in TagsController exists?</li>\n</ul>\n\n<p>I'm curious to see the stack trace here.</p>\n"
},
{
"answer_id": 198175,
"author": "VP.",
"author_id": 18642,
"author_profile": "https://Stackoverflow.com/users/18642",
"pm_score": 0,
"selected": false,
"text": "<p>Did you check your codes for example related with form_for, to check if has any typo? When you run rake routes, everything is fine? I saw this problem before and it was related with a typo in the form_for parameters.</p>\n\n<p>Did you update your mongrel? gem update mongrel?</p>\n\n<p>Did you check your project log? log*.log?</p>\n\n<p>Regards,</p>\n\n<p>Victor</p>\n"
},
{
"answer_id": 207840,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Check your generated routes for problems with \"rake routes | grep tag\"</li>\n<li>Check the actual method that is being called, and the verb it is being called with by tail -f log/development.log</li>\n</ol>\n\n<p>This should bring up any obvious problems.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
I have an *extremely* simple `routes.rb` in my Rails app:
```
ActionController::Routing::Routes.draw do |map|
map.resources :tags
end
```
Starting up my app with `script/server` and pointing my browser to `localhost:3000/tags/` yields:
### ActionController::MethodNotAllowed
```
Only get and post requests are allowed.
```
...
Starting up my app with `script/server webrick`, however, solves the problem.
*Later*: in case it matters, I'm running Mongrel 1.1.5 on OSX 10.5.5.
|
1. Check your generated routes for problems with "rake routes | grep tag"
2. Check the actual method that is being called, and the verb it is being called with by tail -f log/development.log
This should bring up any obvious problems.
|
183,446 |
<p>How do I fix that error once and for all? I just want to be able to do unions in MySQL. </p>
<p>(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)</p>
|
[
{
"answer_id": 183624,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 4,
"selected": true,
"text": "<p>Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do</p>\n\n<pre><code>select column1 from tableWithProperCollation\nunion all\nselect column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation\n</code></pre>\n\n<p>Of course SQL_Latin1_General_CP1_CI_AS is just an example of collation you want to \"convert\" to</p>\n"
},
{
"answer_id": 183927,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks Kristof. In this case it was being caused by selecting a literal in the first select, and not from any different table collations.</p>\n\n<p>Ironically I got it working by following this <a href=\"http://www.answermysearches.com/mysql-fixing-illegal-mix-of-collations-message/352/\" rel=\"nofollow noreferrer\">old blog post</a> I made for that issue.</p>\n"
},
{
"answer_id": 26258216,
"author": "KevinR",
"author_id": 3276221,
"author_profile": "https://Stackoverflow.com/users/3276221",
"pm_score": 1,
"selected": false,
"text": "<p>A fix I found that seems to be an easy fix is to alter the entire database that's giving you problems. I'm thinking this might not be the best way to do it, but it works for me and it's easy. I rune this command in MySQL:</p>\n\n<pre><code>ALTER DATABASE databasename COLLATE utf8_unicode_ci;\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
How do I fix that error once and for all? I just want to be able to do unions in MySQL.
(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)
|
Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do
```
select column1 from tableWithProperCollation
union all
select column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation
```
Of course SQL\_Latin1\_General\_CP1\_CI\_AS is just an example of collation you want to "convert" to
|
183,459 |
<p>I have an Asp.Net 2.0 (VB.Net) app and I'm trying to export a Control (ASCX) to another project. I need to know what other files that the Control needs in order to work. </p>
<p>Is there any way - using VS.Net 2005 or an external app - to recursively trace the dependencies of a page or control in a solution?</p>
<p>For example, for this file: <code>~/Controls/SomeControl.ascx</code>, I'd like to get the following list of files that it depends on to run:</p>
<pre><code>~/Controls/SomeControl.ascx
~/Controls/SomeControl.ascx.vb
~/App_Code/SomeClass.vb
~/App_Code/AnotherClass.vb
~/App_WebReferences/com/example/SomeWebService/SomeWebService.disco
~/App_WebReferences/com/example/SomeWebService/SomeWebService.discomap
~/App_WebReferences/com/example/SomeWebService/SomeWebService.wsdl
~/App_Code/AnotherClass.vb
</code></pre>
|
[
{
"answer_id": 869346,
"author": "Jon Ownbey",
"author_id": 79206,
"author_profile": "https://Stackoverflow.com/users/79206",
"pm_score": 3,
"selected": true,
"text": "<p>I've used the <a href=\"http://msdn.microsoft.com/en-us/library/ms229864(VS.80).aspx\" rel=\"nofollow noreferrer\">Assembly Binding Log Viewer (Fuslogvw.exe)</a> or maybe ProcMon...</p>\n\n<p>One of my coworkers suggested this app called Dependency Auditor. I haven't used it though and am not vouching for it necessarily. </p>\n"
},
{
"answer_id": 872574,
"author": "Richard Anthony Freeman-Hein",
"author_id": 13131,
"author_profile": "https://Stackoverflow.com/users/13131",
"pm_score": 2,
"selected": false,
"text": "<p>I've used <a href=\"http://www.automatedqa.com/products/aqtime/\" rel=\"nofollow noreferrer\">AutomatedQA's AQTime</a> do this kind of thing. You can view sequence diagrams, call graphs, etc.... From there you can see which assemblies and files are being used.</p>\n\n<p>They have a free trial that will give you plenty of time to do what you need to do.</p>\n"
},
{
"answer_id": 874251,
"author": "Oorang",
"author_id": 102270,
"author_profile": "https://Stackoverflow.com/users/102270",
"pm_score": 2,
"selected": false,
"text": "<p>MZ Tools 6.0 integrates with Visual Studio and has a \"get callers\" type feature.\n<a href=\"http://www.mztools.com/v6/mztools6.aspx\" rel=\"nofollow noreferrer\">http://www.mztools.com/v6/mztools6.aspx</a></p>\n"
},
{
"answer_id": 882851,
"author": "Scott Schulthess",
"author_id": 68393,
"author_profile": "https://Stackoverflow.com/users/68393",
"pm_score": -1,
"selected": false,
"text": "<p>I would just move the ascx control to a new project and debug stuff one by one. Then, I would compile that into a dll and use it in the different project.</p>\n"
},
{
"answer_id": 892955,
"author": "andrewbadera",
"author_id": 25952,
"author_profile": "https://Stackoverflow.com/users/25952",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <a href=\"http://www.ndepend.com/\" rel=\"nofollow noreferrer\">NDepend</a>? There's a <a href=\"http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph\" rel=\"nofollow noreferrer\">plugin for Reflector</a> as well.</p>\n"
},
{
"answer_id": 896910,
"author": "Scott Hanselman",
"author_id": 6380,
"author_profile": "https://Stackoverflow.com/users/6380",
"pm_score": 2,
"selected": false,
"text": "<p>Nope. There's no way to do that.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
I have an Asp.Net 2.0 (VB.Net) app and I'm trying to export a Control (ASCX) to another project. I need to know what other files that the Control needs in order to work.
Is there any way - using VS.Net 2005 or an external app - to recursively trace the dependencies of a page or control in a solution?
For example, for this file: `~/Controls/SomeControl.ascx`, I'd like to get the following list of files that it depends on to run:
```
~/Controls/SomeControl.ascx
~/Controls/SomeControl.ascx.vb
~/App_Code/SomeClass.vb
~/App_Code/AnotherClass.vb
~/App_WebReferences/com/example/SomeWebService/SomeWebService.disco
~/App_WebReferences/com/example/SomeWebService/SomeWebService.discomap
~/App_WebReferences/com/example/SomeWebService/SomeWebService.wsdl
~/App_Code/AnotherClass.vb
```
|
I've used the [Assembly Binding Log Viewer (Fuslogvw.exe)](http://msdn.microsoft.com/en-us/library/ms229864(VS.80).aspx) or maybe ProcMon...
One of my coworkers suggested this app called Dependency Auditor. I haven't used it though and am not vouching for it necessarily.
|
183,479 |
<p>I have a class that creates several IDisposable objects, all of these objects are then passed to another 'manager' class in a 3rd party library. As I need some of the objects in later calls I kept a local field reference to the created objects so that I could access them at a later time. When I ran FxCop on the class it said that I should implement IDisposable, due to the disposable objects that I kept a reference to. My questions are:</p>
<ol>
<li>Should I implement IDisposable for my class? (or is it the manager's responsibility?)</li>
<li>If so, should I only dispose the objects I kept a reference to? or should I find a way to dispose all objects I created.</li>
</ol>
<h3>My code:</h3>
<pre><code>public class MyClass
{
ClassThatIsDisposable aReference;
}
public MyClass(ManagerClass manager)
{
ClassThatIsDisposable transient=new ClassThatIsDisposable();
manager.Add(transient);
aReference=new ClassThatIsDisposable();
manager.Add(aReference);
}
public void LaterCall()
{
areference.Method();
}
</code></pre>
|
[
{
"answer_id": 183517,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>If you create any disposable objects, you should either dispose them yourself or make sure you're handing them off to another class which will take responsibility for that.</p>\n\n<p>In this case, I'd say it really depends on what the manager class is going to do. If that guarantees that it will dispose of anything that is added to it, you're okay. It does look like a somewhat odd design pattern though - I can't say I've used anything similar myself. That's not to say it's necessarily wrong/bad, but it would at least be worth taking another look to see if there's any way of avoiding this slight confusion of ownership.</p>\n\n<p>Bear in mind that if the manager disposes the object you're holding a reference to, it's likely to be unusable afterwards.</p>\n"
},
{
"answer_id": 183522,
"author": "Sean",
"author_id": 26095,
"author_profile": "https://Stackoverflow.com/users/26095",
"pm_score": 3,
"selected": true,
"text": "<p>The class that owns the object is the one that should dispose of them... It sounds like your manager is the owner, so he should dispose of the object.</p>\n\n<p>If you're trying to avoid the FXCop warning then one option is to have MyClass request the disposable object from the manager each time is needs to use it. This way you won't have a member variable holding a reference to it. You could do this my having the Add() method return akey for the object that has been added and then use this key to retrieve the object from the manager when you need to use it.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11921/"
] |
I have a class that creates several IDisposable objects, all of these objects are then passed to another 'manager' class in a 3rd party library. As I need some of the objects in later calls I kept a local field reference to the created objects so that I could access them at a later time. When I ran FxCop on the class it said that I should implement IDisposable, due to the disposable objects that I kept a reference to. My questions are:
1. Should I implement IDisposable for my class? (or is it the manager's responsibility?)
2. If so, should I only dispose the objects I kept a reference to? or should I find a way to dispose all objects I created.
### My code:
```
public class MyClass
{
ClassThatIsDisposable aReference;
}
public MyClass(ManagerClass manager)
{
ClassThatIsDisposable transient=new ClassThatIsDisposable();
manager.Add(transient);
aReference=new ClassThatIsDisposable();
manager.Add(aReference);
}
public void LaterCall()
{
areference.Method();
}
```
|
The class that owns the object is the one that should dispose of them... It sounds like your manager is the owner, so he should dispose of the object.
If you're trying to avoid the FXCop warning then one option is to have MyClass request the disposable object from the manager each time is needs to use it. This way you won't have a member variable holding a reference to it. You could do this my having the Add() method return akey for the object that has been added and then use this key to retrieve the object from the manager when you need to use it.
|
183,480 |
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?
Thanks!</p>
<pre><code>def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.isfile(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
</code></pre>
<p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
|
[
{
"answer_id": 183492,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>If you want readable names this looks like a good solution.<br>\nThere are routines to return unique file names for eg. temp files but they produce long random looking names.</p>\n"
},
{
"answer_id": 183528,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Two small changes...</p>\n\n<pre><code>base_name, ext = os.path.splitext(file_name) \n</code></pre>\n\n<p>You get two results with distinct meaning, give them distinct names.</p>\n\n<pre><code>file_name = \"%s_%d%s\" % (base_name, str(counter), ext)\n</code></pre>\n\n<p>It isn't faster or significantly shorter. But, when you want to change your file name pattern, the pattern is on one place, and slightly easier to work with.</p>\n"
},
{
"answer_id": 183533,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, this is a good strategy for readable but unique filenames.</p>\n\n<p><strong>One important change</strong>: You should replace <code>os.path.isfile</code> with <code>os.path.lexists</code>! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since <code>isfile</code> only checks for files and not directories. <code>lexists</code> checks for directories, symlinks, etc... basically if there's any reason that filename could not be created.</p>\n\n<p>EDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions.</p>\n"
},
{
"answer_id": 183582,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": true,
"text": "<p>One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.</p>\n\n<p>To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):</p>\n\n<pre><code>def unique_file(file_name):\n counter = 1\n file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')\n while 1:\n try:\n fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)\n return os.fdopen(fd), file_name\n except OSError:\n pass\n file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]\n counter += 1\n</code></pre>\n\n<p><strong>[Edit]</strong> Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):</p>\n\n<pre><code>def unique_file(file_name):\n dirname, filename = os.path.split(file_name)\n prefix, suffix = os.path.splitext(filename)\n\n fd, filename = tempfile.mkstemp(suffix, prefix+\"_\", dirname)\n return os.fdopen(fd), filename\n\n>>> f, filename=unique_file('/home/some_dir/foo.txt')\n>>> print filename\n/home/some_dir/foo_z8f_2Z.txt\n</code></pre>\n\n<p>The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first.\nYou may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.</p>\n"
},
{
"answer_id": 185558,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 1,
"selected": false,
"text": "<p>if you don't care about readability, uuid.uuid4() is your friend.</p>\n\n<pre><code>import uuid\n\ndef unique_filename(prefix=None, suffix=None):\n fn = []\n if prefix: fn.extend([prefix, '-'])\n fn.append(str(uuid.uuid4()))\n if suffix: fn.extend(['.', suffix.lstrip('.')])\n return ''.join(fn)\n</code></pre>\n"
},
{
"answer_id": 691029,
"author": "Manish",
"author_id": 50481,
"author_profile": "https://Stackoverflow.com/users/50481",
"pm_score": 0,
"selected": false,
"text": "<p>How about </p>\n\n<pre><code>def ensure_unique_filename(orig_file_path): \n from time import time\n import os\n\n if os.path.lexists(orig_file_path):\n name, ext = os.path.splitext(orig_file_path)\n orig_file_path = name + str(time()).replace('.', '') + ext\n\n return orig_file_path\n</code></pre>\n\n<p>time() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26196/"
] |
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?
Thanks!
```
def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.isfile(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
```
I really *do* require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.
|
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.
To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O\_CREAT and os.O\_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):
```
def unique_file(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while 1:
try:
fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)
return os.fdopen(fd), file_name
except OSError:
pass
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
```
**[Edit]** Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):
```
def unique_file(file_name):
dirname, filename = os.path.split(file_name)
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
return os.fdopen(fd), filename
>>> f, filename=unique_file('/home/some_dir/foo.txt')
>>> print filename
/home/some_dir/foo_z8f_2Z.txt
```
The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some\_dir/foo.txt) first.
You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.
|
183,484 |
<p>What is an efficient way to shrink a two dimensional array to a smaller size in C#?</p>
<p>For example:</p>
<pre><code>var bigArray = new object[100, 100];
var smallArray = new object[10, 10];
bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;
startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;
smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
</code></pre>
<p>How will you write SomeShrinkingMethod() ?</p>
<p>Thanks!</p>
<p>EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.</p>
|
[
{
"answer_id": 183516,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.</p>\n\n<p>The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.</p>\n\n<h3>Edit:</h3>\n\n<p>In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.</p>\n"
},
{
"answer_id": 183550,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?</p>\n"
},
{
"answer_id": 4647614,
"author": "winwaed",
"author_id": 481927,
"author_profile": "https://Stackoverflow.com/users/481927",
"pm_score": 0,
"selected": false,
"text": "<p>Yes the best method is almost certainly to loop over each cell, although it might be possible to copy a sequence of each 'row'. The method would need to know lower indices of the square to be copied from the source square, and the size (which might be implicit in the destination square definition).</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18170/"
] |
What is an efficient way to shrink a two dimensional array to a smaller size in C#?
For example:
```
var bigArray = new object[100, 100];
var smallArray = new object[10, 10];
bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;
startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;
smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
```
How will you write SomeShrinkingMethod() ?
Thanks!
EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.
|
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
### Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.
|
183,485 |
<p>I need to convert the punycode <code>NIATO-OTABD</code> to <code>nñiñatoñ</code>.</p>
<p>I found <a href="http://0xcc.net/jsescape/" rel="noreferrer">a text converter in JavaScript</a> the other day, but the punycode conversion doesn't work if there's a dash in the middle.</p>
<p>Any suggestion to fix the "dash" issue?</p>
|
[
{
"answer_id": 301287,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 7,
"selected": true,
"text": "<p>I took the time to create the punycode below. It it based on the C code in RFC 3492. To use it with domain names you have to remove/add <code>xn--</code> from/to the input/output to/from decode/encode.</p>\n<p>The <code>utf16-class</code> is necessary to convert from JavaScripts internal character representation to unicode and back.</p>\n<p>There are also <code>ToASCII</code> and <code>ToUnicode</code> functions to make it easier to convert between puny-coded IDN and ASCII.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//Javascript Punycode converter derived from example in RFC3492.\n//This implementation is created by [email protected] and released into public domain\nvar punycode = new function Punycode() {\n // This object converts to and from puny-code used in IDN\n //\n // punycode.ToASCII ( domain )\n // \n // Returns a puny coded representation of \"domain\".\n // It only converts the part of the domain name that\n // has non ASCII characters. I.e. it dosent matter if\n // you call it with a domain that already is in ASCII.\n //\n // punycode.ToUnicode (domain)\n //\n // Converts a puny-coded domain name to unicode.\n // It only converts the puny-coded parts of the domain name.\n // I.e. it dosent matter if you call it on a string\n // that already has been converted to unicode.\n //\n //\n this.utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode:function(input){\n var output = [], i=0, len=input.length,value,extra;\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xF800) === 0xD800) {\n extra = input.charCodeAt(i++);\n if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {\n throw new RangeError(\"UTF-16(decode): Illegal UTF-16 sequence\");\n }\n value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode:function(input){\n var output = [], i=0, len=input.length,value;\n while (i < len) {\n value = input[i++];\n if ( (value & 0xF800) === 0xD800 ) {\n throw new RangeError(\"UTF-16(encode): Illegal UTF-16 value\");\n }\n if (value > 0xFFFF) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));\n value = 0xDC00 | (value & 0x3FF);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join(\"\");\n }\n }\n\n //Default parameters\n var initial_n = 0x80;\n var initial_bias = 72;\n var delimiter = \"\\x2D\";\n var base = 36;\n var damp = 700;\n var tmin=1;\n var tmax=26;\n var skew=38;\n var maxint = 0x7FFFFFFF;\n\n // decode_digit(cp) returns the numeric value of a basic code \n // point (for use in representing integers) in the range 0 to\n // base-1, or base if cp is does not represent a value.\n\n function decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n }\n\n // encode_digit(d,flag) returns the basic code point whose value\n // (when used for representing integers) is d, which needs to be in\n // the range 0 to base-1. The lowercase form is used unless flag is\n // nonzero, in which case the uppercase form is used. The behavior\n // is undefined if flag is nonzero and digit d has no uppercase form. \n\n function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9\n }\n //** Bias adaptation function **\n function adapt(delta, numpoints, firsttime ) {\n var k;\n delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {\n delta = Math.floor(delta / ( base - tmin ));\n }\n return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));\n }\n\n // encode_basic(bcp,flag) forces a basic code point to lowercase if flag is zero,\n // uppercase if flag is nonzero, and returns the resulting code point.\n // The code point is unchanged if it is caseless.\n // The behavior is undefined if bcp is not a basic code point.\n\n function encode_basic(bcp, flag) {\n bcp -= (bcp - 97 < 26) << 5;\n return bcp + ((!flag && (bcp - 65 < 26)) << 5);\n }\n\n // Main decode\n this.decode=function(input,preserveCase) {\n // Dont use utf16\n var output=[];\n var case_flags=[];\n var input_length = input.length;\n\n var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;\n\n // Initialize the state: \n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code \n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if(preserveCase) case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);\n if ( input.charCodeAt(j) >= 0x80) {\n throw new RangeError(\"Illegal input >= 0x80\");\n }\n output.push( input.charCodeAt(j) );\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise. \n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {\n\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting \n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError (\"punycode_bad_input(1)\");\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError(\"punycode_bad_input(2)\");\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError (\"punycode_overflow(1)\");\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) { break; }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError(\"punycode_overflow(2)\");\n }\n w *= (base - t);\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now: \n if ( Math.floor(i / out) > maxint - n) {\n throw RangeError(\"punycode_overflow(3)\");\n }\n n += Math.floor( i / out ) ;\n i %= out;\n\n // Insert n at position i of the output: \n // Case of last character determines uppercase flag: \n if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);\n }\n }\n }\n return this.utf16.encode(output);\n };\n\n //** Main encode function **\n\n this.encode = function (input,preserveCase) {\n //** Bias adaptation function **\n\n var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;\n\n if (preserveCase) {\n // Preserve case, step1 of 2: Get a list of the unaltered string\n case_flags = this.utf16.decode(input);\n }\n // Converts the input in UTF-16 to Unicode\n input = this.utf16.decode(input.toLowerCase());\n\n var input_length = input.length; // Cache the length\n\n if (preserveCase) {\n // Preserve case, step2 of 2: Modify the list to true/false\n for (j=0; j < input_length; j++) {\n case_flags[j] = input[j] != case_flags[j];\n }\n }\n\n var output=[];\n\n\n // Initialize the state: \n n = initial_n;\n delta = 0;\n bias = initial_bias;\n\n // Handle the basic code points: \n for (j = 0; j < input_length; ++j) {\n if ( input[j] < 0x80) {\n output.push(\n String.fromCharCode(\n case_flags ? encode_basic(input[j], case_flags[j]) : input[j]\n )\n );\n }\n }\n\n h = b = output.length;\n\n // h is the number of code points that have been handled, b is the\n // number of basic code points \n\n if (b > 0) output.push(delimiter);\n\n // Main encoding loop: \n //\n while (h < input_length) {\n // All non-basic code points < n have been\n // handled already. Find the next larger one: \n\n for (m = maxint, j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv >= n && ijv < m) m = ijv;\n }\n\n // Increase delta enough to advance the decoder's\n // <n,i> state to <m,0>, but guard against overflow: \n\n if (m - n > Math.floor((maxint - delta) / (h + 1))) {\n throw RangeError(\"punycode_overflow (1)\");\n }\n delta += (m - n) * (h + 1);\n n = m;\n\n for (j = 0; j < input_length; ++j) {\n ijv = input[j];\n\n if (ijv < n ) {\n if (++delta > maxint) return Error(\"punycode_overflow(2)\");\n }\n\n if (ijv == n) {\n // Represent delta as a generalized variable-length integer: \n for (q = delta, k = base; ; k += base) {\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (q < t) break;\n output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );\n q = Math.floor( (q - t) / (base - t) );\n }\n output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));\n bias = adapt(delta, h + 1, h == b);\n delta = 0;\n ++h;\n }\n }\n\n ++delta, ++n;\n }\n return output.join(\"\");\n }\n\n this.ToASCII = function ( domain ) {\n var domain_array = domain.split(\".\");\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/[^A-Za-z0-9-]/) ?\n \"xn--\" + punycode.encode(s) :\n s\n );\n }\n return out.join(\".\");\n }\n this.ToUnicode = function ( domain ) {\n var domain_array = domain.split(\".\");\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/^xn--/) ?\n punycode.decode(s.slice(4)) :\n s\n );\n }\n return out.join(\".\");\n }\n}();\n\n\n// Example of usage:\ndomain.oninput = function() {\n var input = domain.value\n var ascii = punycode.ToASCII(input)\n var display = punycode.ToUnicode(ascii)\n domain_ascii.value = ascii\n domain_display.value = display\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Try with your own data</p>\n\n<label>\n <div>Input domain</div>\n <div><input id=\"domain\" type=\"text\"></div>\n</label>\n<div>Ascii: <output id=\"domain_ascii\"></div>\n<div>Display: <output id=\"domain_display\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Licence:</strong></p>\n<p>From RFC3492:</p>\n<blockquote>\n<p>Disclaimer and license</p>\n<p>Regarding this entire document or any portion of it (including the pseudocode and C code), the author makes no guarantees and is not responsible for any damage resulting from its use. The author grants irrevocable permission to anyone to use, modify, and distribute it in any way that does not diminish the rights of anyone else to use, modify, and distribute it, provided that redistributed derivative works do not contain misleading author or version information. Derivative works need not be licensed under similar terms.</p>\n</blockquote>\n<p>I put my work in this punycode and utf16 in the public domain. It would be nice to get an email telling me in what project you use it.</p>\n<p><strong>The scope of the code</strong></p>\n<p><em>Each TLD has rules for which code points are allowed. The scope of the code below is to encode and decode a string between punycode and the internal encoding used by javascript regardes of those rules.\nDepending on your use case, you may need to filter the string.\nFor example, 0xFE0F: Variation Selector-16, an invisible code point that specifies that the previous character should be displayed with emoji presentation.\nIf you search for "allowed code points in IDN" you should find several projects that can help you filter the string.</em></p>\n"
},
{
"answer_id": 71605995,
"author": "MyChickenNinja",
"author_id": 1252009,
"author_profile": "https://Stackoverflow.com/users/1252009",
"pm_score": 1,
"selected": false,
"text": "<p>Some's answer is absolutely awesome! Worked exactly how I was hoping for domains. However, I needed it to work for emails too. So I used Some's code and added a check for emails, then, with a little more logic, got it working for emails.\nI am not a JavaScript dev by any streach of the imagination, but I can make stuff work when I need to.\nThis version will take domains or emails and convert to and from punycode.\n(I also added semi-colons and brackets (for IFs). I know, not always necessary but it does make the code a little easier to read and also gets rid of the dammed red squigglies...) @some, I hope you approve =)</p>\n<pre><code>var punycode = new function Punycode() {\n// punycode.ToASCII ( domain )\n// punycode.ToUnicode (domain)\nthis.utf16 = {\n decode:function(input){\n var output = [], i=0, len=input.length,value,extra;\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xF800) === 0xD800) {\n extra = input.charCodeAt(i++);\n if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {\n throw new RangeError("UTF-16(decode): Illegal UTF-16 sequence");\n }\n value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode:function(input){\n var output = [], i=0, len=input.length,value;\n while (i < len) {\n value = input[i++];\n if ( (value & 0xF800) === 0xD800 ) {\n throw new RangeError("UTF-16(encode): Illegal UTF-16 value");\n }\n if (value > 0xFFFF) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));\n value = 0xDC00 | (value & 0x3FF);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join("");\n }\n}\nvar initial_n = 0x80;\nvar initial_bias = 72;\nvar delimiter = "\\x2D";\nvar base = 36;\nvar damp = 700;\nvar tmin=1;\nvar tmax=26;\nvar skew=38;\nvar maxint = 0x7FFFFFFF;\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\nfunction encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag !== 0) << 5);\n}\nfunction adapt(delta, numpoints, firsttime ) {\n var k;\n delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);\n delta += Math.floor(delta / numpoints);\n for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {\n delta = Math.floor(delta / ( base - tmin ));\n }\n return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));\n}\nfunction encode_basic(bcp, flag) {\n bcp -= (bcp - 97 < 26) << 5;\n return bcp + ((!flag && (bcp - 65 < 26)) << 5);\n}\nthis.decode=function(input,preserveCase) {\n var output=[];\n var case_flags=[];\n var input_length = input.length;\n var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;\n n = initial_n;\n i = 0;\n bias = initial_bias;\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) {basic = 0;}\n for (j = 0; j < basic; ++j) {\n if(preserveCase) {case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);}\n if ( input.charCodeAt(j) >= 0x80) {\n throw new RangeError("Illegal input >= 0x80");\n }\n output.push( input.charCodeAt(j) );\n }\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError ("punycode_bad_input(1)");\n }\n digit = decode_digit(input.charCodeAt(ic++));\n if (digit >= base) {\n throw RangeError("punycode_bad_input(2)");\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError ("punycode_overflow(1)");\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) { break; }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError("punycode_overflow(2)");\n }\n w *= (base - t);\n }\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n if ( Math.floor(i / out) > maxint - n) {\n throw RangeError("punycode_overflow(3)");\n }\n n += Math.floor( i / out ) ;\n i %= out;\n if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);\n }\n }\n }\n return this.utf16.encode(output);\n};\nthis.encode = function (input,preserveCase) {\n var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;\n if (preserveCase) {\n case_flags = this.utf16.decode(input);\n }\n input = this.utf16.decode(input.toLowerCase());\n var input_length = input.length; // Cache the length\n if (preserveCase) {\n for (j=0; j < input_length; j++) {\n case_flags[j] = input[j] !== case_flags[j];\n }\n }\n var output=[];\n n = initial_n;\n delta = 0;\n bias = initial_bias;\n for (j = 0; j < input_length; ++j) {\n if ( input[j] < 0x80) {\n output.push(\n String.fromCharCode(\n case_flags ? encode_basic(input[j], case_flags[j]) : input[j]\n )\n );\n }\n }\n h = b = output.length;\n if (b > 0) {output.push(delimiter);}\n while (h < input_length) {\n for (m = maxint, j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv >= n && ijv < m) {m = ijv;}\n }\n if (m - n > Math.floor((maxint - delta) / (h + 1))) {\n throw RangeError("punycode_overflow (1)");\n }\n delta += (m - n) * (h + 1);\n n = m;\n for (j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv < n ) {\n if (++delta > maxint) {return Error("punycode_overflow(2)");}\n }\n if (ijv === n) {\n for (q = delta, k = base; ; k += base) {\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (q < t) {break;}\n output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );\n q = Math.floor( (q - t) / (base - t) );\n }\n output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));\n bias = adapt(delta, h + 1, h === b);\n delta = 0;\n ++h;\n }\n }\n ++delta, ++n;\n }\n return output.join("");\n};\nfunction formatArray(arr){\n var outStr = "";\n if (arr.length === 1) {\n outStr = arr[0];\n } else if (arr.length === 2) {\n outStr = arr.join('.');\n } else if (arr.length > 2) {\n outStr = arr.slice(0, -1).join('@') + '.' + arr.slice(-1);\n }\n return outStr;\n}\n this.ToASCII = function ( domain ) {\n try {\n var domain_array;\n if (domain.includes("@")) {\n domain_array = domain.split("@").join(".").split(".");\n }\n else {\n domain_array = domain.split(".");\n }\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/[^A-Za-z0-9-]/) ?\n "xn--" + punycode.encode(s) :\n s\n );\n }\n return formatArray(out)\n } catch (error) {\n return (domain)\n }\n };\n this.ToUnicode = function ( domain ) {\n try {\n var domain_array;\n if (domain.includes("@")) {\n domain_array = domain.split("@").join(".").split(".");\n }\n else {\n domain_array = domain.split(".");\n }\n var out = [];\n for (var i = 0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n\n out.push(\n s.match(/^xn--/) ?\n punycode.decode(s.slice(4)) :\n s\n );\n\n }\n return formatArray(out)\n } catch (error) {\n return (domain)\n }\n };};\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23520/"
] |
I need to convert the punycode `NIATO-OTABD` to `nñiñatoñ`.
I found [a text converter in JavaScript](http://0xcc.net/jsescape/) the other day, but the punycode conversion doesn't work if there's a dash in the middle.
Any suggestion to fix the "dash" issue?
|
I took the time to create the punycode below. It it based on the C code in RFC 3492. To use it with domain names you have to remove/add `xn--` from/to the input/output to/from decode/encode.
The `utf16-class` is necessary to convert from JavaScripts internal character representation to unicode and back.
There are also `ToASCII` and `ToUnicode` functions to make it easier to convert between puny-coded IDN and ASCII.
```js
//Javascript Punycode converter derived from example in RFC3492.
//This implementation is created by [email protected] and released into public domain
var punycode = new function Punycode() {
// This object converts to and from puny-code used in IDN
//
// punycode.ToASCII ( domain )
//
// Returns a puny coded representation of "domain".
// It only converts the part of the domain name that
// has non ASCII characters. I.e. it dosent matter if
// you call it with a domain that already is in ASCII.
//
// punycode.ToUnicode (domain)
//
// Converts a puny-coded domain name to unicode.
// It only converts the puny-coded parts of the domain name.
// I.e. it dosent matter if you call it on a string
// that already has been converted to unicode.
//
//
this.utf16 = {
// The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.
decode:function(input){
var output = [], i=0, len=input.length,value,extra;
while (i < len) {
value = input.charCodeAt(i++);
if ((value & 0xF800) === 0xD800) {
extra = input.charCodeAt(i++);
if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {
throw new RangeError("UTF-16(decode): Illegal UTF-16 sequence");
}
value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
}
output.push(value);
}
return output;
},
encode:function(input){
var output = [], i=0, len=input.length,value;
while (i < len) {
value = input[i++];
if ( (value & 0xF800) === 0xD800 ) {
throw new RangeError("UTF-16(encode): Illegal UTF-16 value");
}
if (value > 0xFFFF) {
value -= 0x10000;
output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));
value = 0xDC00 | (value & 0x3FF);
}
output.push(String.fromCharCode(value));
}
return output.join("");
}
}
//Default parameters
var initial_n = 0x80;
var initial_bias = 72;
var delimiter = "\x2D";
var base = 36;
var damp = 700;
var tmin=1;
var tmax=26;
var skew=38;
var maxint = 0x7FFFFFFF;
// decode_digit(cp) returns the numeric value of a basic code
// point (for use in representing integers) in the range 0 to
// base-1, or base if cp is does not represent a value.
function decode_digit(cp) {
return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;
}
// encode_digit(d,flag) returns the basic code point whose value
// (when used for representing integers) is d, which needs to be in
// the range 0 to base-1. The lowercase form is used unless flag is
// nonzero, in which case the uppercase form is used. The behavior
// is undefined if flag is nonzero and digit d has no uppercase form.
function encode_digit(d, flag) {
return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
}
//** Bias adaptation function **
function adapt(delta, numpoints, firsttime ) {
var k;
delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);
delta += Math.floor(delta / numpoints);
for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {
delta = Math.floor(delta / ( base - tmin ));
}
return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));
}
// encode_basic(bcp,flag) forces a basic code point to lowercase if flag is zero,
// uppercase if flag is nonzero, and returns the resulting code point.
// The code point is unchanged if it is caseless.
// The behavior is undefined if bcp is not a basic code point.
function encode_basic(bcp, flag) {
bcp -= (bcp - 97 < 26) << 5;
return bcp + ((!flag && (bcp - 65 < 26)) << 5);
}
// Main decode
this.decode=function(input,preserveCase) {
// Dont use utf16
var output=[];
var case_flags=[];
var input_length = input.length;
var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;
// Initialize the state:
n = initial_n;
i = 0;
bias = initial_bias;
// Handle the basic code points: Let basic be the number of input code
// points before the last delimiter, or 0 if there is none, then
// copy the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) basic = 0;
for (j = 0; j < basic; ++j) {
if(preserveCase) case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);
if ( input.charCodeAt(j) >= 0x80) {
throw new RangeError("Illegal input >= 0x80");
}
output.push( input.charCodeAt(j) );
}
// Main decoding loop: Start just after the last delimiter if any
// basic code points were copied; start at the beginning otherwise.
for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {
// ic is the index of the next character to be consumed,
// Decode a generalized variable-length integer into delta,
// which gets added to i. The overflow checking is easier
// if we increase i as we go, then subtract off its starting
// value at the end to obtain delta.
for (oldi = i, w = 1, k = base; ; k += base) {
if (ic >= input_length) {
throw RangeError ("punycode_bad_input(1)");
}
digit = decode_digit(input.charCodeAt(ic++));
if (digit >= base) {
throw RangeError("punycode_bad_input(2)");
}
if (digit > Math.floor((maxint - i) / w)) {
throw RangeError ("punycode_overflow(1)");
}
i += digit * w;
t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
if (digit < t) { break; }
if (w > Math.floor(maxint / (base - t))) {
throw RangeError("punycode_overflow(2)");
}
w *= (base - t);
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi === 0);
// i was supposed to wrap around from out to 0,
// incrementing n each time, so we'll fix that now:
if ( Math.floor(i / out) > maxint - n) {
throw RangeError("punycode_overflow(3)");
}
n += Math.floor( i / out ) ;
i %= out;
// Insert n at position i of the output:
// Case of last character determines uppercase flag:
if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}
output.splice(i, 0, n);
i++;
}
if (preserveCase) {
for (i = 0, len = output.length; i < len; i++) {
if (case_flags[i]) {
output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);
}
}
}
return this.utf16.encode(output);
};
//** Main encode function **
this.encode = function (input,preserveCase) {
//** Bias adaptation function **
var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;
if (preserveCase) {
// Preserve case, step1 of 2: Get a list of the unaltered string
case_flags = this.utf16.decode(input);
}
// Converts the input in UTF-16 to Unicode
input = this.utf16.decode(input.toLowerCase());
var input_length = input.length; // Cache the length
if (preserveCase) {
// Preserve case, step2 of 2: Modify the list to true/false
for (j=0; j < input_length; j++) {
case_flags[j] = input[j] != case_flags[j];
}
}
var output=[];
// Initialize the state:
n = initial_n;
delta = 0;
bias = initial_bias;
// Handle the basic code points:
for (j = 0; j < input_length; ++j) {
if ( input[j] < 0x80) {
output.push(
String.fromCharCode(
case_flags ? encode_basic(input[j], case_flags[j]) : input[j]
)
);
}
}
h = b = output.length;
// h is the number of code points that have been handled, b is the
// number of basic code points
if (b > 0) output.push(delimiter);
// Main encoding loop:
//
while (h < input_length) {
// All non-basic code points < n have been
// handled already. Find the next larger one:
for (m = maxint, j = 0; j < input_length; ++j) {
ijv = input[j];
if (ijv >= n && ijv < m) m = ijv;
}
// Increase delta enough to advance the decoder's
// <n,i> state to <m,0>, but guard against overflow:
if (m - n > Math.floor((maxint - delta) / (h + 1))) {
throw RangeError("punycode_overflow (1)");
}
delta += (m - n) * (h + 1);
n = m;
for (j = 0; j < input_length; ++j) {
ijv = input[j];
if (ijv < n ) {
if (++delta > maxint) return Error("punycode_overflow(2)");
}
if (ijv == n) {
// Represent delta as a generalized variable-length integer:
for (q = delta, k = base; ; k += base) {
t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
if (q < t) break;
output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );
q = Math.floor( (q - t) / (base - t) );
}
output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));
bias = adapt(delta, h + 1, h == b);
delta = 0;
++h;
}
}
++delta, ++n;
}
return output.join("");
}
this.ToASCII = function ( domain ) {
var domain_array = domain.split(".");
var out = [];
for (var i=0; i < domain_array.length; ++i) {
var s = domain_array[i];
out.push(
s.match(/[^A-Za-z0-9-]/) ?
"xn--" + punycode.encode(s) :
s
);
}
return out.join(".");
}
this.ToUnicode = function ( domain ) {
var domain_array = domain.split(".");
var out = [];
for (var i=0; i < domain_array.length; ++i) {
var s = domain_array[i];
out.push(
s.match(/^xn--/) ?
punycode.decode(s.slice(4)) :
s
);
}
return out.join(".");
}
}();
// Example of usage:
domain.oninput = function() {
var input = domain.value
var ascii = punycode.ToASCII(input)
var display = punycode.ToUnicode(ascii)
domain_ascii.value = ascii
domain_display.value = display
}
```
```html
<p>Try with your own data</p>
<label>
<div>Input domain</div>
<div><input id="domain" type="text"></div>
</label>
<div>Ascii: <output id="domain_ascii"></div>
<div>Display: <output id="domain_display"></div>
```
**Licence:**
From RFC3492:
>
> Disclaimer and license
>
>
> Regarding this entire document or any portion of it (including the pseudocode and C code), the author makes no guarantees and is not responsible for any damage resulting from its use. The author grants irrevocable permission to anyone to use, modify, and distribute it in any way that does not diminish the rights of anyone else to use, modify, and distribute it, provided that redistributed derivative works do not contain misleading author or version information. Derivative works need not be licensed under similar terms.
>
>
>
I put my work in this punycode and utf16 in the public domain. It would be nice to get an email telling me in what project you use it.
**The scope of the code**
*Each TLD has rules for which code points are allowed. The scope of the code below is to encode and decode a string between punycode and the internal encoding used by javascript regardes of those rules.
Depending on your use case, you may need to filter the string.
For example, 0xFE0F: Variation Selector-16, an invisible code point that specifies that the previous character should be displayed with emoji presentation.
If you search for "allowed code points in IDN" you should find several projects that can help you filter the string.*
|
183,488 |
<p>We are doing some performance tests on our website and we are getting the following error a lot:</p>
<pre><code>*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58
DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25.
</code></pre>
<p>Line 25 is the following:</p>
<pre><code>SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE
</code></pre>
<p>And lastly, this is perl code.</p>
<p>Any ideas?</p>
<p><strong>EDIT</strong>: the issue here was that I was searching in the zip file with the string "74523%" which is too long. I ended up just not adding the % if they give five digits.</p>
|
[
{
"answer_id": 183518,
"author": "Chris Driver",
"author_id": 5217,
"author_profile": "https://Stackoverflow.com/users/5217",
"pm_score": 6,
"selected": true,
"text": "<p>Either the parameter supplied for <code>ZIP_CODE</code> is larger (in length) than <code>ZIP_CODE</code>s column width or the parameter supplied for <code>CITY</code> is larger (in length) than <code>CITY</code>s column width. </p>\n\n<p>It would be interesting to know the values supplied for the two <code>?</code> placeholders.</p>\n"
},
{
"answer_id": 35803390,
"author": "Keegan",
"author_id": 6019736,
"author_profile": "https://Stackoverflow.com/users/6019736",
"pm_score": 2,
"selected": false,
"text": "<p>I got around the issue by using a convert on the \"?\", so my code looks like convert(char(50),?) and that got rid of the truncation error.</p>\n"
},
{
"answer_id": 56671675,
"author": "hui chen",
"author_id": 9204563,
"author_profile": "https://Stackoverflow.com/users/9204563",
"pm_score": 4,
"selected": false,
"text": "<p>This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:</p>\n\n<blockquote>\n <p>The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a \"String data, right truncation\" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.</p>\n</blockquote>\n\n<p>You can find the full article <a href=\"https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/known-issues-in-this-version-of-the-driver?view=sql-server-2017\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 64951940,
"author": "Daya Shankar",
"author_id": 14685153,
"author_profile": "https://Stackoverflow.com/users/14685153",
"pm_score": 1,
"selected": false,
"text": "<p>I was facing the same issue. So, i created a stored Procedure and defined the size like\n@FromDate datetime,\n@ToDate datetime,\n@BL varchar(50)</p>\n<p>After defining the size in @BL varchar(50), i did not face any problem. Now it is working fine</p>\n"
},
{
"answer_id": 72255401,
"author": "luca.vercelli",
"author_id": 5116356,
"author_profile": "https://Stackoverflow.com/users/5116356",
"pm_score": 0,
"selected": false,
"text": "<p>If the connection is done via PHP, we solved with the connection parameter "CharacterSet":</p>\n<pre><code>sqlsrv_connect(DB_PTH_HOST, array(\n "Database" => ***,\n "UID" => ***,\n "PWD" => ***,\n "CharacterSet" => "UTF-8"));\n</code></pre>\n"
},
{
"answer_id": 74407689,
"author": "Jett Pesson",
"author_id": 12265415,
"author_profile": "https://Stackoverflow.com/users/12265415",
"pm_score": 0,
"selected": false,
"text": "<p>I experienced this today on an application that has been running for years. My cause was a little different, so I figured I'd share to help anyone in the future that this happens to.</p>\n<p>For the issue I experienced, we have an application that runs on Client machines and the clients talk to the DB server via ODBC connection. For whatever reason, the ODBC driver on the client had updated to a newer version than the server had, (which usually didn't matter in the past). The version was only 1 month apart but was the cause of the issue. I went to windows patch history and uninstalled the patch whose date most closely matched the ODBC driver date, and this resolved the issue. (to check ODBC driver version, just search for ODBC in windows start, open ODBC 32, click on the drivers tab, scroll to the driver for the connection type you use, and the date is listed far right.)</p>\n"
},
{
"answer_id": 74636718,
"author": "user5693936",
"author_id": 5693936,
"author_profile": "https://Stackoverflow.com/users/5693936",
"pm_score": 0,
"selected": false,
"text": "<p>Similar to the <a href=\"https://stackoverflow.com/a/72255401/5693936\">solution provided by luca.vercelli</a>: in R, using <code>dbConnect</code> from the <code>odbc</code> package, you can specify the <code>encoding</code> used by the database. My database uses the <code>SQL_Latin1_General_CP1_CI_AS</code> collation, and specifying the <code>latin1</code> encoding in <code>dbConnect</code> solved the problem.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
We are doing some performance tests on our website and we are getting the following error a lot:
```
*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58
DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25.
```
Line 25 is the following:
```
SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE
```
And lastly, this is perl code.
Any ideas?
**EDIT**: the issue here was that I was searching in the zip file with the string "74523%" which is too long. I ended up just not adding the % if they give five digits.
|
Either the parameter supplied for `ZIP_CODE` is larger (in length) than `ZIP_CODE`s column width or the parameter supplied for `CITY` is larger (in length) than `CITY`s column width.
It would be interesting to know the values supplied for the two `?` placeholders.
|
183,496 |
<p>I've recently come across this piece of JavaScript code:</p>
<pre><code>if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)
</code></pre>
<p>I was intrigued, because to write this test I would have done:</p>
<pre><code>if (/(>=|<=|<>)/.test(sCompOp))
</code></pre>
<p>Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...?</p>
<p>It seems to me that using <code>String.indexOf()</code> for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex?</p>
<p>By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?</p>
|
[
{
"answer_id": 183541,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 1,
"selected": false,
"text": "<p>Is it a really old piece of code? It may have been written before regexes were widely used in javascript. Overall it looks like someone was trying to be too clever and \"optimized\" that statement or came from a C background and wasn't used to regexes. A regular expression can be expensive to use but string concatenation can be too and if it's not in a loop I would go with whichever one is easier to understand (for me, the regex).</p>\n"
},
{
"answer_id": 183580,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>There might have been a noticeable speed difference once upon a time, but it's not the case anymore. I think this is either:</p>\n\n<ol>\n<li>Legacy code from (godless) The Land Before REGEX.</li>\n<li>Written by somebody who doesn't know about REGEX or is afraid of it.</li>\n</ol>\n"
},
{
"answer_id": 183645,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... <em>except</em> when <code>sCompOp</code> could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long <code>sCompOp</code> gets, while the second method will potentially iterate through the entire length of <code>sCompOp</code>.</p>\n<p>Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test...</p>\n<p>Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues:</p>\n<pre><code>/^(>=|<=|<>)$/\n</code></pre>\n<hr />\n<h3>Testing code:</h3>\n<pre><code>function Time(fn, iter)\n{\n var start = new Date();\n for (var i=0; i<iter; ++i)\n fn();\n var end = new Date();\n console.log(fn.toString().replace(/[\\r|\\n]/g, ' '), "\\n : " + (end-start));\n}\n\nfunction IndexMethod(op)\n{\n return (",>=,<=,<>,".indexOf("," + op + ",") != -1);\n}\n\nfunction RegexMethod(op)\n{\n return /(>=|<=|<>)/.test(op);\n}\n\nfunction timeTests()\n{\n var loopCount = 50000;\n \n Time(function(){IndexMethod(">=");}, loopCount);\n Time(function(){IndexMethod("<=");}, loopCount);\n Time(function(){IndexMethod("<>");}, loopCount);\n Time(function(){IndexMethod("!!");}, loopCount);\n Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);\n Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);\n\n Time(function(){RegexMethod(">=");}, loopCount);\n Time(function(){RegexMethod("<=");}, loopCount);\n Time(function(){RegexMethod("<>");}, loopCount);\n Time(function(){RegexMethod("!!");}, loopCount);\n Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);\n Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);\n}\n\ntimeTests();\n</code></pre>\n<p>Tested in IE6, FF3, Chrome 0.2.149.30</p>\n"
},
{
"answer_id": 183800,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 2,
"selected": false,
"text": "<p>I doubt it is a question of performance or optimization. I would suspect the author of that code was simply not comfortable or familiar with regular expressions. Also notice how the comma-separated string isn't split apart in order to leverage object properties - possibly also a case of lack of familiarity with the language.</p>\n\n<p>For example, another way of testing for an operator in a comma-separated list of allowable operators would be to split the comma-separated list of allowable operators and do a one-time initialization of an object with the operators as properties:</p>\n\n<pre><code>var aOps = \">=,<=,<>\".split(\",\");\nvar allowableOps = {};\nfor (var iLoop = 0; iLoop < aOps.length; iLoop++) {\n allowableOps[aOps[iLoop]] = true;\n} //for\n</code></pre>\n\n<p>This small initialization overhead would likely be offset by the ability to do speedy lookups:</p>\n\n<pre><code>if (allowableOps[sCompOp]) { ... }\n</code></pre>\n\n<p>Of course, this could end up being slower overall, but it is arguably a cleaner approach.</p>\n"
},
{
"answer_id": 185770,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<p>That reminds me of some early javascript-based <code>getElementsByClassName</code> implementations.</p>\n<p><code>indexOf</code> was much faster than using a regular expression, but the code that made use of <code>indexOf</code> started from the assumption that the developer would separate class names with spaces (and not tabs and line feeds). To be fair, some regexp-based implementations were using <code>\\b</code> (word boundary), which is incompatible with the CSS spec (because CSS allows hyphens in class names).</p>\n<p>Using <code>indexOf</code> to support <code>getElementsByClassName</code> in IE can really make a difference because there are no faster alternatives, and the className property's underlying getter/setter conveniently replace tabs and linefeeds with spaces.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559/"
] |
I've recently come across this piece of JavaScript code:
```
if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)
```
I was intrigued, because to write this test I would have done:
```
if (/(>=|<=|<>)/.test(sCompOp))
```
Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...?
It seems to me that using `String.indexOf()` for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex?
By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?
|
I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... *except* when `sCompOp` could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long `sCompOp` gets, while the second method will potentially iterate through the entire length of `sCompOp`.
Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test...
Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues:
```
/^(>=|<=|<>)$/
```
---
### Testing code:
```
function Time(fn, iter)
{
var start = new Date();
for (var i=0; i<iter; ++i)
fn();
var end = new Date();
console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));
}
function IndexMethod(op)
{
return (",>=,<=,<>,".indexOf("," + op + ",") != -1);
}
function RegexMethod(op)
{
return /(>=|<=|<>)/.test(op);
}
function timeTests()
{
var loopCount = 50000;
Time(function(){IndexMethod(">=");}, loopCount);
Time(function(){IndexMethod("<=");}, loopCount);
Time(function(){IndexMethod("<>");}, loopCount);
Time(function(){IndexMethod("!!");}, loopCount);
Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
Time(function(){RegexMethod(">=");}, loopCount);
Time(function(){RegexMethod("<=");}, loopCount);
Time(function(){RegexMethod("<>");}, loopCount);
Time(function(){RegexMethod("!!");}, loopCount);
Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
}
timeTests();
```
Tested in IE6, FF3, Chrome 0.2.149.30
|
183,499 |
<p>One of the things that always bugs me about using Readers and Streams in Java is that the <code>close()</code> method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction:</p>
<pre><code>FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
</code></pre>
<p>But I've also seen this construction:</p>
<pre><code>FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
</code></pre>
<p>I prefer the first construction because there's only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction?</p>
<p>UPDATE: Would it make a difference if I pointed out that both <code>read</code> and <code>close</code> only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.</p>
|
[
{
"answer_id": 183520,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 1,
"selected": false,
"text": "<p>The difference, as far as I can see, is that there are different exceptions and causes in play on different levels, and the </p>\n\n<p>catch (Exception e) </p>\n\n<p>obscures that. The only point of the multiple levels is to distinguish your exceptions, and what you'll do about them:</p>\n\n<pre><code>try\n{\n try{\n ...\n }\n catch(IOException e)\n {\n ..\n }\n}\ncatch(Exception e)\n{\n // we could read, but now something else is broken \n ...\n}\n</code></pre>\n"
},
{
"answer_id": 183572,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 5,
"selected": false,
"text": "<p>I'm afraid there's a big problem with the first example, which is that if an exception happens on or after the read, the <code>finally</code> block executes. So far so good. But what if the <code>fr.close()</code> then causes another exception to be thrown? This will \"trump\" the first exception (a bit like putting <code>return</code> in a <code>finally</code> block) and <strong>you will lose all information about what actually caused the problem</strong> to begin with. </p>\n\n<p>Your finally block should use:</p>\n\n<pre><code>IOUtil.closeSilently(fr);\n</code></pre>\n\n<p>where this utility method just does:</p>\n\n<pre><code>public static void closeSilently(Closeable c) {\n try { c.close(); } catch (Exception e) {} \n} \n</code></pre>\n"
},
{
"answer_id": 183575,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the second one. Why? If both <code>read()</code> and <code>close()</code> throw exceptions, one of them could be lost. In the first construction, the exception from <code>close()</code> overrides the exception from <code>read()</code>, while in the second one, the exception from <code>close()</code> is handled separately.</p>\n\n<hr>\n\n<p><strong>As of Java 7, the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources construct</a> makes this much simpler.</strong> To read without caring about exceptions:</p>\n\n<pre><code>try (FileReader fr = new FileReader(\"SomeFile.txt\")) {\n fr.read();\n // no need to close since the try-with-resources statement closes it automatically\n}\n</code></pre>\n\n<p>With exception handling:</p>\n\n<pre><code>try (FileReader fr = new FileReader(\"SomeFile.txt\")) {\n fr.read();\n // no need to close since the try-with-resources statement closes it automatically\n} catch (IOException e) {\n // Do exception handling\n log(e);\n // If this catch block is run, the FileReader has already been closed.\n // The exception could have come from either read() or close();\n // if both threw exceptions (or if multiple resources were used and had to be closed)\n // then only one exception is thrown and the others are suppressed\n // but can still be retrieved:\n Throwable[] suppressed = e.getSuppressed(); // can be an empty array\n for (Throwable t : suppressed) {\n log(suppressed[t]);\n }\n}\n</code></pre>\n\n<p>Only one try-catch is needed and all exceptions can be safely handled. You can still add a <code>finally</code> block if you like, but there is no need to close the resources.</p>\n"
},
{
"answer_id": 183646,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "<p>The standard convention I use is that you must not let exceptions escape a finally block.</p>\n\n<p>This is because if an exception is already propagating the exception thrown out of the finally block will trump the original exception (and thus be lost).</p>\n\n<p>In 99% of cases this is not what you want as the original exception is probably the source of your problem (any secondary exceptions may be side effects from the first but will obscure your ability to find the source of the original exception and thus the real problem).</p>\n\n<p>So your basic code should look like this:</p>\n\n<pre><code>try\n{\n // Code\n}\n// Exception handling\nfinally\n{\n // Exception handling that is garanteed not to throw.\n try\n {\n // Exception handling that may throw.\n }\n // Optional Exception handling that should not throw\n finally()\n {}\n}\n</code></pre>\n"
},
{
"answer_id": 183667,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": true,
"text": "<p>I would always go for the first example.</p>\n\n<p>If close were to throw an exception (in practice that will never happen for a FileReader), wouldn't the standard way of handling that be to throw an exception appropriate to the caller? The close exception almost certainly trumps any problem you had using the resource. The second method is probably more appropriate if your idea of exception handling is to call System.err.println.</p>\n\n<p>There is an issue of how far exceptions should be thrown. ThreadDeath should always be rethrown, but any exception within finally would stop that. Similarly Error should throw further than RuntimeException and RuntimeException further than checked exceptions. If you really wanted to you could write code to follow these rules, and then abstract it with the \"execute around\" idiom.</p>\n"
},
{
"answer_id": 183705,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>If both <em>read</em> and <em>close</em> throw an exception, the exception from <em>read</em> will be hidden in option 1. So, the second option does more error handling.</p>\n\n<p>However, in most cases, the first option will still be preferred.</p>\n\n<ol>\n<li>In many cases, you can't deal with exceptions in the method they are generated, but you still must encapsulate the stream handling within that operation.</li>\n<li>Try adding a writer to the code and see how verbose the second approach gets.</li>\n</ol>\n\n<p>If you need to pass all the generated exceptions, <a href=\"http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html\" rel=\"nofollow noreferrer\">it can be done</a>.</p>\n"
},
{
"answer_id": 183779,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": false,
"text": "<p>I usually do the following. First, define a template-method based class to deal with the try/catch mess</p>\n\n<pre><code>import java.io.Closeable;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic abstract class AutoFileCloser {\n private static final Closeable NEW_FILE = new Closeable() {\n public void close() throws IOException {\n // do nothing\n }\n };\n\n // the core action code that the implementer wants to run\n protected abstract void doWork() throws Throwable;\n\n // track a list of closeable thingies to close when finished\n private List<Closeable> closeables_ = new LinkedList<Closeable>();\n\n // mark a new file\n protected void newFile() {\n closeables_.add(0, NEW_FILE);\n }\n\n // give the implementer a way to track things to close\n // assumes this is called in order for nested closeables,\n // inner-most to outer-most\n protected void watch(Closeable closeable) {\n closeables_.add(0, closeable);\n }\n\n public AutoFileCloser() {\n // a variable to track a \"meaningful\" exception, in case\n // a close() throws an exception\n Throwable pending = null;\n\n try {\n doWork(); // do the real work\n\n } catch (Throwable throwable) {\n pending = throwable;\n\n } finally {\n // close the watched streams\n boolean skip = false;\n for (Closeable closeable : closeables_) {\n if (closeable == NEW_FILE) {\n skip = false;\n } else if (!skip && closeable != null) {\n try {\n closeable.close();\n // don't try to re-close nested closeables\n skip = true;\n } catch (Throwable throwable) {\n if (pending == null) {\n pending = throwable;\n }\n }\n }\n }\n\n // if we had a pending exception, rethrow it\n // this is necessary b/c the close can throw an\n // exception, which would remove the pending\n // status of any exception thrown in the try block\n if (pending != null) {\n if (pending instanceof RuntimeException) {\n throw (RuntimeException) pending;\n } else {\n throw new RuntimeException(pending);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Note the \"pending\" exception -- this takes care of the case where an exception thrown during close would mask an exception we might really care about.</p>\n\n<p>The finally tries to close from the outside of any decorated stream first, so if you had a BufferedWriter wrapping a FileWriter, we try to close the BuffereredWriter first, and if that fails, still try to close the FileWriter itself.</p>\n\n<p>You can use the above class as follows:</p>\n\n<pre><code>try {\n // ...\n\n new AutoFileCloser() {\n @Override protected void doWork() throws Throwable {\n // declare variables for the readers and \"watch\" them\n FileReader fileReader = null;\n BufferedReader bufferedReader = null;\n watch(fileReader = new FileReader(\"somefile\"));\n watch(bufferedReader = new BufferedReader(fileReader));\n\n // ... do something with bufferedReader\n\n // if you need more than one reader or writer\n newFile(); // puts a flag in the \n FileWriter fileWriter = null;\n BufferedWriter bufferedWriter = null;\n watch(fileWriter = new FileWriter(\"someOtherFile\"));\n watch(bufferedWriter = new BufferedWriter(fileWriter));\n\n // ... do something with bufferedWriter\n }\n };\n\n // .. other logic, maybe more AutoFileClosers\n\n} catch (RuntimeException e) {\n // report or log the exception\n}\n</code></pre>\n\n<p>Using this approach you never have to worry about the try/catch/finally to deal with closing files again.</p>\n\n<p>If this is too heavy for your use, at least think about following the try/catch and the \"pending\" variable approach it uses.</p>\n"
},
{
"answer_id": 184001,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>2nd approach.</p>\n\n<p>Otherwise, I don't see you catching the exception from the FileReader constructor</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html#FileReader(java.lang.String)\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html#FileReader(java.lang.String)</a></p>\n\n<p>public FileReader(String fileName)\n throws FileNotFoundException</p>\n\n<p>So, I usually have the constructor inside the try block as well. the finally block checks to see if the reader is NOT null before trying to do a close.</p>\n\n<p>The same pattern goes for Datasource, Connection, Statement, ResultSet.</p>\n"
},
{
"answer_id": 184558,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes nested try-catch is not a preference, consider this:</p>\n\n<pre><code>try{\n string s = File.Open(\"myfile\").ReadToEnd(); // my file has a bunch of numbers\n // I want to get a total of the numbers \n int total = 0;\n foreach(string line in s.split(\"\\r\\n\")){\n try{ \n total += int.Parse(line); \n } catch{}\n }\ncatch{}\n</code></pre>\n\n<p>This is probably a bad example, but there are times you will need nested try-cactch.</p>\n"
},
{
"answer_id": 185382,
"author": "Dunderklumpen",
"author_id": 16239,
"author_profile": "https://Stackoverflow.com/users/16239",
"pm_score": 0,
"selected": false,
"text": "<p>I like the approach by @Chris Marshall, but I never like to see exceptions getting swallowed silently. I think its best to log exceptions, especially if you are contiuing regardless. </p>\n\n<p>I always use a utility class to handle these sort of common exceptions, but I would make this tiny different to his answer.</p>\n\n<p>I would always use a logger (log4j for me) to log errors etc.</p>\n\n<pre><code>IOUtil.close(fr);\n</code></pre>\n\n<p>A slight modification to the utility method:</p>\n\n<pre><code>public static void close(Closeable c) {\n try {\n c.close();\n } catch (Exception e) {\n logger.error(\"An error occurred while closing. Continuing regardless\", e); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 29639456,
"author": "codelion",
"author_id": 598029,
"author_profile": "https://Stackoverflow.com/users/598029",
"pm_score": 0,
"selected": false,
"text": "<p>In some cases a nested Try-Catch is unavoidable. For instance when the error recovery code itself can throw and exception. But in order to improve the readability of the code you can always extract the nested block into a method of its own. Check out <a href=\"https://blog.srcclr.com/avoiding-nested-try-catch-in-java/\" rel=\"nofollow\">this</a> blog post for more examples on nested Try-Catch-Finally blocks.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23669/"
] |
One of the things that always bugs me about using Readers and Streams in Java is that the `close()` method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction:
```
FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
```
But I've also seen this construction:
```
FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
```
I prefer the first construction because there's only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction?
UPDATE: Would it make a difference if I pointed out that both `read` and `close` only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.
|
I would always go for the first example.
If close were to throw an exception (in practice that will never happen for a FileReader), wouldn't the standard way of handling that be to throw an exception appropriate to the caller? The close exception almost certainly trumps any problem you had using the resource. The second method is probably more appropriate if your idea of exception handling is to call System.err.println.
There is an issue of how far exceptions should be thrown. ThreadDeath should always be rethrown, but any exception within finally would stop that. Similarly Error should throw further than RuntimeException and RuntimeException further than checked exceptions. If you really wanted to you could write code to follow these rules, and then abstract it with the "execute around" idiom.
|
183,527 |
<p>I have a dtsx package with a precedence constraint that evaluates an expression and a constraint. The constraint is "success" and the expression is "@myVariable" == 3. myVariable is an int32, and when set in Visual Studio's design GUI the package executes fine. There are two other paths that check for the value to be 1 or 2.</p>
<p>However when I try to run the package from the command line and pass in a value for my variable, it errors out claiming the expression does not evaluate to a boolean!</p>
<p><strong>Command:</strong></p>
<pre><code>dtexec /F "c:myPackage.dtsx" /SET
\Package.Variables[User::myVariable].Properties[Value];3
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>The expression "@myVariable == 1" must evaluate to True or False.
Change the expression to evaluate to a Boolean value.
</code></pre>
<p>The fact this runs fine from the GUI and that microsofts documentation claims == (intuiatively) returns a boolean has me very confused. I've also tried surrounding the 3 in double quotes in my command with no luck, and now I am out of ideas.</p>
<p>Anybody have an idea of what is going on?</p>
|
[
{
"answer_id": 195183,
"author": "Michael Entin",
"author_id": 19880,
"author_profile": "https://Stackoverflow.com/users/19880",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if it causes the problem, but you are using a slightly odd syntax to set variable value, try</p>\n\n<pre><code>dtexec ... /SET \\Package.Variables[User::myVariable].Value;3\n</code></pre>\n\n<p>Note I'm using <code>.Value</code>, instead of <code>.Properties[Value]</code>. <code>.Value</code> is the official way recommended by Books Online. Maybe the <code>.Properties[Value]</code> syntax also happens to work, but changes the variable type.</p>\n"
},
{
"answer_id": 221951,
"author": "Aaron Silverman",
"author_id": 26197,
"author_profile": "https://Stackoverflow.com/users/26197",
"pm_score": 3,
"selected": true,
"text": "<p>Sorry took me so long to get back to this thread! But <code>(DT_I4)@[User::myVariable] == 3</code> did the trick. Thanks!</p>\n"
},
{
"answer_id": 388063,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be a bug in the initial release of dtexec.exe. I have version 9.00.3042.00 wich is like, SQL Server 2005 SP2, installed in my dev enviro. We have a second test machine that is on version 9.00.1399.06 . The only place I see this failure is on the test box. My dev. box runs to completion. I added an explicit type conversion (DT_BOOL) to my boolean variable that was part of my expressions and the error went away.</p>\n\n<p>Also the .Value comment above is incorrect. It is supposed to be .Properties[Value] , 'cause the Value of a variable is simply an item in the global variable properties collection. This isn't C# or VB.net syntax. This is SSIS syntax.</p>\n"
},
{
"answer_id": 418391,
"author": "Jobo",
"author_id": 51915,
"author_profile": "https://Stackoverflow.com/users/51915",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like a bug in ssis because the value your passing in via the command line is not being automatically casted to the configuration variables' type. SSIS seems to treat values passed in via cmd line as strings, which causes issues at run time. Either change your variable to a string and do the comparison on that, or use the (DT_I4) to cast in the expression.</p>\n"
},
{
"answer_id": 896510,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's definitely a bug in dtexec - I had a similar problem (setting an integer value via the /set command on a dtexec command line) that complained further in the package execution the (output) variable was of the wrong type when returned from a stored procedure.</p>\n\n<p>Omitting the set of that value (was setting it to zero anyway) fixed up the package execution error. Not sure what you'd do if you really needed the value - they seem to work fine as input parameters, just screws up when you want to use them as output parameters and they aren't strings.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26197/"
] |
I have a dtsx package with a precedence constraint that evaluates an expression and a constraint. The constraint is "success" and the expression is "@myVariable" == 3. myVariable is an int32, and when set in Visual Studio's design GUI the package executes fine. There are two other paths that check for the value to be 1 or 2.
However when I try to run the package from the command line and pass in a value for my variable, it errors out claiming the expression does not evaluate to a boolean!
**Command:**
```
dtexec /F "c:myPackage.dtsx" /SET
\Package.Variables[User::myVariable].Properties[Value];3
```
**Error:**
```
The expression "@myVariable == 1" must evaluate to True or False.
Change the expression to evaluate to a Boolean value.
```
The fact this runs fine from the GUI and that microsofts documentation claims == (intuiatively) returns a boolean has me very confused. I've also tried surrounding the 3 in double quotes in my command with no luck, and now I am out of ideas.
Anybody have an idea of what is going on?
|
Sorry took me so long to get back to this thread! But `(DT_I4)@[User::myVariable] == 3` did the trick. Thanks!
|
183,532 |
<p>I would like to ask for some simple examples showing the uses of <code><div></code> and <code><span></code>. I've seen them both used to mark a section of a page with an <code>id</code> or <code>class</code>, but I'm interested in knowing if there are times when one is preferred over the other.</p>
|
[
{
"answer_id": 183535,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": false,
"text": "<p><code><div></code> is a block-level element and <code><span></code> is an inline element. </p>\n\n<p>If you wanted to do something with some inline text, <code><span></code> is the way to go since it will not introduce line breaks that a <code><div></code> would.</p>\n\n<hr>\n\n<p>As noted by others, there are some semantics implied with each of these, most significantly the fact that a <code><div></code> implies a logical division in the document, akin to maybe a section of a document or something, a la:</p>\n\n<pre><code><div id=\"Chapter1\">\n <p>Lorem ipsum dolor sit amet, <span id=\"SomeSpecialText1\">consectetuer adipiscing</span> elit. Duis congue vehicula purus.</p>\n <p>Nam <span id=\"SomeSpecialText2\">eget magna nec</span> sapien fringilla euismod. Donec hendrerit.</p> \n</div>\n</code></pre>\n"
},
{
"answer_id": 183536,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 10,
"selected": true,
"text": "<ul>\n<li><code>div</code> is a <a href=\"https://en.wikipedia.org/wiki/HTML_element#Block_elements\" rel=\"noreferrer\">block element</a></li>\n<li><code>span</code> is an <a href=\"https://en.wikipedia.org/wiki/HTML_element#Inline_elements\" rel=\"noreferrer\">inline element</a>.</li>\n</ul>\n\n<p>This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.</p>\n\n<h2>For example:</h2>\n\n<pre><code><div>This a large main division, with <span>a small bit</span> of spanned text!</div>\n</code></pre>\n\n<h3>Note that it is illegal to place a block-level element within an inline element, so:</h3>\n\n<pre><code><div>Some <span>text that <div>I want</div> to mark</span> up</div>\n</code></pre>\n\n<p>...is illegal.</p>\n\n<hr>\n\n<p>EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories\" rel=\"noreferrer\">here</a> for a pretty clear listing. The above is still illegal, as <code><span></code> only accepts phrasing content, and <code><div></code> is flow content.</p>\n\n<hr>\n\n<p>You asked for some concrete examples, so is one taken from my bowling website, <a href=\"http://www.bowlsk.com\" rel=\"noreferrer\">BowlSK</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"header\">\r\n <div id=\"userbar\">\r\n Hi there, <span class=\"username\">Chris Marasti-Georg</span> |\r\n <a href=\"/edit-profile.html\">Profile</a> |\r\n <a href=\"https://www.bowlsk.com/_ah/logout?...\">Sign out</a>\r\n </div>\r\n <h1><a href=\"/\">Bowl<span class=\"sk\">SK</span></a></h1>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><h2>Ok, what's going on?</h2> At the top of my page, I have a logical section, the \"header\". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, <code>h1</code>. The userbar, being a section, is wrapped in a <code>div</code>. Within that, the username is wrapped in a <code>span</code>, so that I can change the style. As you can see, I have also wrapped a <code>span</code> around 2 letters in the title - this allows me to change their color in my stylesheet.</p>\n\n<p>Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc. </p>\n\n<p>Section 4.4 of the <a href=\"https://dev.w3.org/html5/spec/Overview.html\" rel=\"noreferrer\">HTML 5 working draft</a> lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is \"final\" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using <code>document.createElement</code> before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up <a href=\"https://code.google.com/p/html5shiv/\" rel=\"noreferrer\">html5shiv</a>.</p>\n"
},
{
"answer_id": 183561,
"author": "Eric R. Rath",
"author_id": 23883,
"author_profile": "https://Stackoverflow.com/users/23883",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned in other answers, by default <code>div</code> will be rendered as a block element, while <code>span</code> will be rendered inline within its context. But neither has any semantic value; they exist to allow you to apply styling and an identity to any given bit of content. Using styles, you can make a <code>div</code> act like a <code>span</code> and vice-versa.</p>\n\n<p>One of the useful styles for <code>div</code> is <code>inline-block</code></p>\n\n<p>Examples:</p>\n\n<ol>\n<li><p><a href=\"http://dustwell.com/div-span-inline-block.html\" rel=\"noreferrer\">http://dustwell.com/div-span-inline-block.html</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/9189810/css-display-inline-vs-inline-block\">CSS display: inline vs inline-block</a></p></li>\n</ol>\n\n<p>I have used <code>inline-block</code> to a great success, in game web projects.</p>\n"
},
{
"answer_id": 183565,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>The real important difference is already mentioned in Chris' answer. However, the implications won't be obvious for everybody.</p>\n\n<p>As an inline element, <code><span></code> may only contain other inline elements. The following code is therefore wrong:</p>\n\n<pre><code><span><p>This is a paragraph</p></span>\n</code></pre>\n\n<p>The above code isn't valid. To wrap block-level elements, another block-level element must be used (such as <code><div></code>). On the other hand, <code><div></code> may only be used in places where block-level elements are legal.</p>\n\n<p>Furthermore, these rules are fixed in (X)HTML and they are <em>not</em> altered by the presence of CSS rules! So the following codes are <em>also</em> wrong!</p>\n\n<pre><code><span style=\"display: block\"><p>Still wrong</p></span>\n<span><p style=\"display: inline\">Just as wrong</p></span>\n</code></pre>\n"
},
{
"answer_id": 183571,
"author": "Pablo Herrero",
"author_id": 366094,
"author_profile": "https://Stackoverflow.com/users/366094",
"pm_score": 3,
"selected": false,
"text": "<p>I would say that if you know a bit of spanish to look at <a href=\"http://developer.mozilla.org/es/HTML/Elemento/span#div_y_span\" rel=\"nofollow noreferrer\">this page</a>, where is properly explained. </p>\n\n<p>However, a fast definition would be that <code>div</code> is for dividing sections and <code>span</code> is for applying some kind of style to an element within another block element like <code>div</code>.</p>\n"
},
{
"answer_id": 185819,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 9,
"selected": false,
"text": "<p>Just for the sake of completeness, I invite you to think about it like this:</p>\n\n<ul>\n<li>There are lots of block elements (linebreaks before and after) defined in HTML, and lots of inline tags (no linebreaks).</li>\n<li>But in modern HTML all elements are supposed to have <em>meanings</em>: a <code><p></code> is a paragraph, an <code><li></code> is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <code><blockquote></code> whether the content was a quote or not.</li>\n<li>So, what do you do when there <em>is</em> no meaning to the thing you're trying to do? There's no <em>meaning</em> to a 400px-wide column, is there? You just want your column of text to be 400px wide because that suits your design.</li>\n<li>For this reason, they added two more elements to HTML: the generic, or meaningless elements <code><div></code> and <code><span></code>, because otherwise, people would go back to abusing the elements which do have meanings.</li>\n</ul>\n"
},
{
"answer_id": 16621362,
"author": "Jagannath Samanta",
"author_id": 2396156,
"author_profile": "https://Stackoverflow.com/users/2396156",
"pm_score": 3,
"selected": false,
"text": "<p>Div is a block element and span is an inline element and its width depends upon the content of it self where div does not</p>\n"
},
{
"answer_id": 19231559,
"author": "Brian",
"author_id": 1486275,
"author_profile": "https://Stackoverflow.com/users/1486275",
"pm_score": 8,
"selected": false,
"text": "<p>There are already good, detailed answers here, but no visual examples, so here's a quick illustration:</p>\n\n<p><img src=\"https://i.stack.imgur.com/wA8PD.png\" alt=\"difference between div and span\"></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>This is a div.</div>\r\n<div>This is a div.</div>\r\n<div>This is a div.</div>\r\n<span>This is a span.</span>\r\n<span>This is a span.</span>\r\n<span>This is a span.</span></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><code><div></code> is a block tag, while <code><span></code> is an inline tag.</p>\n"
},
{
"answer_id": 35671823,
"author": "Robert",
"author_id": 1798677,
"author_profile": "https://Stackoverflow.com/users/1798677",
"pm_score": 2,
"selected": false,
"text": "<p>In HTML there are tags that add structure or semantics to content. For example the <code><p></code> tag is used to identify a paragraph. Another example is the <code><ol></code> tag for an ordered list.</p>\n\n<p>When there is no suitable tag available in HTML as shown above, the <code><div></code> and <code><span></code> tags are usually resorted to.</p>\n\n<p>The <code><div></code> tag is used to identify a blocklevel section/division of a document that has a line break both before and after it.</p>\n\n<p>Examples of where div tags can be used are headers, footers, navigations etc. However in HTML 5 these tags have already been provided.</p>\n\n<p>The <code><span></code> tag is used to identify an inline section/division of a document.</p>\n\n<p>For example a span tag can be used to add inline pictographs to an element. </p>\n"
},
{
"answer_id": 35876865,
"author": "Sam Hobbs",
"author_id": 2392247,
"author_profile": "https://Stackoverflow.com/users/2392247",
"pm_score": 4,
"selected": false,
"text": "<p>The significance of \"block element\" is implied but never stated explicitly. If we ignore all the theory (theory is good) then the following is a pragmatic comparison. The following:</p>\n\n<pre><code><p>This paragraph <span>has</span> a span.</p>\n<p>This paragraph <div>has</div> a div.</p>\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>This paragraph has a span.\n\nThis paragraph\n\nhas\na div.\n</code></pre>\n\n<p>That shows that not only <strong>should</strong> a div <strong>not</strong> be used inline, it simply won't produce the desired affect.</p>\n"
},
{
"answer_id": 50353745,
"author": "Alex W",
"author_id": 1399491,
"author_profile": "https://Stackoverflow.com/users/1399491",
"pm_score": 3,
"selected": false,
"text": "<p>Just wanted to add some historical context to how there came to be <code>span</code> vs <code>div</code></p>\n<p>History of <code>span</code>:</p>\n<blockquote>\n<p>On July 3, 1995, Benjamin C. W. Sittler <strong>proposes a generic text\ncontainer</strong> tag for applying styles to certain blocks of text.\nThe rendering is neutral except if used in conjunction of a\nstylesheet. There is a debate around versus about\nreadability, meaning. Bert Bos is mentioning the extensibility nature\nof the element through the class attribute (with values such as\ncity, person, date, etc.). <strong>Paul Prescod is worried that both elements\nwill be abused. He is opposed to text mentionning that "any new\nelement should be on an old one" and adding "If we create a tag with\nno semantics it can be used anywehere without ever being wrong.</strong> We\nmust force authors to properly tag the semantics of their document. We\nmust force editor vendors to make that choice explicit in their\ninterfaces."</p>\n</blockquote>\n<p><a href=\"https://www.w3.org/wiki/Html/Elements/span\" rel=\"nofollow noreferrer\">- Source (w3 wiki)</a></p>\n<p>From the RFC draft that introduces <code>span</code>:</p>\n<blockquote>\n<p>First, a generic con-\ntainer is needed to carry the LANG and BIDI attributes in\ncases where no other element is appropriate; <strong>the SPAN ele-\nment is introduced for that purpose.</strong></p>\n</blockquote>\n<p><a href=\"https://datatracker.ietf.org/doc/html/draft-ietf-html-i18n-01#page-12\" rel=\"nofollow noreferrer\">- Source (IETF Draft)</a></p>\n<p>History of <code>div</code>:</p>\n<blockquote>\n<p>DIV elements can be used to structure HTML documents as a hierarchy of divisions.</p>\n<p>...</p>\n<p>CENTER was introduced by Netscape before they added support for the\nHTML 3.0 DIV element. It is retained in HTML 3.2 on account of its\nwidespread deployment.</p>\n</blockquote>\n<p><a href=\"https://www.w3.org/TR/2018/SPSD-html32-20180315/#center\" rel=\"nofollow noreferrer\">HTML 3.2 Spec</a></p>\n<p>In a nutshell, both elements arose out of a need for a more semantically-generic container. Span was proposed as a more generic replacement for a <code><text></code> element to style text. Div was proposed as a generic way to divide pages and had the added benefit of replacing the <code><center></code> tag for center-aligning content. Div has always been a block element because of its history as a page divider. Span has always been an inline element because its original purpose was text styling and today div and span have both arrived at being generic elements with default block and inline display properties respectively.</p>\n"
},
{
"answer_id": 53593274,
"author": "yatheendra k v",
"author_id": 8836967,
"author_profile": "https://Stackoverflow.com/users/8836967",
"pm_score": 2,
"selected": false,
"text": "<p>Remember, basically and them self doesn't perform any function either.\nThey are <strong>not</strong> specific about functionality <strong>just by their tags</strong>.</p>\n\n<p>They can only be customized with the help of CSS.</p>\n\n<p>Now that coming to your question:</p>\n\n<p>SPAN tag together with some styling will be useful on having hold inside a line, say in a paragraph, in the html. \nThis is kind of line level or statement level in HTML.</p>\n\n<p>Example:</p>\n\n<pre><code><p>Am writing<span class=\"time\">this answer</span> in my free time of my day.</p>\n</code></pre>\n\n<p>DIV tag functionality as said can only be visible backed with styling, can have hold of large chunks of HTML code.</p>\n\n<p>DIV is Block level</p>\n\n<p>Example:</p>\n\n<pre><code> <div class=\"large-time\">\n <p>Am writing <span class=\"time\"> this answer</span> in my free time of my day. \n </p>\n </div>\n</code></pre>\n\n<p>Both have their time and case when to be used, based on your requirement.</p>\n\n<p>Hope am clear with the answer.\nThank you.</p>\n"
},
{
"answer_id": 62449945,
"author": "Vivek Mahajan",
"author_id": 11323042,
"author_profile": "https://Stackoverflow.com/users/11323042",
"pm_score": 2,
"selected": false,
"text": "<p>It's plain and simple.</p>\n\n<ul>\n<li>use of <code>span</code> does not affect the layout because it's inline(<code>in line</code> (one should not confuse because things could be wrapped))</li>\n<li>use of <code>div</code> affects the layout, the content inside appears in the new line(<code>block element</code>), when the element you wanna add has no special semantic meaning and you want it to appear in new line use <code><div></code>.</li>\n</ul>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3676/"
] |
I would like to ask for some simple examples showing the uses of `<div>` and `<span>`. I've seen them both used to mark a section of a page with an `id` or `class`, but I'm interested in knowing if there are times when one is preferred over the other.
|
* `div` is a [block element](https://en.wikipedia.org/wiki/HTML_element#Block_elements)
* `span` is an [inline element](https://en.wikipedia.org/wiki/HTML_element#Inline_elements).
This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.
For example:
------------
```
<div>This a large main division, with <span>a small bit</span> of spanned text!</div>
```
### Note that it is illegal to place a block-level element within an inline element, so:
```
<div>Some <span>text that <div>I want</div> to mark</span> up</div>
```
...is illegal.
---
EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference [here](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories) for a pretty clear listing. The above is still illegal, as `<span>` only accepts phrasing content, and `<div>` is flow content.
---
You asked for some concrete examples, so is one taken from my bowling website, [BowlSK](http://www.bowlsk.com):
```html
<div id="header">
<div id="userbar">
Hi there, <span class="username">Chris Marasti-Georg</span> |
<a href="/edit-profile.html">Profile</a> |
<a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a>
</div>
<h1><a href="/">Bowl<span class="sk">SK</span></a></h1>
</div>
```
Ok, what's going on?
--------------------
At the top of my page, I have a logical section, the "header". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, `h1`. The userbar, being a section, is wrapped in a `div`. Within that, the username is wrapped in a `span`, so that I can change the style. As you can see, I have also wrapped a `span` around 2 letters in the title - this allows me to change their color in my stylesheet.
Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.
Section 4.4 of the [HTML 5 working draft](https://dev.w3.org/html5/spec/Overview.html) lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using `document.createElement` before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up [html5shiv](https://code.google.com/p/html5shiv/).
|
183,560 |
<p>I have been trying to use the Perl utility/module "prove" as a test harness for some unit tests. The unit tests are a little more "system" than "unit" as I need to fork off some background processes as part of the test, Using the following...</p>
<pre><code>sub SpinupMonitor{
my $base_dir = shift;
my $config = shift;
my $pid = fork();
if($pid){
return $pid;
}else{
my $cmd = "$base_dir\/..\/bin\/monitor_real.pl -config $config -test";
close STDOUT;
exec ($cmd) or die "cannot exec test code [$cmd]\n";
}
}
sub KillMonitor{
my $pid = shift;
print "Killing monitor [$pid]\n";
kill(1,$pid);
}
</code></pre>
<p>However for some reason when I have my .t file spin up some extra processes it causes the test harness to hang at the end of the first .t file after all the tests have finished, rather than going on to the next file, or exiting if there is only one.</p>
<p>At first I wondered if it might be because I was killing of my sub-processes and leaving them defunct. So I added..</p>
<pre><code>$SIG{CHLD} = \&REAPER;
sub REAPER {
my $pid = wait;
$SIG{CHLD} = \&REAPER;
}
</code></pre>
<p>To the code. But that doesn't help. In fact on closed examination it turns out that my perl test file has exited and is now a defunct process and it is the prove wrapper script that has not reaped its child. In fact when I added a die() call at the end of my test script I got...</p>
<pre><code># Looks like your test died just after 7.
</code></pre>
<p>So my script exited but for some reason the harness isn't unraveling.</p>
<p>I did confirm that it is definitely my sub-processes that are upsetting it as when I disabled them while the tests failed the harness exited properly.</p>
<p>Is there anything I am doing wrong with the way I am starting up my processes that might upset the harness in some way?</p>
|
[
{
"answer_id": 183673,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 4,
"selected": false,
"text": "<p><p>Note that you don't test whether <code>fork()</code> failed. You need to make sure <code>$pid</code> is <a href=\"http://perldoc.perl.org/functions/defined.html\" rel=\"nofollow noreferrer\">defined</a> before assuming that \"false\" means \"child.\"\n<p>Because your <code>$cmd</code> contains shell metacharacters (spaces), Perl is actually using a shell when you call <code>exec()</code>. While your monitor is running, there's (1) Perl, (2) a child <code>sh -c</code>, and (3) a grandchild Perl running <code>monitor_real.pl</code>. What that means in particular is when you call <code>KillMonitor</code>, you're only killing the shell (because that's the PID you have) and not the monitor.\n<p>You might also be interested in <a href=\"http://perldoc.perl.org/perlfaq8.html#How-do-I-fork-a-daemon-process%3f\" rel=\"nofollow noreferrer\">How do I fork a daemon process?</a> from the Perl FAQ.</p>\n"
},
{
"answer_id": 184929,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 4,
"selected": true,
"text": "<p>I'm assuming that all your kids have exited before you leave your test? Because otherwise, it may be hanging on to STDERR, which may confuse prove. If you could close STDERR, or at least redirect to a pipe in your parent process, that may be one issue you're having.</p>\n\n<p>Besides that, I'd also point out that you don't need to escape forward slashes, and if you're not using shell metacharacters (spaces are not metacharacters to perl - think \"<code>*?{}()</code>\"), you should be explicit and create a list:</p>\n\n<pre><code>use File::Spec;\nmy @cmd = File::Spec->catfile($basedir,\n File::Spec->updir(),\n qw(bin monitor_real.pl)\n ),\n -config => $config,\n -test =>;\n\nclose STDOUT;\nclose STDERR;\n\nexec (@cmd) or die \"cannot exec test code [@cmd]\\n\";\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3720/"
] |
I have been trying to use the Perl utility/module "prove" as a test harness for some unit tests. The unit tests are a little more "system" than "unit" as I need to fork off some background processes as part of the test, Using the following...
```
sub SpinupMonitor{
my $base_dir = shift;
my $config = shift;
my $pid = fork();
if($pid){
return $pid;
}else{
my $cmd = "$base_dir\/..\/bin\/monitor_real.pl -config $config -test";
close STDOUT;
exec ($cmd) or die "cannot exec test code [$cmd]\n";
}
}
sub KillMonitor{
my $pid = shift;
print "Killing monitor [$pid]\n";
kill(1,$pid);
}
```
However for some reason when I have my .t file spin up some extra processes it causes the test harness to hang at the end of the first .t file after all the tests have finished, rather than going on to the next file, or exiting if there is only one.
At first I wondered if it might be because I was killing of my sub-processes and leaving them defunct. So I added..
```
$SIG{CHLD} = \&REAPER;
sub REAPER {
my $pid = wait;
$SIG{CHLD} = \&REAPER;
}
```
To the code. But that doesn't help. In fact on closed examination it turns out that my perl test file has exited and is now a defunct process and it is the prove wrapper script that has not reaped its child. In fact when I added a die() call at the end of my test script I got...
```
# Looks like your test died just after 7.
```
So my script exited but for some reason the harness isn't unraveling.
I did confirm that it is definitely my sub-processes that are upsetting it as when I disabled them while the tests failed the harness exited properly.
Is there anything I am doing wrong with the way I am starting up my processes that might upset the harness in some way?
|
I'm assuming that all your kids have exited before you leave your test? Because otherwise, it may be hanging on to STDERR, which may confuse prove. If you could close STDERR, or at least redirect to a pipe in your parent process, that may be one issue you're having.
Besides that, I'd also point out that you don't need to escape forward slashes, and if you're not using shell metacharacters (spaces are not metacharacters to perl - think "`*?{}()`"), you should be explicit and create a list:
```
use File::Spec;
my @cmd = File::Spec->catfile($basedir,
File::Spec->updir(),
qw(bin monitor_real.pl)
),
-config => $config,
-test =>;
close STDOUT;
close STDERR;
exec (@cmd) or die "cannot exec test code [@cmd]\n";
```
|
183,567 |
<p>I have a User class which may or may not have an associated Department. This is referenced through the foreign key DepartmentId, and the relevant field in the User table is set to allow nulls.</p>
<p>When I set up my "Create User" form and select no Department, I get a conflict error on SubmitChanges():</p>
<pre><code>The INSERT statement conflicted with the FOREIGN KEY constraint "FK_User_Department".
</code></pre>
<p>How can I convince Linq to SQL to insert a NULL when the "Department" has been selected as the "blank" first option?</p>
<p>Or, perhaps, is there a keyword I am missing for the "optionLabel" parameter of the Html.DropDownList method that does this? I am currently using "None" because using null or "" cause no "blank option" to be displayed, and I suspect that this may be contributing to the problem. Thanks for any assistance.</p>
|
[
{
"answer_id": 183593,
"author": "sepang",
"author_id": 25930,
"author_profile": "https://Stackoverflow.com/users/25930",
"pm_score": 0,
"selected": false,
"text": "<p>You could have an entry \"N/A\" in Department which you assign when no department is selected. Then you wouldn't get a foreign key conflict.</p>\n"
},
{
"answer_id": 183639,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 2,
"selected": true,
"text": "<p>I have found a less-than-desirable solution by putting the following in my <code>UsersController.Create</code> method:</p>\n\n<pre><code>// Snipped UpdateModel call\nif (form[\"User.DepartmentId\"].Length == 0)\n{\n createdUser.DepartmentId = null;\n}\nModels.User.DataContext.SubmitChanges();\n</code></pre>\n\n<p>Of course, I would prefer something that is cleaner / automatic.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
I have a User class which may or may not have an associated Department. This is referenced through the foreign key DepartmentId, and the relevant field in the User table is set to allow nulls.
When I set up my "Create User" form and select no Department, I get a conflict error on SubmitChanges():
```
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_User_Department".
```
How can I convince Linq to SQL to insert a NULL when the "Department" has been selected as the "blank" first option?
Or, perhaps, is there a keyword I am missing for the "optionLabel" parameter of the Html.DropDownList method that does this? I am currently using "None" because using null or "" cause no "blank option" to be displayed, and I suspect that this may be contributing to the problem. Thanks for any assistance.
|
I have found a less-than-desirable solution by putting the following in my `UsersController.Create` method:
```
// Snipped UpdateModel call
if (form["User.DepartmentId"].Length == 0)
{
createdUser.DepartmentId = null;
}
Models.User.DataContext.SubmitChanges();
```
Of course, I would prefer something that is cleaner / automatic.
|
183,578 |
<p>I am trying to install newgem on my linux box (sudo gem install newgem) and i am getting the following error:</p>
<pre><code>Building native extensions. This could take a while...
ERROR: Error installing newgem:
ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb install newgem
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
from extconf.rb:1
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4/ext/redcloth_scan/gem_make.out
</code></pre>
<p>What could the problem be?</p>
|
[
{
"answer_id": 183875,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "<p><code>mkmf</code> is a Ruby module which generates Makefiles. It is supposed to be part of the standard Ruby install, but Debian (and derivatives) split it out into the <code>ruby1.8-dev</code> package.</p>\n\n<p>If you can't find <code>mkmf.rb</code> in any of the directories outputted by <code>ruby -e'print $:.join(\"\\n\")'</code>, then you should figure out what you need to install.</p>\n"
},
{
"answer_id": 399529,
"author": "Dr Nic",
"author_id": 36170,
"author_profile": "https://Stackoverflow.com/users/36170",
"pm_score": 1,
"selected": false,
"text": "<p>Its probably caused by one of its dependencies. I don't think it needs all those dependencies anymore. If its still an issue, raise a bug at <a href=\"http://drnic.lighthouseapp.com/projects/18881-newgem/\" rel=\"nofollow noreferrer\">http://drnic.lighthouseapp.com/projects/18881-newgem/</a> and we'll see what dependencies can be ripped out.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
I am trying to install newgem on my linux box (sudo gem install newgem) and i am getting the following error:
```
Building native extensions. This could take a while...
ERROR: Error installing newgem:
ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb install newgem
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
from extconf.rb:1
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4/ext/redcloth_scan/gem_make.out
```
What could the problem be?
|
`mkmf` is a Ruby module which generates Makefiles. It is supposed to be part of the standard Ruby install, but Debian (and derivatives) split it out into the `ruby1.8-dev` package.
If you can't find `mkmf.rb` in any of the directories outputted by `ruby -e'print $:.join("\n")'`, then you should figure out what you need to install.
|
183,585 |
<p>I'm moving DB from MySQL (used ODBC) to MS SQL and I want to "translate" SQL queries to LINQ. Can someone help me with this (it should SUM Charge column for every location and group result by months):</p>
<pre><code>SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC
</code></pre>
<p>?</p>
<p>Output should look like this:</p>
<pre><code>Location1 | Location2 | Location3 | date
</code></pre>
<p>EDIT:</p>
<p>I tryed to use LINQ sample from here:</p>
<p><a href="https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq">Is it possible to Pivot data using LINQ?</a></p>
<pre><code>var query = context.log_sales
.GroupBy(c => c.OrderTime)
.Select(g => new
{
Date = g.Key,
Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
}).ToList();
</code></pre>
<p>and it is almost what I need. There should be grouping by year too and I don't know how to do this.</p>
|
[
{
"answer_id": 184032,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<p>This might help.</p>\n\n<pre><code>context.log_sales\n.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})\n.Select\n( g => new {\n Date = new DateTime(g.Key.Year, g.Key.Month, 1),\n Location1 = g.Where(s => s.Location == \"Location1\").Sum(s => s.Charge),\n Location2 = g.Where(s => s.Location == \"Location2\").Sum(s => s.Charge),\n Location3 = g.Where(s => s.Location == \"Location3\").Sum(s => s.Charge),\n }\n)\n.OrderBy(x => x.Date);\n</code></pre>\n"
},
{
"answer_id": 186438,
"author": "GrZeCh",
"author_id": 23280,
"author_profile": "https://Stackoverflow.com/users/23280",
"pm_score": 0,
"selected": false,
"text": "<p>.. do You know maybe how to make adding Locations to Select dynamically? For example from List/Array.</p>\n\n<p>EDIT: .. or maybe making Locations to load dynamically and setting which Locations should be loaded in Where statement before Select. Is this possible?</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
] |
I'm moving DB from MySQL (used ODBC) to MS SQL and I want to "translate" SQL queries to LINQ. Can someone help me with this (it should SUM Charge column for every location and group result by months):
```
SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC
```
?
Output should look like this:
```
Location1 | Location2 | Location3 | date
```
EDIT:
I tryed to use LINQ sample from here:
[Is it possible to Pivot data using LINQ?](https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq)
```
var query = context.log_sales
.GroupBy(c => c.OrderTime)
.Select(g => new
{
Date = g.Key,
Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
}).ToList();
```
and it is almost what I need. There should be grouping by year too and I don't know how to do this.
|
This might help.
```
context.log_sales
.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})
.Select
( g => new {
Date = new DateTime(g.Key.Year, g.Key.Month, 1),
Location1 = g.Where(s => s.Location == "Location1").Sum(s => s.Charge),
Location2 = g.Where(s => s.Location == "Location2").Sum(s => s.Charge),
Location3 = g.Where(s => s.Location == "Location3").Sum(s => s.Charge),
}
)
.OrderBy(x => x.Date);
```
|
183,604 |
<p>Let's say I'm writing a Library application for a publishing company who already has a People application.</p>
<p>So in my Library application I have</p>
<pre><code>class Person < ActiveResource::Base
self.site = "http://api.people.mypublisher.com/"
end
</code></pre>
<p>and now I want to store <code>Article</code>s for each <code>Person</code>: </p>
<pre><code>class Article < ActiveRecord::Base
belongs_to :person, :as => :author
end
</code></pre>
<p>I imagine I'd have the following table in my database:</p>
<pre><code>Articles
id (PK) | title (string) | body (text) | author_id (integer)
</code></pre>
<p><code>author_id</code> isn't exactly a Foreign-Key, since I don't have a People table. That leaves several questions:</p>
<ol>
<li><p>how do I tell my <code>Person</code> <code>ActiveResource</code> object that it <code>has_many</code> <code>Articles</code>?</p></li>
<li><p>Will <code>Articles.find(:first).author</code> work? Will <code>belongs_to</code> even work given that there's no <code>ActiveRecord</code> and no backing table?</p></li>
</ol>
|
[
{
"answer_id": 183617,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": false,
"text": "<p>I suppose one possibility for #1, assuming I can get any of it working, is to do this:</p>\n\n<pre><code>class Person < ActiveResource::Base\n self.site = \"http://api.people.mypublisher.com/\"\n\n def articles\n Article.find(:all, :conditions => { :person_id => self.id })\n end\n\n def add_article(article)\n article.person_id = self.id\n end\nend\n</code></pre>\n\n<p>But it loses a <strong>lot</strong> of what <code>has_many</code> offers.</p>\n"
},
{
"answer_id": 1183481,
"author": "cnk",
"author_id": 52325,
"author_profile": "https://Stackoverflow.com/users/52325",
"pm_score": 3,
"selected": true,
"text": "<p>As you point out, you are giving up a lot because ActiveResource does not have associations in the sense that ActiveRecord does. </p>\n\n<p>You have already found the answer to question #1. As for question #2, your ActiveRecord model Article should behave just fine when configured with a \"belongs_to\" association to an ActiveResource model. That is Aritcle.find(:first).author should return the person object you want. </p>\n"
},
{
"answer_id": 3507538,
"author": "dwaynemac",
"author_id": 89063,
"author_profile": "https://Stackoverflow.com/users/89063",
"pm_score": 0,
"selected": false,
"text": "<p>I think a better solution would be making a method that returns a scope.</p>\n\n<pre><code>class Person < ActiveResource::Base\n self.site = ..\n. \n def articles\n Article.for_person(self.id)\n end\nend\n\nclass Article < ActiveRecord::Base\n named_scope :for_person, lambda { |pid| { :conditions => { :person_id => pid }}}\nend\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
Let's say I'm writing a Library application for a publishing company who already has a People application.
So in my Library application I have
```
class Person < ActiveResource::Base
self.site = "http://api.people.mypublisher.com/"
end
```
and now I want to store `Article`s for each `Person`:
```
class Article < ActiveRecord::Base
belongs_to :person, :as => :author
end
```
I imagine I'd have the following table in my database:
```
Articles
id (PK) | title (string) | body (text) | author_id (integer)
```
`author_id` isn't exactly a Foreign-Key, since I don't have a People table. That leaves several questions:
1. how do I tell my `Person` `ActiveResource` object that it `has_many` `Articles`?
2. Will `Articles.find(:first).author` work? Will `belongs_to` even work given that there's no `ActiveRecord` and no backing table?
|
As you point out, you are giving up a lot because ActiveResource does not have associations in the sense that ActiveRecord does.
You have already found the answer to question #1. As for question #2, your ActiveRecord model Article should behave just fine when configured with a "belongs\_to" association to an ActiveResource model. That is Aritcle.find(:first).author should return the person object you want.
|
183,622 |
<p>I need to compare strings in shell:</p>
<pre><code>var1="mtu eth0"
if [ "$var1" == "mtu *" ]
then
# do something
fi
</code></pre>
<p>But obviously the "*" doesn't work in Shell. Is there a way to do it?</p>
|
[
{
"answer_id": 183647,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "<h1><code>bash</code></h1>\n\n<p>Shortest fix:</p>\n\n<pre><code>if [[ \"$var1\" = \"mtu \"* ]]\n</code></pre>\n\n<p>Bash's <code>[[ ]]</code> doesn't get glob-expanded, unlike <code>[ ]</code> (which must, for historical reasons).</p>\n\n<hr>\n\n<h1><code>bash --posix</code></h1>\n\n<p>Oh, I posted too fast. Bourne shell, not Bash...</p>\n\n<pre><code>if [ \"${var1:0:4}\" == \"mtu \" ]\n</code></pre>\n\n<p><code>${var1:0:4}</code> means the first four characters of <code>$var1</code>.</p>\n\n<hr>\n\n<h1><code>/bin/sh</code></h1>\n\n<p>Ah, sorry. Bash's POSIX emulation doesn't go far enough; a true original Bourne shell doesn't have <code>${var1:0:4}</code>. You'll need something like mstrobl's solution.</p>\n\n<pre><code>if [ \"$(echo \"$var1\" | cut -c0-4)\" == \"mtu \" ]\n</code></pre>\n"
},
{
"answer_id": 183650,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 4,
"selected": false,
"text": "<p>Use the Unix tools. The program <code>cut</code> will happily shorten a string. </p>\n\n<pre><code>if [ \"$(echo $var1 | cut -c 4)\" = \"mtu \" ];\n</code></pre>\n\n<p>... should do what you want.</p>\n"
},
{
"answer_id": 183654,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": -1,
"selected": false,
"text": "<p>Or, as an example of the <strong>=~</strong> operator:</p>\n\n<pre><code>if [[ \"$var1\" =~ \"mtu *\" ]]\n</code></pre>\n"
},
{
"answer_id": 183707,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 3,
"selected": false,
"text": "<p>You can call <code>expr</code> to match strings against regular expressions from within Bourne Shell scripts. The below seems to work:</p>\n\n<pre><code>#!/bin/sh\n\nvar1=\"mtu eth0\"\n\nif [ \"`expr \\\"$var1\\\" : \\\"mtu .*\\\"`\" != \"0\" ];then\n echo \"match\"\nfi\n</code></pre>\n"
},
{
"answer_id": 184956,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 2,
"selected": false,
"text": "<p>I'd do the following:</p>\n\n<pre><code># Removes anything but first word from \"var1\"\nif [ \"${var1%% *}\" = \"mtu\" ] ; then ... fi\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code># Tries to remove the first word if it is \"mtu\", checks if we removed anything\nif [ \"${var1#mtu }\" != \"$var1\" ] ; then ... fi\n</code></pre>\n"
},
{
"answer_id": 1663007,
"author": "chris",
"author_id": 201148,
"author_profile": "https://Stackoverflow.com/users/201148",
"pm_score": 2,
"selected": false,
"text": "<p>I like to use the case statement to compare strings.</p>\n\n<p>A trivial example is </p>\n\n<pre><code>case \"$input\"\nin\n \"$variable1\") echo \"matched the first value\" \n ;;\n \"$variable2\") echo \"matched the second value\"\n ;;\n *[a-z]*) echo \"input has letters\" \n ;;\n '') echo \"input is null!\"\n ;;\n *[0-9]*) echo \"matched numbers (but I don't have letters, otherwise the letter test would have been hit first!)\"\n ;;\n *) echo \"Some wacky stuff in the input!\"\nesac\n</code></pre>\n\n<p>I've done crazy things like</p>\n\n<pre><code>case \"$(cat file)\"\nin\n \"$(cat other_file)\") echo \"file and other_file are the same\"\n ;;\n *) echo \"file and other_file are different\"\nesac\n</code></pre>\n\n<p>And that works too, with some limitations, such as the files can't be more than a couple megabytes and the shell simply doesn't see nulls, so if one file is full of nulls and the other has none, (and neither have anything else), this test won't see any difference between the two.</p>\n\n<p>I don't use the file-comparing as a serious example, only an example of how the case statement is capable of doing much more flexible string matching than is available with test or expr or other similar shell expressions.</p>\n"
},
{
"answer_id": 2225794,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>In Bourne shell, if I want to check whether a string contains another string:</p>\n\n<pre><code>if [ `echo ${String} | grep -c ${Substr} ` -eq 1 ] ; then\n</code></pre>\n\n<p>Enclose <code>echo ${String} | grep -c ${Substr}</code> with two <code>`</code> backticks:</p>\n\n<p>To check whether the substring is at the beginning or at the end:</p>\n\n<pre><code>if [ `echo ${String} | grep -c \"^${Substr}\"` -eq 1 ] ; then\n...\nif [ `echo ${String} | grep -c \"${Substr}$\"` -eq 1 ] ; then\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
I need to compare strings in shell:
```
var1="mtu eth0"
if [ "$var1" == "mtu *" ]
then
# do something
fi
```
But obviously the "\*" doesn't work in Shell. Is there a way to do it?
|
`bash`
======
Shortest fix:
```
if [[ "$var1" = "mtu "* ]]
```
Bash's `[[ ]]` doesn't get glob-expanded, unlike `[ ]` (which must, for historical reasons).
---
`bash --posix`
==============
Oh, I posted too fast. Bourne shell, not Bash...
```
if [ "${var1:0:4}" == "mtu " ]
```
`${var1:0:4}` means the first four characters of `$var1`.
---
`/bin/sh`
=========
Ah, sorry. Bash's POSIX emulation doesn't go far enough; a true original Bourne shell doesn't have `${var1:0:4}`. You'll need something like mstrobl's solution.
```
if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]
```
|
183,629 |
<p>It seems like most examples of JPA/Hibernate entity bean classes I've seen do no explicit synchronization. Yet, it is possible to call getters/setters on those objects in the context of building up a transaction. And it's possible for those methods to be called across multiple threads (although maybe that's unusual and weird). </p>
<p>It seems like if it is built up across multiple threads then it's possible for changes to object state to be lost, which would be sad. </p>
<p>So, is leaving out synchronization best practice? Is the Hibernate instrumented code taking care of proper synchronization for me? </p>
<p>As an example:</p>
<pre><code>@Entity
public class Ninja {
@Id @GeneratedValue
private Long id;
@Column
private String name;
@Column
private int throwingStars;
public Ninja() {}
public int getThrowingStars() { return throwingStars; }
public void addThrowingStar() { throwingStars += 1; }
}
</code></pre>
<p>Do the throwing star methods need synchronization? I sure don't want my ninja to lose any throwing stars.</p>
|
[
{
"answer_id": 183979,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "<p>\"And it's possible for those methods to be called across multiple threads (although maybe that's unusual and weird).\"</p>\n\n<p>I can speak for hibernate ONLY since I don't have much experience with JPA.\nThe object on which you call set is NOT always the same object on which you call get. When Hibernate is loading the Object for you, it gets to call the set* methods and then you're(and your threads) calling get the rest of the time. </p>\n\n<p>Again, when you're(i.e, your writer threads) modifying an existing Object and then saving it again, you need to protect access to the object(so that other reader/writer threads don't read dirty data).</p>\n"
},
{
"answer_id": 201083,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 2,
"selected": true,
"text": "<p>The object probably is not the same for the 2 threads. Supposing your threads use a session factory to access the db, the objects you get from the session should be viewed as 'independent' (I believe hibernate creates 'fresh' objects for each get(), unless they are in the session).</p>\n\n<p>As for your stars question, it's the same when two persons fetch the same row from a DB, the DB 'ACID' properties will make sure that each operation is atomic, so if you remove a star from a ninja in Thread t1 and <strong>commit</strong>, Thread t2 will read the committed values of t1. </p>\n\n<p>Alternatively, you can ask hibernate to lock the row of the relevant ninja in T1, so that even if T2 asks for the row it will have to wait until T1 commits or aborts.</p>\n"
},
{
"answer_id": 560870,
"author": "jbandi",
"author_id": 32749,
"author_profile": "https://Stackoverflow.com/users/32749",
"pm_score": 0,
"selected": false,
"text": "<p>JPA/Hibernate entities are POJOs. Hibernate and any JPA-Provider does not change runtime sematics.</p>\n\n<p>So if you would have concurrency issues with a simple POJO, you will also have them with your entity!</p>\n\n<p>In all the Systems I have seen the domain model is not threadsave, entity instances are not accessed by several threads.</p>\n\n<p>However you can have several instances of the same entities concurrently. In this case synchronization is done over the DB. The patterns here are Optimistic and Pessimistic Locking. Hibernate and JPA can help you with the realization of these patterns.</p>\n"
},
{
"answer_id": 682499,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The best practice for your problem is Optimistic Locking:</p>\n\n<p>From the Java Persistence API (JPA) specification (Chapter 3.4.1):</p>\n\n<blockquote>\n <p>Optimistic locking is a technique that\n is used to insure that updates to the\n database data corresponding to the\n state of an entity are made only when\n no intervening transaction has updated\n that data for the entity state since\n the entity state was read. This\n insures that updates or deletes to\n that data are consistent with the\n current state of the database and that\n intervening updates are not lost.</p>\n</blockquote>\n\n<p>You need to add an @Version annotation to your class and a column in the DB table.</p>\n"
},
{
"answer_id": 758091,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion you should NEVER share domains objects across threads. In fact I typically share very little between threads as such data must be protected. I have built some large/high performance systems and have never had to break this rule. If you need to parallelize work then do so but NOT by sharing instances of domain objects. Each thread should read data from the database, operate on it by mutating/creating objects and then commit/rollback the transaction. Work pass in/out should be value/readonly objects generally.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7671/"
] |
It seems like most examples of JPA/Hibernate entity bean classes I've seen do no explicit synchronization. Yet, it is possible to call getters/setters on those objects in the context of building up a transaction. And it's possible for those methods to be called across multiple threads (although maybe that's unusual and weird).
It seems like if it is built up across multiple threads then it's possible for changes to object state to be lost, which would be sad.
So, is leaving out synchronization best practice? Is the Hibernate instrumented code taking care of proper synchronization for me?
As an example:
```
@Entity
public class Ninja {
@Id @GeneratedValue
private Long id;
@Column
private String name;
@Column
private int throwingStars;
public Ninja() {}
public int getThrowingStars() { return throwingStars; }
public void addThrowingStar() { throwingStars += 1; }
}
```
Do the throwing star methods need synchronization? I sure don't want my ninja to lose any throwing stars.
|
The object probably is not the same for the 2 threads. Supposing your threads use a session factory to access the db, the objects you get from the session should be viewed as 'independent' (I believe hibernate creates 'fresh' objects for each get(), unless they are in the session).
As for your stars question, it's the same when two persons fetch the same row from a DB, the DB 'ACID' properties will make sure that each operation is atomic, so if you remove a star from a ninja in Thread t1 and **commit**, Thread t2 will read the committed values of t1.
Alternatively, you can ask hibernate to lock the row of the relevant ninja in T1, so that even if T2 asks for the row it will have to wait until T1 commits or aborts.
|
183,636 |
<p>Is there a way to select manually a node in virtualizing TreeView and then bring it into view?</p>
<p>The data model I'm using with my TreeView is implemented based on the VM-M-V model. Each TreeViewItem's IsSelected property is binded to a corresponing property in ViewModel. I've also created a listener for TreeView's ItemSelected event where I call BringIntoView() for the selected TreeViewItem.</p>
<p>The problem with this approach seems to be that the ItemSelected event won't be raised until the actual TreeViewItem is created. So with the virtualization enabled node selection won't do anything until the TreeView is scrolled enough and then it jumps "magically" to the selected node when the event is finally raised.</p>
<p>I'd really like to use virtualization because I have thousands of nodes in my tree and I've already seen quite impressive performance improvements when the virtualization has been enabled. </p>
|
[
{
"answer_id": 183687,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example taken from an <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a74f22cc-5f82-4070-9f32-c6985dbdead5/\" rel=\"nofollow noreferrer\">MSDN Question</a>\n public void ScrollToItem(int index)</p>\n\n<pre><code> {\n\n Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,\n\n (System.Windows.Threading.DispatcherOperationCallback)delegate(object arg)\n\n {\n\n int N = fileList.Items.Count;\n\n if (N == 0)\n\n return null;\n\n if (index < 0)\n\n {\n\n fileList.ScrollIntoView(fileList.Items[0]); // scroll to first\n\n }\n\n else\n\n {\n\n if (index < N)\n\n {\n\n fileList.ScrollIntoView(fileList.Items[index]); // scroll to item\n\n }\n\n else\n\n {\n\n fileList.ScrollIntoView(fileList.Items[N - 1]); // scroll to last\n\n }\n\n }\n\n return null;\n\n }, null);\n\n }\n</code></pre>\n"
},
{
"answer_id": 1722804,
"author": "user88520",
"author_id": 88520,
"author_profile": "https://Stackoverflow.com/users/88520",
"pm_score": 1,
"selected": false,
"text": "<p>I used an attached property to solve this issue. </p>\n\n<pre><code>public class TreeViewItemBehaviour\n{\n #region IsBroughtIntoViewWhenSelected\n\n public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);\n }\n\n public static void SetIsBroughtIntoViewWhenSelected(\n TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);\n }\n\n public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =\n DependencyProperty.RegisterAttached(\n \"IsBroughtIntoViewWhenSelected\",\n typeof(bool),\n typeof(TreeViewItemBehaviour),\n new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));\n\n static void OnIsBroughtIntoViewWhenSelectedChanged(\n DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n TreeViewItem item = depObj as TreeViewItem;\n if (item == null)\n return;\n\n if (e.NewValue is bool == false)\n return;\n\n if ((bool)e.NewValue)\n {\n item.Loaded += item_Loaded;\n }\n else\n {\n item.Loaded -= item_Loaded;\n }\n }\n\n static void item_Loaded(object sender, RoutedEventArgs e)\n {\n TreeViewItem item = e.OriginalSource as TreeViewItem;\n if (item != null)\n item.BringIntoView();\n }\n\n #endregion // IsBroughtIntoViewWhenSelected\n\n}\n</code></pre>\n\n<p>And in my XAML style for a TreeViewItem, I just set the property to true</p>\n\n<pre><code><Setter Property=\"Behaviours:TreeViewItemBehaviour.IsBroughtIntoViewWhenSelected\" Value=\"True\" />\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 9206992,
"author": "splintor",
"author_id": 46635,
"author_profile": "https://Stackoverflow.com/users/46635",
"pm_score": 4,
"selected": false,
"text": "<p>The link Estifanos Kidane gave is broken. He probably meant <a href=\"http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475\" rel=\"noreferrer\">the \"Changing selection in a virtualized TreeView\" MSDN sample</a>. however, this sample shows how to select a node in a tree, but using code-behind and not MVVM and binding, so it also doesn't handle the missing <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditemchanged.aspx\" rel=\"noreferrer\">SelectedItemChanged event</a> when the bound SelectedItem is changed.</p>\n\n<p>The only solution I can think of is to break the MVVM pattern, and when the ViewModel property that is bound to SelectedItem property changes, get the View and call a code-behind method (similar to the MSDN sample) that makes sure the new value is actually selected in the tree.</p>\n\n<p>Here is the code I wrote to handle it. Suppose your data items are of type <code>Node</code> which has a <code>Parent</code> property:</p>\n\n<pre><code>public class Node\n{\n public Node Parent { get; set; }\n}\n</code></pre>\n\n<p>I wrote the following behavior class:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Interactivity;\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public Node SelectedItem\n {\n get { return (Node)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\"SelectedItem\", typeof(Node), typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var newNode = e.NewValue as Node;\n if (newNode == null) return;\n var behavior = (NodeTreeSelectionBehavior)d;\n var tree = behavior.AssociatedObject;\n\n var nodeDynasty = new List<Node> { newNode };\n var parent = newNode.Parent;\n while (parent != null)\n {\n nodeDynasty.Insert(0, parent);\n parent = parent.Parent;\n }\n\n var currentParent = tree as ItemsControl;\n foreach (var node in nodeDynasty)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475\n // see also the question at http://stackoverflow.com/q/183636/46635\n currentParent.ApplyTemplate();\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName(\"ItemsHost\", currentParent);\n if (itemsPresenter != null)\n {\n itemsPresenter.ApplyTemplate();\n }\n else\n {\n currentParent.UpdateLayout();\n }\n\n var virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel;\n CallEnsureGenerator(virtualizingPanel);\n var index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException(\"Node '\" + node + \"' cannot be fount in container\");\n }\n CallBringIndexIntoView(virtualizingPanel, index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException(\"Tree view item cannot be found or created for node '\" + node + \"'\");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as Node;\n }\n\n #region Functions to get internal members using reflection\n\n // Some functionality we need is hidden in internal members, so we use reflection to get them\n\n #region ItemsControl.ItemsHost\n\n static readonly PropertyInfo ItemsHostPropertyInfo = typeof(ItemsControl).GetProperty(\"ItemsHost\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static Panel GetItemsHost(ItemsControl itemsControl)\n {\n Debug.Assert(itemsControl != null);\n return ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel;\n }\n\n #endregion ItemsControl.ItemsHost\n\n #region Panel.EnsureGenerator\n\n private static readonly MethodInfo EnsureGeneratorMethodInfo = typeof(Panel).GetMethod(\"EnsureGenerator\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallEnsureGenerator(Panel panel)\n {\n Debug.Assert(panel != null);\n EnsureGeneratorMethodInfo.Invoke(panel, null);\n }\n\n #endregion Panel.EnsureGenerator\n\n #region VirtualizingPanel.BringIndexIntoView\n\n private static readonly MethodInfo BringIndexIntoViewMethodInfo = typeof(VirtualizingPanel).GetMethod(\"BringIndexIntoView\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallBringIndexIntoView(VirtualizingPanel virtualizingPanel, int index)\n {\n Debug.Assert(virtualizingPanel != null);\n BringIndexIntoViewMethodInfo.Invoke(virtualizingPanel, new object[] { index });\n }\n\n #endregion VirtualizingPanel.BringIndexIntoView\n\n #endregion Functions to get internal members using reflection\n}\n</code></pre>\n\n<p>With this class, you can write XAML like the following:</p>\n\n<pre><code><UserControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:i=\"clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity\"\n xmlns:local=\"clr-namespace:MyProject\">\n <Grid>\n <TreeView ItemsSource=\"{Binding MyItems}\"\n ScrollViewer.CanContentScroll=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n VirtualizingStackPanel.VirtualizationMode=\"Recycling\">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem=\"{Binding MySelectedItem}\" />\n </i:Interaction.Behaviors>\n </TreeView>\n <Grid>\n<UserControl>\n</code></pre>\n"
},
{
"answer_id": 17883600,
"author": "Heiner",
"author_id": 495910,
"author_profile": "https://Stackoverflow.com/users/495910",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this problem by creating custom controls for <code>TreeView</code>, <code>TreeViewItem</code> and <code>VirtualizingStackPanel</code>.\nA part of the solution is from <a href=\"http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8\" rel=\"nofollow\">http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8</a>.</p>\n\n<p>Each TreeItem (bound item) requires to know its parent (enforced by <code>ITreeItem</code>).</p>\n\n<pre><code>public interface ITreeItem {\n ITreeItem Parent { get; }\n IList<ITreeItem> Children { get; }\n bool IsSelected { get; set; }\n bool IsExpanded { get; set; }\n}\n</code></pre>\n\n<p>When <code>IsSelected</code> is set on any TreeItem the view model is notified and raises an event. The corresponding event listener in the view calls <code>BringItemIntoView</code> on the <code>TreeView</code>.</p>\n\n<p>The <code>TreeView</code> finds all <code>TreeViewItems</code> on the path to the selected item and brings them into view.</p>\n\n<p>And here the rest of the code:</p>\n\n<pre><code>public class SelectableVirtualizingTreeView : TreeView {\n public SelectableVirtualizingTreeView() {\n VirtualizingStackPanel.SetIsVirtualizing(this, true);\n VirtualizingStackPanel.SetVirtualizationMode(this, VirtualizationMode.Recycling);\n var panelfactory = new FrameworkElementFactory(typeof(SelectableVirtualizingStackPanel));\n panelfactory.SetValue(Panel.IsItemsHostProperty, true);\n var template = new ItemsPanelTemplate { VisualTree = panelfactory };\n ItemsPanel = template;\n }\n\n public void BringItemIntoView(ITreeItem treeItemViewModel) {\n if (treeItemViewModel == null) {\n return;\n }\n var stack = new Stack<ITreeItem>();\n stack.Push(treeItemViewModel);\n while (treeItemViewModel.Parent != null) {\n stack.Push(treeItemViewModel.Parent);\n treeItemViewModel = treeItemViewModel.Parent;\n }\n ItemsControl containerControl = this;\n while (stack.Count > 0) {\n var viewModel = stack.Pop();\n var treeViewItem = containerControl.ItemContainerGenerator.ContainerFromItem(viewModel);\n var virtualizingPanel = FindVisualChild<SelectableVirtualizingStackPanel>(containerControl);\n if (virtualizingPanel != null) {\n var index = viewModel.Parent != null ? viewModel.Parent.Children.IndexOf(viewModel) : Items.IndexOf(treeViewItem);\n virtualizingPanel.BringIntoView(index);\n Focus();\n }\n containerControl = (ItemsControl)treeViewItem;\n }\n }\n\n protected override DependencyObject GetContainerForItemOverride() {\n return new SelectableVirtualizingTreeViewItem();\n }\n\n protected override void PrepareContainerForItemOverride(DependencyObject element, object item) {\n base.PrepareContainerForItemOverride(element, item);\n ((TreeViewItem)element).IsExpanded = true;\n }\n\n private static T FindVisualChild<T>(Visual visual) where T : Visual {\n for (var i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) {\n var child = (Visual)VisualTreeHelper.GetChild(visual, i);\n if (child == null) {\n continue;\n }\n var correctlyTyped = child as T;\n if (correctlyTyped != null) {\n return correctlyTyped;\n }\n var descendent = FindVisualChild<T>(child);\n if (descendent != null) {\n return descendent;\n }\n }\n return null;\n }\n}\n\npublic class SelectableVirtualizingTreeViewItem : TreeViewItem {\n public SelectableVirtualizingTreeViewItem() {\n var panelfactory = new FrameworkElementFactory(typeof(SelectableVirtualizingStackPanel));\n panelfactory.SetValue(Panel.IsItemsHostProperty, true);\n var template = new ItemsPanelTemplate { VisualTree = panelfactory };\n ItemsPanel = template;\n SetBinding(IsSelectedProperty, new Binding(\"IsSelected\"));\n SetBinding(IsExpandedProperty, new Binding(\"IsExpanded\"));\n }\n\n protected override DependencyObject GetContainerForItemOverride() {\n return new SelectableVirtualizingTreeViewItem();\n }\n\n protected override void PrepareContainerForItemOverride(DependencyObject element, object item) {\n base.PrepareContainerForItemOverride(element, item);\n ((TreeViewItem)element).IsExpanded = true;\n }\n}\n\npublic class SelectableVirtualizingStackPanel : VirtualizingStackPanel {\n public void BringIntoView(int index) {\n if (index < 0) {\n return;\n }\n BringIndexIntoView(index);\n }\n}\n\npublic abstract class TreeItemBase : ITreeItem {\n protected TreeItemBase() {\n Children = new ObservableCollection<ITreeItem>();\n }\n\n public ITreeItem Parent { get; protected set; }\n\n public IList<ITreeItem> Children { get; protected set; }\n\n public abstract bool IsSelected { get; set; }\n\n public abstract bool IsExpanded { get; set; }\n\n public event EventHandler DescendantSelected;\n\n protected void RaiseDescendantSelected(TreeItemViewModel newItem) {\n if (Parent != null) {\n ((TreeItemViewModel)Parent).RaiseDescendantSelected(newItem);\n } else {\n var handler = DescendantSelected;\n if (handler != null) {\n handler.Invoke(newItem, EventArgs.Empty);\n }\n }\n }\n}\n\npublic class MainViewModel : INotifyPropertyChanged {\n private TreeItemViewModel _selectedItem;\n\n public MainViewModel() {\n TreeItemViewModels = new List<TreeItemViewModel> { new TreeItemViewModel { Name = \"Item\" } };\n for (var i = 0; i < 30; i++) {\n TreeItemViewModels[0].AddChildInitial();\n }\n TreeItemViewModels[0].IsSelected = true;\n TreeItemViewModels[0].DescendantSelected += OnDescendantSelected;\n }\n\n public event EventHandler DescendantSelected;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public List<TreeItemViewModel> TreeItemViewModels { get; private set; }\n\n public TreeItemViewModel SelectedItem {\n get {\n return _selectedItem;\n }\n set {\n if (_selectedItem == value) {\n return;\n }\n _selectedItem = value;\n var handler = PropertyChanged;\n if (handler != null) {\n handler.Invoke(this, new PropertyChangedEventArgs(\"SelectedItem\"));\n }\n }\n }\n\n private void OnDescendantSelected(object sender, EventArgs eventArgs) {\n var handler = DescendantSelected;\n if (handler != null) {\n handler.Invoke(sender, eventArgs);\n }\n }\n}\n\npublic partial class MainWindow {\n public MainWindow() {\n InitializeComponent();\n var mainViewModel = (MainViewModel)DataContext;\n mainViewModel.DescendantSelected += OnMainViewModelDescendantSelected;\n }\n\n private void OnAddButtonClick(object sender, RoutedEventArgs e) {\n var mainViewModel = (MainViewModel)DataContext;\n var treeItemViewModel = mainViewModel.SelectedItem;\n if (treeItemViewModel != null) {\n treeItemViewModel.AddChild();\n }\n }\n\n private void OnMainViewModelDescendantSelected(object sender, EventArgs eventArgs) {\n _treeView.BringItemIntoView(sender as TreeItemViewModel);\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) {\n if (e.OldValue == e.NewValue) {\n return;\n }\n var treeView = (TreeView)sender;\n var treeItemviewModel = treeView.SelectedItem as TreeItemViewModel;\n var mainViewModel = (MainViewModel)DataContext;\n mainViewModel.SelectedItem = treeItemviewModel;\n }\n}\n</code></pre>\n\n<p>And in XAML:</p>\n\n<pre><code><controls:SelectableVirtualizingTreeView x:Name=\"_treeView\" ItemsSource=\"{Binding TreeItemViewModels}\" Margin=\"8\" \n SelectedItemChanged=\"OnTreeViewSelectedItemChanged\">\n <controls:SelectableVirtualizingTreeView.ItemTemplate>\n <HierarchicalDataTemplate ... />\n </controls:SelectableVirtualizingTreeView.ItemTemplate>\n</controls:SelectableVirtualizingTreeView>\n</code></pre>\n"
},
{
"answer_id": 52218467,
"author": "Бадалов Бадал",
"author_id": 8559138,
"author_profile": "https://Stackoverflow.com/users/8559138",
"pm_score": 1,
"selected": false,
"text": "<p>If you used this (<a href=\"https://stackoverflow.com/a/9206992/8559138\">https://stackoverflow.com/a/9206992/8559138</a>) decision and sometimes get InvalidOperationException, you can use my fixed decision:</p>\n\n<p>I update currentParent layout if newParent is null and trying get ContainerFromIndex again.</p>\n\n<pre><code> newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n if (newParent == null)\n {\n currentParent.UpdateLayout();\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n</code></pre>\n\n<p>Full decision:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Interactivity;\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public INode SelectedItem\n {\n get { return (INode)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\"SelectedItem\", typeof(Node), typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var newNode = e.NewValue as INode;\n if (newNode == null) return;\n var behavior = (NodeTreeSelectionBehavior)d;\n var tree = behavior.AssociatedObject;\n\n var nodeDynasty = new List<INode> { newNode };\n var parent = newNode.Parent;\n while (parent != null)\n {\n nodeDynasty.Insert(0, parent);\n parent = parent.Parent;\n }\n\n var currentParent = tree as ItemsControl;\n foreach (var node in nodeDynasty)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n var index = 0;\n VirtualizingPanel virtualizingPanel = null;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475\n // see also the question at http://stackoverflow.com/q/183636/46635\n currentParent.ApplyTemplate();\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName(\"ItemsHost\", currentParent);\n if (itemsPresenter != null)\n {\n itemsPresenter.ApplyTemplate();\n }\n else\n {\n currentParent.UpdateLayout();\n }\n\n virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel;\n CallEnsureGenerator(virtualizingPanel);\n index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException(\"Node '\" + node + \"' cannot be fount in container\");\n }\n if (virtualizingPanel != null)\n {\n virtualizingPanel.BringIndexIntoViewPublic(index);\n }\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n if (newParent == null)\n {\n currentParent.UpdateLayout();\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException(\"Tree view item cannot be found or created for node '\" + node + \"'\");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as INode;\n }\n\n #region Functions to get internal members using reflection\n\n // Some functionality we need is hidden in internal members, so we use reflection to get them\n\n #region ItemsControl.ItemsHost\n\n static readonly PropertyInfo ItemsHostPropertyInfo = typeof(ItemsControl).GetProperty(\"ItemsHost\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static Panel GetItemsHost(ItemsControl itemsControl)\n {\n Debug.Assert(itemsControl != null);\n return ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel;\n }\n\n #endregion ItemsControl.ItemsHost\n\n #region Panel.EnsureGenerator\n\n private static readonly MethodInfo EnsureGeneratorMethodInfo = typeof(Panel).GetMethod(\"EnsureGenerator\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallEnsureGenerator(Panel panel)\n {\n Debug.Assert(panel != null);\n EnsureGeneratorMethodInfo.Invoke(panel, null);\n }\n\n #endregion Panel.EnsureGenerator\n\n #endregion Functions to get internal members using reflection\n}\n</code></pre>\n\n<p>And XAML:</p>\n\n<pre><code><UserControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:i=\"clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity\"\n xmlns:local=\"clr-namespace:MyProject\">\n<Grid>\n <TreeView ItemsSource=\"{Binding MyItems}\"\n ScrollViewer.CanContentScroll=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n VirtualizingStackPanel.VirtualizationMode=\"Recycling\">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem=\"{Binding MySelectedItem}\" />\n </i:Interaction.Behaviors>\n </TreeView>\n<Grid>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 52218926,
"author": "Peregrine",
"author_id": 967885,
"author_profile": "https://Stackoverflow.com/users/967885",
"pm_score": 0,
"selected": false,
"text": "<p>Seeing as there's a new answer recently posted to this question, I'll add my $0.02 into the mix with a MVVM pure solution to this issue.</p>\n\n<p>Given <a href=\"https://github.com/Peregrine66/PeregrinesView/blob/master/library/Peregrine.WPF.ViewModel/perTreeViewItemViewModelBase.cs\" rel=\"nofollow noreferrer\">perTreeViewItemViewModelBase</a> as a base class for treeview item data, you can create a bindable selected item property on the TreeView using an attached property.</p>\n\n<pre><code>public class perTreeViewHelper : Behavior<TreeView>\n{\n public object BoundSelectedItem\n {\n get { return GetValue(BoundSelectedItemProperty); }\n set { SetValue(BoundSelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty BoundSelectedItemProperty =\n DependencyProperty.Register(\"BoundSelectedItem\",\n typeof(object),\n typeof(perTreeViewHelper),\n new FrameworkPropertyMetadata(null,\n FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,\n OnBoundSelectedItemChanged));\n\n private static void OnBoundSelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n var item = args.NewValue as perTreeViewItemViewModelBase;\n\n if (item != null)\n item.IsSelected = true;\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n base.OnDetaching();\n }\n\n private void OnTreeViewSelectedItemChanged(object obj, RoutedPropertyChangedEventArgs<object> args)\n {\n BoundSelectedItem = args.NewValue;\n }\n}\n</code></pre>\n\n<p>A second helper class handles scrolling TreeViewItems into view. There are two distinct cases</p>\n\n<ul>\n<li>when an item is selected</li>\n<li>when an item is expanded, the tree is scrolled to show as many child items as possible</li>\n</ul>\n\n<p>Note the use of dispatcher priority, which ensures that any virtualised items are fully formed before we try to scroll them into view.</p>\n\n<pre><code>public static class perTreeViewItemHelper\n{\n public static bool GetBringSelectedItemIntoView(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(BringSelectedItemIntoViewProperty);\n }\n\n public static void SetBringSelectedItemIntoView(TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(BringSelectedItemIntoViewProperty, value);\n }\n\n public static readonly DependencyProperty BringSelectedItemIntoViewProperty =\n DependencyProperty.RegisterAttached(\n \"BringSelectedItemIntoView\",\n typeof(bool),\n typeof(perTreeViewItemHelper),\n new UIPropertyMetadata(false, BringSelectedItemIntoViewChanged));\n\n private static void BringSelectedItemIntoViewChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n if (!(args.NewValue is bool))\n return;\n\n var item = obj as TreeViewItem;\n\n if (item == null)\n return;\n\n if ((bool)args.NewValue)\n item.Selected += OnTreeViewItemSelected;\n else\n item.Selected -= OnTreeViewItemSelected;\n }\n\n private static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)\n {\n var item = e.OriginalSource as TreeViewItem;\n item?.BringIntoView();\n\n // prevent this event bubbling up to any parent nodes\n e.Handled = true;\n }\n\n public static bool GetBringExpandedChildrenIntoView(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(BringExpandedChildrenIntoViewProperty);\n }\n\n public static void SetBringExpandedChildrenIntoView(TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(BringExpandedChildrenIntoViewProperty, value);\n }\n\n public static readonly DependencyProperty BringExpandedChildrenIntoViewProperty =\n DependencyProperty.RegisterAttached(\n \"BringExpandedChildrenIntoView\",\n typeof(bool),\n typeof(perTreeViewItemHelper),\n new UIPropertyMetadata(false, BringExpandedChildrenIntoViewChanged));\n\n private static void BringExpandedChildrenIntoViewChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n if (!(args.NewValue is bool))\n return;\n\n var item = obj as TreeViewItem;\n\n if (item == null)\n return;\n\n if ((bool)args.NewValue)\n item.Expanded += OnTreeViewItemExpanded;\n else\n item.Expanded -= OnTreeViewItemExpanded;\n }\n\n private static void OnTreeViewItemExpanded(object sender, RoutedEventArgs e)\n {\n var item = e.OriginalSource as TreeViewItem;\n\n if (item == null)\n return;\n\n // use DispatcherPriority.ContextIdle, so that we wait for all of the UI elements for any newly visible children to be created\n\n // first bring the last child into view\n Action action = () =>\n {\n var lastChild = item.ItemContainerGenerator.ContainerFromIndex(item.Items.Count - 1) as TreeViewItem;\n lastChild?.BringIntoView();\n };\n\n item.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);\n\n // then bring the expanded item (back) into view\n action = () => { item.BringIntoView(); };\n item.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);\n\n // prevent this event bubbling up to any parent nodes\n e.Handled = true;\n }\n}\n</code></pre>\n\n<p>This helper class can be included in a style for TreeView controls.</p>\n\n<pre><code><Style x:Key=\"perExpandCollapseToggleStyle\" TargetType=\"ToggleButton\">\n <Setter Property=\"Focusable\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"ToggleButton\">\n <Grid Width=\"10\"\n Height=\"10\"\n Background=\"Transparent\">\n <Path x:Name=\"ExpanderGlyph\"\n Margin=\"1\"\n HorizontalAlignment=\"Left\"\n VerticalAlignment=\"Center\"\n Data=\"M 0,3 L 0,5 L 3,5 L 3,8 L 5,8 L 5,5 L 8,5 L 8,3 L 5,3 L 5,0 L 3,0 L 3,3 z\"\n Fill=\"LightGreen\"\n Stretch=\"None\" />\n </Grid>\n\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsChecked\" Value=\"True\">\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Data\" Value=\"M 0,0 M 8,8 M 0,3 L 0,5 L 8,5 L 8,3 z\" />\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Fill\" Value=\"Red\" />\n </Trigger>\n\n <Trigger Property=\"IsEnabled\" Value=\"False\">\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Fill\" Value=\"{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n\n<Style x:Key=\"perTreeViewItemContainerStyle\"\n TargetType=\"{x:Type TreeViewItem}\">\n\n <!-- Link the properties of perTreeViewItemViewModelBase to the corresponding ones on the TreeViewItem -->\n <Setter Property=\"IsExpanded\" Value=\"{Binding IsExpanded, Mode=TwoWay}\" />\n <Setter Property=\"IsSelected\" Value=\"{Binding IsSelected, Mode=TwoWay}\" />\n <Setter Property=\"IsEnabled\" Value=\"{Binding IsEnabled}\" />\n\n <!-- Include the two \"Scroll into View\" behaviors -->\n <Setter Property=\"vhelp:perTreeViewItemHelper.BringSelectedItemIntoView\" Value=\"True\" />\n <Setter Property=\"vhelp:perTreeViewItemHelper.BringExpandedChildrenIntoView\" Value=\"True\" />\n\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TreeViewItem}\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\"\n MinWidth=\"14\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"*\" />\n </Grid.RowDefinitions>\n <ToggleButton x:Name=\"Expander\"\n Grid.Row=\"0\"\n Grid.Column=\"0\"\n ClickMode=\"Press\"\n IsChecked=\"{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}\"\n Style=\"{StaticResource perExpandCollapseToggleStyle}\" />\n\n <Border x:Name=\"PART_Border\"\n Grid.Row=\"0\"\n Grid.Column=\"1\"\n Padding=\"{TemplateBinding Padding}\"\n Background=\"{TemplateBinding Background}\"\n BorderBrush=\"{TemplateBinding BorderBrush}\"\n BorderThickness=\"{TemplateBinding BorderThickness}\">\n\n <ContentPresenter x:Name=\"PART_Header\"\n Margin=\"0,2\"\n HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\"\n ContentSource=\"Header\" />\n\n </Border>\n\n <ItemsPresenter x:Name=\"ItemsHost\"\n Grid.Row=\"1\"\n Grid.Column=\"1\" />\n </Grid>\n\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsExpanded\" Value=\"false\">\n <Setter TargetName=\"ItemsHost\" Property=\"Visibility\" Value=\"Collapsed\" />\n </Trigger>\n\n <Trigger Property=\"HasItems\" Value=\"false\">\n <Setter TargetName=\"Expander\" Property=\"Visibility\" Value=\"Hidden\" />\n </Trigger>\n\n <!-- Use the same colors for a selected item, whether the TreeView is focussed or not -->\n <Trigger Property=\"IsSelected\" Value=\"true\">\n <Setter TargetName=\"PART_Border\" Property=\"Background\" Value=\"{DynamicResource {x:Static SystemColors.HighlightBrushKey}}\" />\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}\" />\n </Trigger>\n\n <Trigger Property=\"IsEnabled\" Value=\"false\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n\n<Style TargetType=\"{x:Type TreeView}\">\n <Setter Property=\"ItemContainerStyle\" Value=\"{StaticResource perTreeViewItemContainerStyle}\" />\n</Style>\n</code></pre>\n\n<p>I've covered this in more detail in a recent <a href=\"http://peregrinesview.uk/wpf-behaviors-part-2-treeview/\" rel=\"nofollow noreferrer\">blog post</a>.</p>\n"
},
{
"answer_id": 64600450,
"author": "Michel Jansson",
"author_id": 1807542,
"author_profile": "https://Stackoverflow.com/users/1807542",
"pm_score": 0,
"selected": false,
"text": "<p>An update of <a href=\"https://stackoverflow.com/a/9206992/1807542\">@splintor's excellent answer</a>, using some modern C# features, and does without any reflection.</p>\n<pre><code>public class Node\n{\n public Node Parent { get; set; }\n}\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public Node SelectedItem\n {\n get { return (Node)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\n "SelectedItem",\n typeof(Node),\n typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(e.NewValue is Node newNode)) return;\n\n var treeView = ((NodeTreeSelectionBehavior)d).AssociatedObject;\n\n var ancestors = new List<Node> { newNode };\n var parent = newNode;\n while ((parent = parent.Parent) != null)\n {\n ancestors.Insert(0, parent);\n }\n\n var currentParent = treeView as ItemsControl;\n foreach (var node in ancestors)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // see also the question at http://stackoverflow.com/q/183636/46635\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName("ItemsHost", currentParent);\n var virtualizingPanel = (VirtualizingPanel)VisualTreeHelper.GetChild(itemsPresenter, 0);\n var index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException("Node '" + node + "' cannot be fount in container");\n }\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException("Tree view item cannot be found or created for node '" + node + "'");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as Node;\n }\n}\n</code></pre>\n<p>Used in the same way:</p>\n<pre><code><UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"\n xmlns:local="clr-namespace:MyProject">\n <Grid>\n <TreeView ItemsSource="{Binding MyItems}"\n ScrollViewer.CanContentScroll="True"\n VirtualizingStackPanel.IsVirtualizing="True"\n VirtualizingStackPanel.VirtualizationMode="Recycling">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem="{Binding MySelectedItem}" />\n </i:Interaction.Behaviors>\n </TreeView>\n <Grid>\n<UserControl>\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19982/"
] |
Is there a way to select manually a node in virtualizing TreeView and then bring it into view?
The data model I'm using with my TreeView is implemented based on the VM-M-V model. Each TreeViewItem's IsSelected property is binded to a corresponing property in ViewModel. I've also created a listener for TreeView's ItemSelected event where I call BringIntoView() for the selected TreeViewItem.
The problem with this approach seems to be that the ItemSelected event won't be raised until the actual TreeViewItem is created. So with the virtualization enabled node selection won't do anything until the TreeView is scrolled enough and then it jumps "magically" to the selected node when the event is finally raised.
I'd really like to use virtualization because I have thousands of nodes in my tree and I've already seen quite impressive performance improvements when the virtualization has been enabled.
|
The link Estifanos Kidane gave is broken. He probably meant [the "Changing selection in a virtualized TreeView" MSDN sample](http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475). however, this sample shows how to select a node in a tree, but using code-behind and not MVVM and binding, so it also doesn't handle the missing [SelectedItemChanged event](http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditemchanged.aspx) when the bound SelectedItem is changed.
The only solution I can think of is to break the MVVM pattern, and when the ViewModel property that is bound to SelectedItem property changes, get the View and call a code-behind method (similar to the MSDN sample) that makes sure the new value is actually selected in the tree.
Here is the code I wrote to handle it. Suppose your data items are of type `Node` which has a `Parent` property:
```
public class Node
{
public Node Parent { get; set; }
}
```
I wrote the following behavior class:
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
public class NodeTreeSelectionBehavior : Behavior<TreeView>
{
public Node SelectedItem
{
get { return (Node)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(Node), typeof(NodeTreeSelectionBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var newNode = e.NewValue as Node;
if (newNode == null) return;
var behavior = (NodeTreeSelectionBehavior)d;
var tree = behavior.AssociatedObject;
var nodeDynasty = new List<Node> { newNode };
var parent = newNode.Parent;
while (parent != null)
{
nodeDynasty.Insert(0, parent);
parent = parent.Parent;
}
var currentParent = tree as ItemsControl;
foreach (var node in nodeDynasty)
{
// first try the easy way
var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;
if (newParent == null)
{
// if this failed, it's probably because of virtualization, and we will have to do it the hard way.
// this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475
// see also the question at http://stackoverflow.com/q/183636/46635
currentParent.ApplyTemplate();
var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName("ItemsHost", currentParent);
if (itemsPresenter != null)
{
itemsPresenter.ApplyTemplate();
}
else
{
currentParent.UpdateLayout();
}
var virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel;
CallEnsureGenerator(virtualizingPanel);
var index = currentParent.Items.IndexOf(node);
if (index < 0)
{
throw new InvalidOperationException("Node '" + node + "' cannot be fount in container");
}
CallBringIndexIntoView(virtualizingPanel, index);
newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;
}
if (newParent == null)
{
throw new InvalidOperationException("Tree view item cannot be found or created for node '" + node + "'");
}
if (node == newNode)
{
newParent.IsSelected = true;
newParent.BringIntoView();
break;
}
newParent.IsExpanded = true;
currentParent = newParent;
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
}
private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
SelectedItem = e.NewValue as Node;
}
#region Functions to get internal members using reflection
// Some functionality we need is hidden in internal members, so we use reflection to get them
#region ItemsControl.ItemsHost
static readonly PropertyInfo ItemsHostPropertyInfo = typeof(ItemsControl).GetProperty("ItemsHost", BindingFlags.Instance | BindingFlags.NonPublic);
private static Panel GetItemsHost(ItemsControl itemsControl)
{
Debug.Assert(itemsControl != null);
return ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel;
}
#endregion ItemsControl.ItemsHost
#region Panel.EnsureGenerator
private static readonly MethodInfo EnsureGeneratorMethodInfo = typeof(Panel).GetMethod("EnsureGenerator", BindingFlags.Instance | BindingFlags.NonPublic);
private static void CallEnsureGenerator(Panel panel)
{
Debug.Assert(panel != null);
EnsureGeneratorMethodInfo.Invoke(panel, null);
}
#endregion Panel.EnsureGenerator
#region VirtualizingPanel.BringIndexIntoView
private static readonly MethodInfo BringIndexIntoViewMethodInfo = typeof(VirtualizingPanel).GetMethod("BringIndexIntoView", BindingFlags.Instance | BindingFlags.NonPublic);
private static void CallBringIndexIntoView(VirtualizingPanel virtualizingPanel, int index)
{
Debug.Assert(virtualizingPanel != null);
BringIndexIntoViewMethodInfo.Invoke(virtualizingPanel, new object[] { index });
}
#endregion VirtualizingPanel.BringIndexIntoView
#endregion Functions to get internal members using reflection
}
```
With this class, you can write XAML like the following:
```
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:MyProject">
<Grid>
<TreeView ItemsSource="{Binding MyItems}"
ScrollViewer.CanContentScroll="True"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<i:Interaction.Behaviors>
<local:NodeTreeSelectionBehavior SelectedItem="{Binding MySelectedItem}" />
</i:Interaction.Behaviors>
</TreeView>
<Grid>
<UserControl>
```
|
183,638 |
<p>I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change!</p>
<pre><code>print("$('.ajaxdropdown').change(function(){
$.ajax({
type: "GET",
url: "/includes/html/gsm-tariff.php",
data: "c_name="+escape($(this).val()),
success: function(html){
$("#charges-gsm").html(html);
//i want to fade result into these 2 divs...
$("#charges-gsm-faq").html(html);
$("#charges-gsm-prices").html(html);
}
});
});");
</code></pre>
<p>I've tried appending the fadein method and a few other things, but no joy.</p>
|
[
{
"answer_id": 183644,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 7,
"selected": true,
"text": "<p>You'll have to <code>hide()</code> it before you can use <code>fadeIn()</code>.</p>\n\n<p><strong>UPDATE:</strong> Here's how you'd do this by chaining:</p>\n\n<pre><code>$(\"#charges-gsm-faq\").hide().html(html).fadeIn();\n$(\"#charges-gsm-prices\").hide().html(html).fadeIn();\n</code></pre>\n"
},
{
"answer_id": 183755,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>You could also leave it visible and just make it transparent, and then fade it to full opacity, using:</p>\n\n<pre><code>... .css({ opacity: 0 }).fadeTo(\"normal\",1);\n</code></pre>\n"
},
{
"answer_id": 279364,
"author": "Malfist",
"author_id": 12243,
"author_profile": "https://Stackoverflow.com/users/12243",
"pm_score": 0,
"selected": false,
"text": "<p>JQuery.ui has a bunch of different things you can do with effects. You can find them here: <a href=\"http://docs.jquery.com/Effects\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Effects</a> </p>\n"
},
{
"answer_id": 4722731,
"author": "kingr",
"author_id": 518668,
"author_profile": "https://Stackoverflow.com/users/518668",
"pm_score": 2,
"selected": false,
"text": "<p>You'll have to hide() it before you can use fadeIn()</p>\n\n<p>Above worked for me</p>\n"
},
{
"answer_id": 28162084,
"author": "Brynner Ferreira",
"author_id": 548727,
"author_profile": "https://Stackoverflow.com/users/548727",
"pm_score": 1,
"selected": false,
"text": "<p>It works with load(): </p>\n\n<pre><code>$('.element').load('file.html').hide().fadeIn();\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change!
```
print("$('.ajaxdropdown').change(function(){
$.ajax({
type: "GET",
url: "/includes/html/gsm-tariff.php",
data: "c_name="+escape($(this).val()),
success: function(html){
$("#charges-gsm").html(html);
//i want to fade result into these 2 divs...
$("#charges-gsm-faq").html(html);
$("#charges-gsm-prices").html(html);
}
});
});");
```
I've tried appending the fadein method and a few other things, but no joy.
|
You'll have to `hide()` it before you can use `fadeIn()`.
**UPDATE:** Here's how you'd do this by chaining:
```
$("#charges-gsm-faq").hide().html(html).fadeIn();
$("#charges-gsm-prices").hide().html(html).fadeIn();
```
|
183,642 |
<pre><code>select distinct constraint_type from user_constraints;
C
-
C
P
R
U
</code></pre>
<p>Seems P means primary key and R means foreign key, correct? What are U and C? </p>
|
[
{
"answer_id": 183664,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 7,
"selected": true,
"text": "<pre><code>Code Description Acts On Level\n---------------------------------------------\nC Check on a table Column\nO Read Only on a view Object\nP Primary Key Object\nR Referential (Foreign Key) Column\nU Unique Key Column\nV Check Option on a view Object\n</code></pre>\n"
},
{
"answer_id": 3552727,
"author": "user428974",
"author_id": 428974,
"author_profile": "https://Stackoverflow.com/users/428974",
"pm_score": 6,
"selected": false,
"text": "<p>From the <a href=\"https://docs.oracle.com/database/121/REFRN/GUID-9C96DA92-CFE0-4A3F-9061-C5ED17B43EFE.htm\" rel=\"noreferrer\">12cR1 documentation</a>:</p>\n\n<pre><code>C - Check constraint on a table \nP - Primary key \nU - Unique key \nR - Referential integrity \nV - With check option, on a view \nO - With read only, on a view \nH - Hash expression \nF - Constraint that involves a REF column \nS - Supplemental logging\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
```
select distinct constraint_type from user_constraints;
C
-
C
P
R
U
```
Seems P means primary key and R means foreign key, correct? What are U and C?
|
```
Code Description Acts On Level
---------------------------------------------
C Check on a table Column
O Read Only on a view Object
P Primary Key Object
R Referential (Foreign Key) Column
U Unique Key Column
V Check Option on a view Object
```
|
183,675 |
<p>my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known db systems.
My Firebird is 1.5 and dialect 3 (not sure what it means).
So maybe someone could help me with a algorithm example.</p>
|
[
{
"answer_id": 184142,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p>The following procedure does what you describe:</p>\n\n<pre><code>SET TERM !!;\nCREATE PROCEDURE concat_names\n RETURNS (concat VARCHAR(2000))\nAS\nDECLARE VARIABLE name VARCHAR(100);\nBEGIN\n concat = '';\n FOR SELECT first_name || ' ' || last_name FROM employee INTO :name\n DO BEGIN\n concat = concat || name || ', ';\n END\nEND!!\nSET TERM ;!!\nEXECUTE PROCEDURE concat_names;\n</code></pre>\n\n<p>But I question the wisdom of this solution. How do you know the VARCHAR is long enough for all the rows in your desired dataset?</p>\n\n<p>It's far easier and safer to run a query to return the result to an application row by row. Every application programming language has methods to concatenate strings, but more importantly they have more flexible methods to manage the growth of data.</p>\n\n<p>By the way, \"dialect\" in Firebird and InterBase refers to a compatibility mode that was introduced so that applications developed for InterBase 5.x can work with later versions of InterBase and Firebird. That was almost ten years ago, and AFAIK there's no need today to use anything lower than dialect 3.</p>\n"
},
{
"answer_id": 185930,
"author": "Attila Szasz",
"author_id": 15089,
"author_profile": "https://Stackoverflow.com/users/15089",
"pm_score": 0,
"selected": false,
"text": "<p>You have to test for null values when concatenating, here is an example for two fields and a separator between them:</p>\n\n<pre><code> CREATE PROCEDURE CONCAT(\n F1 VARCHAR(385),\n F2 VARCHAR(385),\n SEPARATOR VARCHAR(10))\nRETURNS (\n RESULT VARCHAR(780))\nAS\nbegin\n\n if ((:f1 is not null) and (:f1 <> '')) then\n result = :f1;\n\n if ((:f2 is not null) and (:f2 <> '')) then\n if ((result is not null) and (result <> '')) then\n begin\n if ((:separator is not null) and (separator <> '')) then\n result = result||separator||f2;\n else\n result = result||f2;\n end\n else\n result = f2;\n\n suspend;\nend\n</code></pre>\n"
},
{
"answer_id": 12208149,
"author": "Adamson",
"author_id": 1637559,
"author_profile": "https://Stackoverflow.com/users/1637559",
"pm_score": 0,
"selected": false,
"text": "<p>Returning multiple rows using Firebird stored procedures is very very easy.</p>\n\n<p>Don't use:</p>\n\n<pre><code>execute procedure proc_name(value);\n</code></pre>\n\n<p>Instead use the:</p>\n\n<pre><code>select * from proc_name(value);\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26207/"
] |
my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some\_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known db systems.
My Firebird is 1.5 and dialect 3 (not sure what it means).
So maybe someone could help me with a algorithm example.
|
The following procedure does what you describe:
```
SET TERM !!;
CREATE PROCEDURE concat_names
RETURNS (concat VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(100);
BEGIN
concat = '';
FOR SELECT first_name || ' ' || last_name FROM employee INTO :name
DO BEGIN
concat = concat || name || ', ';
END
END!!
SET TERM ;!!
EXECUTE PROCEDURE concat_names;
```
But I question the wisdom of this solution. How do you know the VARCHAR is long enough for all the rows in your desired dataset?
It's far easier and safer to run a query to return the result to an application row by row. Every application programming language has methods to concatenate strings, but more importantly they have more flexible methods to manage the growth of data.
By the way, "dialect" in Firebird and InterBase refers to a compatibility mode that was introduced so that applications developed for InterBase 5.x can work with later versions of InterBase and Firebird. That was almost ten years ago, and AFAIK there's no need today to use anything lower than dialect 3.
|
183,686 |
<p>Whenever I restore a backup of my database in SQL Server I am presented with the following error:</p>
<pre><code>Msg 3101, Level 16, State 1, Line 1
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
</code></pre>
<p>Usually to get around this I just restart the server. This was fine when we were developing on our local instance on our development machines. But we have a few programmers that need to access the database, and the logistics of having everyone script their changes and drop them into <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow noreferrer">Subversion</a> was becoming a nightmare. Regardless our simple solution was to put it on a shared server in the office and backup the server occasionally in case someone screwed up the data.</p>
<p>Well, I screwed up the data and needed to restore. Unfortunately, I have another co-worker in the office who is working on another project and is using the same database server for development. To be nice I'd like to restore without restarting the SQL Server and possibly disrupting his work.</p>
<p>Is there a way to script in T-SQL to be able to take exclusive access or to drop all connections?</p>
|
[
{
"answer_id": 183734,
"author": "Bravax",
"author_id": 13911,
"author_profile": "https://Stackoverflow.com/users/13911",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest talking to your co-worker, and asking him to leave the database. (And make him aware of the problem, because he might lose changes he's made when you restore.)</p>\n\n<p>That's far better than dropping his connections, or setting exclusive access which might cause him some inconvenience.</p>\n"
},
{
"answer_id": 183743,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 2,
"selected": false,
"text": "<p>So far this worked for me. I right clicked on the database > Tasks > Detach...</p>\n\n<p>This brought up a screen that allows you to view all active connections. You can then go through and disconnect each connection. When you hit ok you've detached the database and need to Attach the database. Right-click on Databases and choose attach, pick you mdf file and the db is attached. At this point you should have exclusive access to restore.</p>\n\n<p><strong>Note:</strong> I tested this by connecting to one of his databases from my local machine and from the server dropped the connections to my database and I didn't lose my connection to his database.</p>\n"
},
{
"answer_id": 183744,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 1,
"selected": false,
"text": "<p>Well, you can kill SQL processes and sessions with <a href=\"http://msdn.microsoft.com/en-us/library/ms173730.aspx\" rel=\"nofollow noreferrer\">KILL</a>.</p>\n\n<p>But if you just drop all his current connections, won't he just reopen them?</p>\n\n<p>You probably just have to go tell him you're going to restore from a backup so he stops connecting for a bit.</p>\n"
},
{
"answer_id": 183754,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 5,
"selected": true,
"text": "<p>You can force the database offline and drop connections with:</p>\n\n<pre><code>EXEC sp_dboption N'yourDatabase', N'offline', N'true'\n</code></pre>\n\n<p>Or you can</p>\n\n<pre><code>ALTER DATABASE [yourDatabase] SET OFFLINE WITH\nROLLBACK AFTER 60 SECONDS\n</code></pre>\n\n<p>Rollback specifies if anything is executing. After that period they will be rolled back. So it provides some protection.</p>\n\n<p>Sorry I wasn't thinking/reading right. You could bing back online and backup. There was also a post on Stack Overflow on a <a href=\"http://en.wikipedia.org/wiki/Transact-SQL\" rel=\"nofollow noreferrer\">T-SQL</a> snippet for dropping all connections rather than binging offline first: <em><a href=\"https://stackoverflow.com/questions/121243/hidden-features-of-sql-server#121927\">Hidden Features of SQL Server</a></em></p>\n"
},
{
"answer_id": 183855,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>First, you cannot restore a database unless you are the only person currently connected and you have administrator rights. You must first tell your co-worker that you need to restore and ask him or her to be sure to script out any changes that might not be on the backup media. This is only polite and keeps co-workers from killing you. </p>\n\n<p>Next you set the database to single-user mode. You can look up how to do this in Books Online. This prevents anyone else from connecting while you are doing this and gives you a chance to kill existing connections. It is important to go to single-user mode, because no one else should be doing anything to the database while you restore.</p>\n\n<p>Then you run the restore process.</p>\n"
},
{
"answer_id": 183938,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 3,
"selected": false,
"text": "<p>@mattlant - that's what I was looking for. I bring it over here so it's in the thread. </p>\n\n<pre><code>Use Master\nGo\n\nDeclare @dbname sysname\n\nSet @dbname = 'name of database you want to drop connections from'\n\nDeclare @spid int\nSelect @spid = min(spid) from master.dbo.sysprocesses\nwhere dbid = db_id(@dbname)\nWhile @spid Is Not Null\nBegin\n Execute ('Kill ' + @spid)\n Select @spid = min(spid) from master.dbo.sysprocesses\n where dbid = db_id(@dbname) and spid > @spid\nEnd\n</code></pre>\n"
},
{
"answer_id": 881280,
"author": "Precipitous",
"author_id": 77784,
"author_profile": "https://Stackoverflow.com/users/77784",
"pm_score": 4,
"selected": false,
"text": "<p>I find this vastly faster and generally better than taking offline. Do read about it in <a href=\"http://msdn.microsoft.com/en-us/library/bb522682.aspx\" rel=\"noreferrer\">MSDN</a> so you understand the caveats. If using aysnc statistics, you have to turn those off, as well.</p>\n\n<pre><code>-- set single user, terminate connections\nALTER DATABASE [target] SET SINGLE_USER WITH ROLLBACK IMMEDIATE\nRESTORE ...\nALTER DATABASE [target] SET MULTI_USER\n</code></pre>\n\n<p>The \"with rollback immediate\" is the essential \"termination\" clause. Leaving it out waits forever. A nicer version of the above gives user transactions a few seconds to terminate.</p>\n\n<pre><code>ALTER DATABASE [target] SET SINGLE_USER WITH ROLLBACK AFTER 5\n</code></pre>\n\n<p>Offline is a good idea if you want to copy database files around, a scenario that can be handy in desktop editions of SQL. Too heavy for this scenario. If offline, this would be preferred. <a href=\"http://msdn.microsoft.com/en-us/library/ms187310.aspx\" rel=\"noreferrer\">SQL is moving away from sp_dboption</a>. </p>\n\n<pre><code>ALTER DATABASE [target] SET OFFLINE WITH ROLLBACK AFTER 5\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
] |
Whenever I restore a backup of my database in SQL Server I am presented with the following error:
```
Msg 3101, Level 16, State 1, Line 1
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
```
Usually to get around this I just restart the server. This was fine when we were developing on our local instance on our development machines. But we have a few programmers that need to access the database, and the logistics of having everyone script their changes and drop them into [Subversion](http://en.wikipedia.org/wiki/Apache_Subversion) was becoming a nightmare. Regardless our simple solution was to put it on a shared server in the office and backup the server occasionally in case someone screwed up the data.
Well, I screwed up the data and needed to restore. Unfortunately, I have another co-worker in the office who is working on another project and is using the same database server for development. To be nice I'd like to restore without restarting the SQL Server and possibly disrupting his work.
Is there a way to script in T-SQL to be able to take exclusive access or to drop all connections?
|
You can force the database offline and drop connections with:
```
EXEC sp_dboption N'yourDatabase', N'offline', N'true'
```
Or you can
```
ALTER DATABASE [yourDatabase] SET OFFLINE WITH
ROLLBACK AFTER 60 SECONDS
```
Rollback specifies if anything is executing. After that period they will be rolled back. So it provides some protection.
Sorry I wasn't thinking/reading right. You could bing back online and backup. There was also a post on Stack Overflow on a [T-SQL](http://en.wikipedia.org/wiki/Transact-SQL) snippet for dropping all connections rather than binging offline first: *[Hidden Features of SQL Server](https://stackoverflow.com/questions/121243/hidden-features-of-sql-server#121927)*
|
183,698 |
<p>I'm using DB2, although a solution using any flavor of SQL would likely be easy enough for me to convert.</p>
<p>I didn't design this database, or the application that uses the database. I haven't the power to change this application, how it works, or the data. Because it defies what I consider to be conventional use of a start and an end date, I am struggling with writing something as simple as a select for a specific point in time.</p>
<p>Here are the relevant/edited parts of the table:</p>
<pre><code>OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1001 500 1/1/1980 5/1/2000 Really Old Name
1002 500 1/1/1980 1/1/2006 Old Name
1003 500 1/1/1980 null Current Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
</code></pre>
<p>What I want to return, are the records which are valid for 7/1/2005:</p>
<pre><code>OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1002 500 1/1/1980 1/1/2006 Old Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
</code></pre>
<p>I'm trying to avoid subselects, but understand they may be necessary. If I do need a subselect, I'd like to keep it limited to one. Looking between the start and end date doesn't work, because it doesn't return facilities which have only one record with a null end date. Adding an OR condition to include end dates which are null may return more than one record in some cases. This problem seems so simple on the service, that I must be missing a ridiculously obvious solution. Does anyone have any ideas?</p>
|
[
{
"answer_id": 183718,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 2,
"selected": false,
"text": "<p>would this work:</p>\n\n<pre><code>SELECT * FROM table_name\nWHERE START_DATE < '7/1/2005' AND (END_DATE > '7/1/2005' OR END_DATE IS NULL);\n</code></pre>\n"
},
{
"answer_id": 183720,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>The trick is to coalesce the end date to the next day, :) Coalesce basically replaces a null value with the second parameter. Pretty cool little trick.</p>\n\n<pre><code>select * from TAble where START_DATE < @DATE and Coalesce(END_DATE, @DATE+1) > @DATE\n</code></pre>\n"
},
{
"answer_id": 183732,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>From what you've given us, this is what you want:</p>\n\n<pre><code>select * from facitities\nwhere START_DATE <= @my_date and (@mydate <= END_DATE or END_DATE is null)\n</code></pre>\n\n<p>however, I suspect you knew that, and want something different, in which case, you'll have to be more specific about what's wrong with the data.</p>\n"
},
{
"answer_id": 183762,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>Take 2:</p>\n\n<pre><code>select OBJECTID, FACILITY_ID, START_DATE, FACILITY_NAME, MIN(END_DATE) as END_DATE\nfrom facitities\nwhere START_DATE <= @my_date and (@mydate <= END_DATE or END_DATE is null)\ngroup by OBJECTID, FACILITY_ID, START_DATE, FACILITY_NAME\n</code></pre>\n"
},
{
"answer_id": 184267,
"author": "srclontz",
"author_id": 4606,
"author_profile": "https://Stackoverflow.com/users/4606",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry to answer my own question. Thanks all, the answers given were very helpful. It was also helpful to think about exactly what I was trying to accomplish. Combining concepts from the answers that were given, I was able to come up with something that seems to work:</p>\n\n<pre><code>SELECT \n * \nFROM \n FACILITY_TABLE\nWHERE \n (END_DATE IS NULL\n AND OBJECTID NOT IN \n (SELECT A.OBJECTID FROM FACILITY_TABLE A \n WHERE '7/1/2005' BETWEEN A.BEGINDATE AND A.ENDDATE))\n OR \n '7/1/2005' BETWEEN FACILITY_TABLE.START_DATE AND FACILITY_TABLE.ENDDATE\n</code></pre>\n\n<p>Since the start date was made meaningless by the data, I didn't include it. The returns only the records that were valid back in 7/1/2005 without also including the current record if a record was expired between now and then.</p>\n"
},
{
"answer_id": 391688,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Slight variation on the above:</p>\n\n<pre><code>select * from facilities\nwhere @my_date between START_DATE AND COALESCE(END_DATE, CURRENT DATE)\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606/"
] |
I'm using DB2, although a solution using any flavor of SQL would likely be easy enough for me to convert.
I didn't design this database, or the application that uses the database. I haven't the power to change this application, how it works, or the data. Because it defies what I consider to be conventional use of a start and an end date, I am struggling with writing something as simple as a select for a specific point in time.
Here are the relevant/edited parts of the table:
```
OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1001 500 1/1/1980 5/1/2000 Really Old Name
1002 500 1/1/1980 1/1/2006 Old Name
1003 500 1/1/1980 null Current Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
```
What I want to return, are the records which are valid for 7/1/2005:
```
OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1002 500 1/1/1980 1/1/2006 Old Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
```
I'm trying to avoid subselects, but understand they may be necessary. If I do need a subselect, I'd like to keep it limited to one. Looking between the start and end date doesn't work, because it doesn't return facilities which have only one record with a null end date. Adding an OR condition to include end dates which are null may return more than one record in some cases. This problem seems so simple on the service, that I must be missing a ridiculously obvious solution. Does anyone have any ideas?
|
would this work:
```
SELECT * FROM table_name
WHERE START_DATE < '7/1/2005' AND (END_DATE > '7/1/2005' OR END_DATE IS NULL);
```
|
183,702 |
<p>Something like</p>
<pre><code>var life= {
users : {
guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); },
girls : function(){ this.SOMETHING.kiss(this.boys); },
},
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
</code></pre>
<p>this.SOMETHING is what I imagine the format is, but it might not be. What will step back up to the parent of an object?</p>
|
[
{
"answer_id": 183731,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.</p>\n"
},
{
"answer_id": 183737,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": false,
"text": "<p>In this case, you could use <code>life</code> to reference the parent object. Or you could store a reference to <code>life</code> in the users object. There can't be a fixed <code>parent</code> available to you in the language, because users is just a reference to an object, and there could be other references...</p>\n\n<pre><code>var death = { residents : life.users };\nlife.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };\n// death.residents.smallFurryCreaturesFromAlphaCentauri now exists\n// - because life.users references the same object as death.residents!\n</code></pre>\n\n<p>You might find it helpful to use something like this:</p>\n\n<pre><code>function addChild(ob, childName, childOb)\n{\n ob[childName] = childOb;\n childOb.parent = ob;\n}\n\nvar life= {\n mameAndDestroy : function(group){ },\n kiss : function(group){ }\n};\n\naddChild(life, 'users', {\n guys : function(){ this.parent.mameAndDestroy(this.girls); },\n girls : function(){ this.parent.kiss(this.boys); },\n });\n\n// life.users.parent now exists and points to life\n</code></pre>\n"
},
{
"answer_id": 184536,
"author": "harley.333",
"author_id": 26259,
"author_profile": "https://Stackoverflow.com/users/26259",
"pm_score": 7,
"selected": true,
"text": "<p>JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example:</p>\n\n<pre><code>var Bobby = {name: \"Bobby\"};\nvar Dad = {name: \"Dad\", children: [ Bobby ]};\nvar Mom = {name: \"Mom\", children: [ Bobby ]};\n</code></pre>\n\n<p>Who does Bobby belong to?</p>\n"
},
{
"answer_id": 1949628,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 2,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>var life={\n users:{\n guys:function(){ life.mameAndDestroy(life.users.girls); },\n girls:function(){ life.kiss(life.users.guys); }\n },\n mameAndDestroy : function(group){ \n alert(\"mameAndDestroy\");\n group();\n },\n kiss : function(group){\n alert(\"kiss\");\n //could call group() here, but would result in infinite loop\n }\n};\n\nlife.users.guys();\nlife.users.girls();\n</code></pre>\n\n<p>Also, make sure you don't have a comma after the \"girls\" definition. This will cause the script to crash in IE (any time you have a comma after the last item in an array in IE it dies).</p>\n\n<p><a href=\"http://jsbin.com/icoga/edit\" rel=\"nofollow noreferrer\">See it run</a></p>\n"
},
{
"answer_id": 3861917,
"author": "jazkat",
"author_id": 318380,
"author_profile": "https://Stackoverflow.com/users/318380",
"pm_score": 6,
"selected": false,
"text": "<p>I simply added in first function </p>\n\n<pre><code>parentThis = this;\n</code></pre>\n\n<p>and use parentThis in subfunction. Why? Because in JavaScript, objects are soft. A new member can be added to a soft object by simple assignment (not like ie. Java where classical objects are hard. The only way to add a new member to a hard object is to create a new class) More on this here: <a href=\"http://www.crockford.com/javascript/inheritance.html\" rel=\"noreferrer\">http://www.crockford.com/javascript/inheritance.html</a></p>\n\n<p>And also at the end you don't have to kill or destroy the object. Why I found here: <a href=\"http://bytes.com/topic/javascript/answers/152552-javascript-destroy-object\" rel=\"noreferrer\">http://bytes.com/topic/javascript/answers/152552-javascript-destroy-object</a></p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 17885573,
"author": "transilvlad",
"author_id": 1311393,
"author_profile": "https://Stackoverflow.com/users/1311393",
"pm_score": 0,
"selected": false,
"text": "<p>I have done something like this and it works like a charm.</p>\n\n<p>Simple.</p>\n\n<p>P.S. There is more the the object but I just posted the relevant part.</p>\n\n<pre><code>var exScript = (function (undefined) {\n function exScript() {\n this.logInfo = [];\n var that = this;\n this.logInfo.push = function(e) {\n that.logInfo[that.logInfo.length] = e;\n console.log(e);\n };\n }\n})();\n</code></pre>\n"
},
{
"answer_id": 37283234,
"author": "Rodrigo Morales",
"author_id": 4091841,
"author_profile": "https://Stackoverflow.com/users/4091841",
"pm_score": 0,
"selected": false,
"text": "<p>With the following code you can access the parent of the object:</p>\n\n<pre><code>var Users = function(parent) {\n this.parent = parent;\n};\nUsers.prototype.guys = function(){ \n this.parent.nameAndDestroy(['test-name-and-destroy']);\n};\nUsers.prototype.girls = function(){ \n this.parent.kiss(['test-kiss']);\n};\n\nvar list = {\n users : function() {\n return new Users(this);\n },\n nameAndDestroy : function(group){ console.log(group); },\n kiss : function(group){ console.log(group); }\n};\n\nlist.users().guys(); // should output [\"test-name-and-destroy\"]\nlist.users().girls(); // should output [\"test-kiss\"]\n</code></pre>\n\n<p>I would recommend you read about javascript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow\">Objects</a> to get to know how you can work with Objects, it helped me a lot. I even found out about functions that I didn't even knew they existed.</p>\n"
},
{
"answer_id": 38172287,
"author": "Parchandri",
"author_id": 2616181,
"author_profile": "https://Stackoverflow.com/users/2616181",
"pm_score": 1,
"selected": false,
"text": "<p>I used something that resembles singleton pattern:</p>\n\n<pre><code>function myclass() = {\n var instance = this;\n\n this.Days = function() {\n var days = [\"Piątek\", \"Sobota\", \"Niedziela\"];\n return days;\n }\n\n this.EventTime = function(day, hours, minutes) {\n this.Day = instance.Days()[day];\n this.Hours = hours;\n this.minutes = minutes;\n this.TotalMinutes = day*24*60 + 60*hours + minutes;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41227400,
"author": "rplaurindo",
"author_id": 2730593,
"author_profile": "https://Stackoverflow.com/users/2730593",
"pm_score": 0,
"selected": false,
"text": "<p>If you want get all parents key of a node in a literal object (<code>{}</code>), you can to do that:</p>\n\n<pre><code>(function ($) {\n \"use strict\";\n\n $.defineProperties($, {\n parentKeys: {\n value: function (object) {\n var\n traces = [],\n queue = [{trace: [], node: object}],\n\n block = function () {\n var\n node,\n nodeKeys,\n trace;\n\n // clean the queue\n queue = [];\n return function (map) {\n node = map.node;\n nodeKeys = Object.keys(node);\n\n nodeKeys.forEach(function (nodeKey) {\n if (typeof node[nodeKey] == \"object\") {\n trace = map.trace.concat(nodeKey);\n // put on queue\n queue.push({trace: trace, node: node[nodeKey]});\n\n // traces.unshift(trace);\n traces.push(trace);\n }\n });\n };\n };\n\n while(true) {\n if (queue.length) {\n queue.forEach(block());\n } else {\n break;\n }\n }\n\n return traces;\n },\n\n writable: true\n }\n\n });\n\n})(Object);\n</code></pre>\n\n<p>This algorithm uses the <code>FIFO</code> concept for iterate the graphs using the <code>BFS</code> method. This code extend the class <code>Object</code> adding the static method <code>parentKeys</code> that expects a <code>literal Object</code> (hash table - associative array...) of the Javacript, as parameter.</p>\n\n<p>I hope I have helped.</p>\n"
},
{
"answer_id": 42048192,
"author": "amurrell",
"author_id": 2100636,
"author_profile": "https://Stackoverflow.com/users/2100636",
"pm_score": 3,
"selected": false,
"text": "<h3>About Call:</h3>\n\n<p>You can sort of solve this issue by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"noreferrer\"><code>.call()</code></a> which:</p>\n\n<ul>\n<li>must be called on a function <code>addName.call()</code></li>\n<li>you pass it an object of what you want to be the \"this\" <code>addName.call({\"name\" : 'angela'});</code></li>\n<li>you can pass additional arguments that can be used in the function it is called on <code>addName.call({\"name\": \"angela\"}, true);</code> where perhaps <code>addName</code> accepts an argument of boolean <code>append</code>.</li>\n</ul>\n\n<h3>Use Call:</h3>\n\n<p>For this particular problem, we can pass the \"parent\" object through <code>call</code> to override the <code>this</code> normally present in the child object.</p>\n\n<h3>Look at our problem first</h3>\n\n<pre><code>var app = {\n init: function() {\n var _this = this; // so we can access the app object in other functions\n\n $('#thingy').click(function(){\n alert(_this.options.thingy());\n });\n\n $('#another').click(function(){\n alert(_this.options.getAnother());\n });\n },\n options: {\n thingy: function() {\n // PROBLEM: the this here refers to options\n return this.getThingy();\n },\n getAnother: function() {\n // PROBLEM 2: we want the this here to refer to options,\n // but thingy will need the parent object\n return 'another ' + this.thingy();\n },\n },\n getThingy: function() {\n return 'thingy';\n }\n};\n</code></pre>\n\n<h3>Now, here's a solution use call</h3>\n\n<p>And <a href=\"https://jsfiddle.net/hL65m2ed/\" rel=\"noreferrer\">JSFIDDLE</a> to see it work.</p>\n\n<pre><code>var app = {\n init: function() {\n var _this = this; // so we can access the app object in other functions\n\n $('#thingy').click(function(){\n // SOLUTION: use call to pass _this as the 'this' used by thingy\n alert(_this.options.thingy.call(_this));\n });\n\n $('#another').click(function(){\n // SOLUTION 2: Use call to pass parent all the way through\n alert(_this.options.getAnother.call(_this)); \n });\n },\n options: {\n thingy: function() {\n // SOLUTION in action, the this is the app object, not options.\n return this.getThingy(); \n },\n getAnother: function() {\n // SOLUTION 2 in action, we can still access the options \n // AND pass through the app object to the thingy method.\n return 'another ' + this.options.thingy.call(this); \n },\n },\n getThingy: function() {\n return 'thingy';\n }\n};\n</code></pre>\n\n<h3>In conclusion</h3>\n\n<p>You can use <code>.call()</code> whenever you use a method on a property of your main object: <code>app.options.someFunction(arg)</code> should always be called with <code>.call</code> - <code>app.options.someFunction.call(this, arg);</code> - that way you can ensure that you'll always have access to every part of the object. It could give you access to another property's methods like <code>app.helpers.anotherFunction()</code>.</p>\n\n<p>A good idea is in the <code>somefunction</code>, store <code>this</code> in a variable <code>_parentThis</code> so it's obvious what the <code>this</code> reflects.</p>\n"
},
{
"answer_id": 48514729,
"author": "Elliot B.",
"author_id": 1215133,
"author_profile": "https://Stackoverflow.com/users/1215133",
"pm_score": 2,
"selected": false,
"text": "<p>As others have said, it is not possible to directly lookup a parent from a nested child. All of the proposed solutions advise various different ways of referring back to the parent object or parent scope through an explicit variable name.</p>\n\n<p>However, directly traversing up to the the parent object is possible if you employ recursive <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\" rel=\"nofollow noreferrer\">ES6 Proxies</a> on the parent object.</p>\n\n<p>I've written a library called <a href=\"https://github.com/ElliotNB/observable-slim\" rel=\"nofollow noreferrer\">ObservableSlim</a> that, among other things, allows you to traverse up from a child object to the parent. </p>\n\n<p>Here's a simple example (<a href=\"https://jsfiddle.net/hp0h5g8v/\" rel=\"nofollow noreferrer\">jsFiddle demo</a>):</p>\n\n<pre><code>var test = {\"hello\":{\"foo\":{\"bar\":\"world\"}}};\nvar proxy = ObservableSlim.create(test, true, function() { return false });\n\nfunction traverseUp(childObj) {\n console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {\"foo\":{\"bar\":\"world\"}}\n console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object\n};\n\ntraverseUp(proxy.hello.foo);\n</code></pre>\n"
},
{
"answer_id": 71843502,
"author": "Ninroot",
"author_id": 6244121,
"author_profile": "https://Stackoverflow.com/users/6244121",
"pm_score": 0,
"selected": false,
"text": "<p>If you can't modify the structure of the object because it's given to you (typically from a library), you can alway traverse recursively the object to find its parent.</p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Recursively traverse the rootObject to find the parent of childObject.\n * @param rootObject - root object to inspect\n * @param childObject - child object to match\n * @returns - parent object of child if exists, undefined otherwise\n */\nfunction findParent(rootObject, childObject) {\n if (!(rootObject && typeof rootObject === 'object')) {\n return undefined;\n }\n if (Array.isArray(rootObject)) {\n for (let i = 0; i < rootObject.length; i++) {\n if (rootObject[i] === childObject) {\n return rootObject;\n }\n const child = this.findParent(rootObject[i], childObject);\n if (child) {\n return child;\n }\n }\n } else {\n const keys = Object.keys(rootObject);\n for (let i = 0; i < keys.length; i += 1) {\n const key = keys[i];\n if (rootObject[key] === childObject) {\n return rootObject;\n }\n const child = this.findParent(rootObject[key], childObject);\n if (child) {\n return child;\n }\n }\n }\n return undefined;\n}\n\n// tests\n\nconst obj = {\n l1: { l11: { l111: ['a', 'b', 'c'] } },\n l2: { l21: ['a', 1, {}], l22: 123 },\n l3: [ { l33: {} } ],\n};\n\nassert.equal(findParent(obj, obj.l1), obj);\nassert.equal(findParent(obj, obj.l1.l11), obj.l1);\nassert.equal(findParent(obj, obj.l2), obj);\nassert.equal(findParent(obj, obj.l2.l21), obj.l2);\nassert.equal(findParent(obj, obj.l2.l22), obj.l2);\nassert.equal(findParent(obj, obj.l3[0]), obj.l3);\nassert.equal(findParent(obj, obj.l3[0].l33), obj.l3[0]);\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1825034/"
] |
Something like
```
var life= {
users : {
guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); },
girls : function(){ this.SOMETHING.kiss(this.boys); },
},
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
```
this.SOMETHING is what I imagine the format is, but it might not be. What will step back up to the parent of an object?
|
JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example:
```
var Bobby = {name: "Bobby"};
var Dad = {name: "Dad", children: [ Bobby ]};
var Mom = {name: "Mom", children: [ Bobby ]};
```
Who does Bobby belong to?
|
183,773 |
<p>A program receives a list of Messages (base type). Each message in the list has to be processed according to it's type (descendant type). However, different messages need different inputs in order to be processed correctly.</p>
<p>What is the following technique called? (I haven't checked this code in a compiler)</p>
<pre><code>abstract class MessageProcessor
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
public abstract void Process();
}
</code></pre>
<p>And this one?</p>
<pre><code>static class MessageProcessorFactory
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
}
</code></pre>
<p>And what is it called if I can inject the ProcessBuilder class into a MessageProcessor (using a property or Setter) and then call Process?</p>
<p>What technique would be the best pattern for solving this problem?</p>
|
[
{
"answer_id": 183836,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>They are both examples of the <em>factory method</em> pattern. The only difference is that the second example has the method in its own static class. </p>\n\n<p>This would be an example of the <em>abstract factory</em> pattern:</p>\n\n<pre><code>abstract class MessageProcessorFactory\n { public abstract MessageProcessor GetProcessor\n (Message message, DataDomain data);\n }\n\nclass FooMessageProcessorFactory : MessageProcessorFactory\n { public override MessageProcessor GetProcessor\n (Message message, DataDomain data)\n { return new FooMessageProcessor(data.Name, data.Classification);\n }\n }\n</code></pre>\n\n<p>Each MessageProcessor gets its own factory class which makes use of polymorphism.</p>\n\n<p>Passing a ProcessBuilder to create the process would be the <em>strategy</em> pattern:</p>\n\n<pre><code>class MessageProcessor\n { ProcessBuilder builder;\n\n public MessageProcessor(ProcessBuilder builder)\n { this.builder = builder;\n }\n\n public void Process()\n { builder.BuildMessage();\n builder.BuildProcess();\n builder.Process();\n }\n }\n\nvar mp = new MessageProcessor(new FooProcessBuilder());\n</code></pre>\n\n<p>The simplest solution would be to encapsulate a factory method:</p>\n\n<pre><code>static void Process(Message msg, DataDomain data)\n { var p = getProcessor(msg.GetType());\n p.Process(msg, data);\n }\n</code></pre>\n\n<p>If it's a small known number of types, you can use the series of type checks:</p>\n\n<pre><code>private static MessageProcessor getProcessor(Type msgType)\n { return (msgType == typeof(FooMessage)) ? new FooMessageProcessor()\n : (msgType == typeof(BarMessage)) ? new BarMessageProcessor()\n : new DefaultMessageProcessor();\n }\n</code></pre>\n\n<p>Otherwise use a dictionary:</p>\n\n<pre><code>Dictionary<Type,MessageProcessor> processors; \n\nprivate static MessageProcessor getProcessor(Type msgType) \n { return processors[msgType];\n }\n</code></pre>\n"
},
{
"answer_id": 184932,
"author": "DaSteph",
"author_id": 26035,
"author_profile": "https://Stackoverflow.com/users/26035",
"pm_score": 2,
"selected": false,
"text": "<p>In my understanding <em>factory method</em> defnies the abstract type of class with which to work with but delegates the creation of the concrete type to the succeeding/implementing classes. \n<em>Abstract factory</em> would define an interface for a manufactorer of a set of corresponding classes.\nA <em>builder</em> works simply to build an object step by step giving some control to the calling instance.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
A program receives a list of Messages (base type). Each message in the list has to be processed according to it's type (descendant type). However, different messages need different inputs in order to be processed correctly.
What is the following technique called? (I haven't checked this code in a compiler)
```
abstract class MessageProcessor
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
public abstract void Process();
}
```
And this one?
```
static class MessageProcessorFactory
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
}
```
And what is it called if I can inject the ProcessBuilder class into a MessageProcessor (using a property or Setter) and then call Process?
What technique would be the best pattern for solving this problem?
|
They are both examples of the *factory method* pattern. The only difference is that the second example has the method in its own static class.
This would be an example of the *abstract factory* pattern:
```
abstract class MessageProcessorFactory
{ public abstract MessageProcessor GetProcessor
(Message message, DataDomain data);
}
class FooMessageProcessorFactory : MessageProcessorFactory
{ public override MessageProcessor GetProcessor
(Message message, DataDomain data)
{ return new FooMessageProcessor(data.Name, data.Classification);
}
}
```
Each MessageProcessor gets its own factory class which makes use of polymorphism.
Passing a ProcessBuilder to create the process would be the *strategy* pattern:
```
class MessageProcessor
{ ProcessBuilder builder;
public MessageProcessor(ProcessBuilder builder)
{ this.builder = builder;
}
public void Process()
{ builder.BuildMessage();
builder.BuildProcess();
builder.Process();
}
}
var mp = new MessageProcessor(new FooProcessBuilder());
```
The simplest solution would be to encapsulate a factory method:
```
static void Process(Message msg, DataDomain data)
{ var p = getProcessor(msg.GetType());
p.Process(msg, data);
}
```
If it's a small known number of types, you can use the series of type checks:
```
private static MessageProcessor getProcessor(Type msgType)
{ return (msgType == typeof(FooMessage)) ? new FooMessageProcessor()
: (msgType == typeof(BarMessage)) ? new BarMessageProcessor()
: new DefaultMessageProcessor();
}
```
Otherwise use a dictionary:
```
Dictionary<Type,MessageProcessor> processors;
private static MessageProcessor getProcessor(Type msgType)
{ return processors[msgType];
}
```
|
183,791 |
<p>I have two collections which have property <code>Email</code> in both collections. I need to get a list of the items in the first list where <code>Email</code> does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?</p>
<p>So far I have a join, like...</p>
<pre><code>var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };
</code></pre>
<p>But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.</p>
|
[
{
"answer_id": 183804,
"author": "Robert Rouse",
"author_id": 25129,
"author_profile": "https://Stackoverflow.com/users/25129",
"pm_score": 9,
"selected": true,
"text": "<p>I don't know if this will help you but..</p>\n<pre><code>NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where !(from o in dc.Orders \n select o.CustomerID) \n .Contains(c.CustomerID) \n select c;\n\nforeach (var c in query) Console.WriteLine( c );\n</code></pre>\n<p>from <a href=\"https://web.archive.org/web/20120321161927/https://www.programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx\" rel=\"noreferrer\">The NOT IN clause in LINQ to SQL</a> by <a href=\"https://web.archive.org/web/20110805143247/http://introducinglinq.com/blogs/marcorusso/default.aspx\" rel=\"noreferrer\">Marco Russo</a></p>\n"
},
{
"answer_id": 183806,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var secondEmails = (from item in list2\n select new { Email = item.Email }\n ).ToList();\n\nvar matches = from item in list1\n where !secondEmails.Contains(item.Email)\n select new {Email = item.Email};\n</code></pre>\n"
},
{
"answer_id": 183812,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 8,
"selected": false,
"text": "<p>You want the Except operator.</p>\n\n<pre><code>var answer = list1.Except(list2);\n</code></pre>\n\n<p>Better explanation here: <a href=\"https://learn.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators\" rel=\"noreferrer\">https://learn.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators</a></p>\n\n<p><strong>NOTE:</strong> This technique works best for primitive types only, since you have to implement an <a href=\"https://learn.microsoft.com/dotnet/api/system.collections.generic.iequalitycomparer-1\" rel=\"noreferrer\">IEqualityComparer</a> to use the <code>Except</code> method with complex types.</p>\n"
},
{
"answer_id": 183822,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 1,
"selected": false,
"text": "<p>Example using List of int for simplicity.</p>\n\n<pre><code>List<int> list1 = new List<int>();\n// fill data\nList<int> list2 = new List<int>();\n// fill data\n\nvar results = from i in list1\n where !list2.Contains(i)\n select i;\n\nforeach (var result in results)\n Console.WriteLine(result.ToString());\n</code></pre>\n"
},
{
"answer_id": 183974,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>items in the first list where the Email does not exist in the second list. </p>\n</blockquote>\n\n<pre><code>from item1 in List1\nwhere !(list2.Any(item2 => item2.Email == item1.Email))\nselect item1;\n</code></pre>\n"
},
{
"answer_id": 184251,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "<p>While <code>Except</code> is part of the answer, it's not the whole answer. By default, <code>Except</code> (like several of the LINQ operators) does a reference comparison on reference types. To compare by values in the objects, you'll have to</p>\n\n<ul>\n<li>implement <code>IEquatable<T></code> in your type, or</li>\n<li>override <code>Equals</code> and <code>GetHashCode</code> in your type, or</li>\n<li>pass in an instance of a type implementing <code>IEqualityComparer<T></code> for your type</li>\n</ul>\n"
},
{
"answer_id": 3389553,
"author": "Brett",
"author_id": 188474,
"author_profile": "https://Stackoverflow.com/users/188474",
"pm_score": 3,
"selected": false,
"text": "<p>In the case where one is using the <a href=\"http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework\" rel=\"nofollow noreferrer\">ADO.NET Entity Framework</a>, EchoStorm's solution also works perfectly. But it took me a few minutes to wrap my head around it. Assuming you have a database context, dc, and want to find rows in table x not linked in table y, the complete answer answer looks like:</p>\n\n<pre><code>var linked =\n from x in dc.X\n from y in dc.Y\n where x.MyProperty == y.MyProperty\n select x;\nvar notLinked =\n dc.X.Except(linked);\n</code></pre>\n\n<p>In response to Andy's comment, yes, one can have two from's in a LINQ query. Here's a complete working example, using lists. Each class, Foo and Bar, has an Id. Foo has a \"foreign key\" reference to Bar via Foo.BarId. The program selects all Foo's not linked to a corresponding Bar.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n // Creates some foos\n List<Foo> fooList = new List<Foo>();\n fooList.Add(new Foo { Id = 1, BarId = 11 });\n fooList.Add(new Foo { Id = 2, BarId = 12 });\n fooList.Add(new Foo { Id = 3, BarId = 13 });\n fooList.Add(new Foo { Id = 4, BarId = 14 });\n fooList.Add(new Foo { Id = 5, BarId = -1 });\n fooList.Add(new Foo { Id = 6, BarId = -1 });\n fooList.Add(new Foo { Id = 7, BarId = -1 });\n\n // Create some bars\n List<Bar> barList = new List<Bar>();\n barList.Add(new Bar { Id = 11 });\n barList.Add(new Bar { Id = 12 });\n barList.Add(new Bar { Id = 13 });\n barList.Add(new Bar { Id = 14 });\n barList.Add(new Bar { Id = 15 });\n barList.Add(new Bar { Id = 16 });\n barList.Add(new Bar { Id = 17 });\n\n var linked = from foo in fooList\n from bar in barList\n where foo.BarId == bar.Id\n select foo;\n var notLinked = fooList.Except(linked);\n foreach (Foo item in notLinked)\n {\n Console.WriteLine(\n String.Format(\n \"Foo.Id: {0} | Bar.Id: {1}\",\n item.Id, item.BarId));\n }\n Console.WriteLine(\"Any key to continue...\");\n Console.ReadKey();\n }\n}\n\nclass Foo\n{\n public int Id { get; set; }\n public int BarId { get; set; }\n}\n\nclass Bar\n{\n public int Id { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 3389610,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 6,
"selected": false,
"text": "<p>For people who start with a group of in-memory objects and are querying against a database, I've found this to be the best way to go:</p>\n\n<pre><code>var itemIds = inMemoryList.Select(x => x.Id).ToArray();\nvar otherObjects = context.ItemList.Where(x => !itemIds.Contains(x.Id));\n</code></pre>\n\n<p>This produces a nice <code>WHERE ... IN (...)</code> clause in SQL.</p>\n"
},
{
"answer_id": 7242227,
"author": "Chintan Udeshi",
"author_id": 919568,
"author_profile": "https://Stackoverflow.com/users/919568",
"pm_score": 3,
"selected": false,
"text": "<p>You can take both the collections in two different lists, say list1 and list2.</p>\n\n<p>Then just write</p>\n\n<pre><code>list1.RemoveAll(Item => list2.Contains(Item));\n</code></pre>\n\n<p>This will work.</p>\n"
},
{
"answer_id": 25890827,
"author": "Tarik",
"author_id": 990750,
"author_profile": "https://Stackoverflow.com/users/990750",
"pm_score": 0,
"selected": false,
"text": "<p>I did not test this with <a href=\"http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework#LINQ_to_Entities\" rel=\"nofollow\">LINQ to Entities</a>:</p>\n\n<pre><code>NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where !dc.Orders.Any(o => o.CustomerID == c.CustomerID) \n select c;\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where dc.Orders.All(o => o.CustomerID != c.CustomerID) \n select c;\n\nforeach (var c in query) \n Console.WriteLine( c );\n</code></pre>\n"
},
{
"answer_id": 27498081,
"author": "DevT",
"author_id": 1395178,
"author_profile": "https://Stackoverflow.com/users/1395178",
"pm_score": 4,
"selected": false,
"text": "<p>You can use a combination of Where and Any for finding not in:</p>\n\n<pre><code>var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email == p.Email));\n</code></pre>\n"
},
{
"answer_id": 29822197,
"author": "Marten Jacobs",
"author_id": 3512199,
"author_profile": "https://Stackoverflow.com/users/3512199",
"pm_score": 0,
"selected": false,
"text": "<p>Couldn't you do an outer join, only selecting the items from the first list if the group is empty? Something like:</p>\n\n<pre><code>Dim result = (From a In list1\n Group Join b In list2 \n On a.Value Equals b.Value \n Into grp = Group\n Where Not grp.Any\n Select a)\n</code></pre>\n\n<p>I'm unsure whether this would work in any sort of efficient way with the Entity framework.</p>\n"
},
{
"answer_id": 41100707,
"author": "mshwf",
"author_id": 6197785,
"author_profile": "https://Stackoverflow.com/users/6197785",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone who also wants to use a SQL-alike <code>IN</code> operator in C#, download this package : </p>\n\n<blockquote>\n <p>Mshwf.NiceLinq</p>\n</blockquote>\n\n<p>It has <code>In</code> and <code>NotIn</code> methods:</p>\n\n<pre><code>var result = list1.In(x => x.Email, list2.Select(z => z.Email));\n</code></pre>\n\n<p>Even you can use it this way</p>\n\n<pre><code>var result = list1.In(x => x.Email, \"[email protected]\", \"[email protected]\", \"[email protected]\");\n</code></pre>\n"
},
{
"answer_id": 45915151,
"author": "Janis S.",
"author_id": 5251960,
"author_profile": "https://Stackoverflow.com/users/5251960",
"pm_score": 3,
"selected": false,
"text": "<p>One could also use <code>All()</code></p>\n\n<pre><code>var notInList = list1.Where(p => list2.All(p2 => p2.Email != p.Email));\n</code></pre>\n"
},
{
"answer_id": 58080005,
"author": "nzrytmn",
"author_id": 3193030,
"author_profile": "https://Stackoverflow.com/users/3193030",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively you can do like this:</p>\n\n<pre><code>var result = list1.Where(p => list2.All(x => x.Id != p.Id));\n</code></pre>\n"
},
{
"answer_id": 63037787,
"author": "Arup Mahapatra",
"author_id": 10366755,
"author_profile": "https://Stackoverflow.com/users/10366755",
"pm_score": 0,
"selected": false,
"text": "<pre><code> DynamicWebsiteEntities db = new DynamicWebsiteEntities();\n var data = (from dt_sub in db.Subjects_Details\n //Sub Query - 1\n let sub_s_g = (from sg in db.Subjects_In_Group\n where sg.GroupId == groupId\n select sg.SubjectId)\n //Where Cause\n where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false\n //Order By Cause\n orderby dt_sub.Subject_Name\n\n select dt_sub)\n .AsEnumerable();\n \n SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);\n\n //======================================OR===========================================\n\n var data = (from dt_sub in db.Subjects_Details\n\n \n //Where Cause\n where !(from sg in db.Subjects_In_Group\n where sg.GroupId == groupId\n select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false\n\n //Order By Cause\n orderby dt_sub.Subject_Name\n\n select dt_sub)\n\n .AsEnumerable();\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] |
I have two collections which have property `Email` in both collections. I need to get a list of the items in the first list where `Email` does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?
So far I have a join, like...
```
var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };
```
But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.
|
I don't know if this will help you but..
```
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );
```
from [The NOT IN clause in LINQ to SQL](https://web.archive.org/web/20120321161927/https://www.programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx) by [Marco Russo](https://web.archive.org/web/20110805143247/http://introducinglinq.com/blogs/marcorusso/default.aspx)
|
183,846 |
<p><a href="http://blog.stevenlevithan.com/archives/balancing-groups" rel="nofollow noreferrer">.NET balanced group regexes</a> make my head explode. I've got this string i'm trying to match:</p>
<pre><code>other stuff blah blah....
{
stuff stuff
{key:
stuff
stuff
}
} more stuff.....
</code></pre>
<p>Here's my regex:</p>
<pre><code>[^{}]* # anything that isn't { }
\{ # starting with {
(?> # atomic group: throw away backtracks on exit
[^{}]+
|
\{(?:\w+:)?(?<DEPTH>) # on matching { plus optional "word:" push stack
|
\}(?<-DEPTH>) # on matching } pop stack
)*
(?(DEPTH)(?!)) # if depth unbalanced, fail match
\} # ending with }
[^{}]* # anything that isn't { }
</code></pre>
<p>So, I'm trying to match balancing curly braces, where some of the opening curly braces have an optional word followed by a colon. The above regex matches my example string, but if i remove a curly brace, (i.e. "unbalancing it):</p>
<pre><code> other stuff blah blah....
{
stuff stuff
{key:
stuff
stuff
} more stuff.....
</code></pre>
<p>...it still matches!</p>
<p>Can anyone tell me how to fix my regex?</p>
|
[
{
"answer_id": 183876,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "<p>Not to be a kill joy but what you're attempting to do with a regular expression is boggling your mind because it's simply not possible. Regular expressions are a class of finite automata and do not posses enough state in which to peform recursive/nested matching. You'll need a context free grammar of sorts in order to get this working.</p>\n\n<p>There are some regular expression engines which do support a notion of recursion. These are not strictly speaking regular expressions though. Can you tell us what engine you are using because it's possible it has a recursion function which will help out this scenario. </p>\n"
},
{
"answer_id": 183988,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": true,
"text": "<p>Have you checked what it is matching in the second case? Since you don't have any anchors, I think the engine starts the match just after the first '{'. From there, until the end, the string matches.</p>\n\n<p>Try surrounding the pattern with \\A and \\z.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670022/"
] |
[.NET balanced group regexes](http://blog.stevenlevithan.com/archives/balancing-groups) make my head explode. I've got this string i'm trying to match:
```
other stuff blah blah....
{
stuff stuff
{key:
stuff
stuff
}
} more stuff.....
```
Here's my regex:
```
[^{}]* # anything that isn't { }
\{ # starting with {
(?> # atomic group: throw away backtracks on exit
[^{}]+
|
\{(?:\w+:)?(?<DEPTH>) # on matching { plus optional "word:" push stack
|
\}(?<-DEPTH>) # on matching } pop stack
)*
(?(DEPTH)(?!)) # if depth unbalanced, fail match
\} # ending with }
[^{}]* # anything that isn't { }
```
So, I'm trying to match balancing curly braces, where some of the opening curly braces have an optional word followed by a colon. The above regex matches my example string, but if i remove a curly brace, (i.e. "unbalancing it):
```
other stuff blah blah....
{
stuff stuff
{key:
stuff
stuff
} more stuff.....
```
...it still matches!
Can anyone tell me how to fix my regex?
|
Have you checked what it is matching in the second case? Since you don't have any anchors, I think the engine starts the match just after the first '{'. From there, until the end, the string matches.
Try surrounding the pattern with \A and \z.
|
183,853 |
<p>Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:</p>
<pre><code>>>> 6/3
2
>>> 6//3
2
</code></pre>
|
[
{
"answer_id": 183863,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": false,
"text": "<p><code>//</code> is floor division. It will always give you the integer floor of the result. The other is 'regular' division.</p>\n"
},
{
"answer_id": 183865,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 3,
"selected": false,
"text": "<p>The double slash, <code>//</code>, is floor division:</p>\n\n<pre><code>>>> 7//3\n2\n</code></pre>\n"
},
{
"answer_id": 183866,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 5,
"selected": false,
"text": "<p><code>//</code> implements "floor division", regardless of your type. So\n<code>1.0/2.0</code> will give <code>0.5</code>, but both <code>1/2</code>, <code>1//2</code> and <code>1.0//2.0</code> will give <code>0</code>.</p>\n<p>See <em><a href=\"https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator\" rel=\"nofollow noreferrer\">PEP 238: Changing the Division Operator</a></em> for details.</p>\n"
},
{
"answer_id": 183870,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 11,
"selected": true,
"text": "<p>In Python 3.x, <code>5 / 2</code> will return <code>2.5</code> and <code>5 // 2</code> will return <code>2</code>. The former is floating point division, and the latter is <em><strong>floor division</strong></em>, sometimes also called <em><strong>integer division</strong></em>.</p>\n<p>In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a <code>from __future__ import division</code>, which causes Python 2.x to adopt the 3.x behavior.</p>\n<p>Regardless of the future import, <code>5.0 // 2</code> will return <code>2.0</code> since that's the floor division result of the operation.</p>\n<p>You can find a detailed description at <em><a href=\"https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator\" rel=\"noreferrer\">PEP 238: Changing the Division Operator</a></em>.</p>\n"
},
{
"answer_id": 1704753,
"author": "u0b34a0f6ae",
"author_id": 137317,
"author_profile": "https://Stackoverflow.com/users/137317",
"pm_score": 5,
"selected": false,
"text": "<p>As everyone has already answered, <code>//</code> is floor division.</p>\n\n<p>Why this is important is that <code>//</code> is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions.</p>\n\n<p>The behavior of <code>/</code> can change depending on:</p>\n\n<ul>\n<li>Active <code>__future__</code> import or not (module-local)</li>\n<li>Python command line option, either <code>-Q old</code> or <code>-Q new</code></li>\n</ul>\n"
},
{
"answer_id": 11604247,
"author": "Yichun",
"author_id": 766827,
"author_profile": "https://Stackoverflow.com/users/766827",
"pm_score": 6,
"selected": false,
"text": "<h3>Python 2.x Clarification:</h3>\n<p>To clarify for the Python 2.x line, <code>/</code> is neither floor division nor true division.</p>\n<p><code>/</code> is floor division when <strong>both</strong> args are <code>int</code>, but is true division when <em><strong>either</strong></em> of the args are <code>float</code>.</p>\n"
},
{
"answer_id": 22487879,
"author": "Jonas Sciangula Street",
"author_id": 2246650,
"author_profile": "https://Stackoverflow.com/users/2246650",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> print 5.0 / 2\n2.5\n\n>>> print 5.0 // 2\n2.0\n</code></pre>\n"
},
{
"answer_id": 30624406,
"author": "G.Ant",
"author_id": 4922716,
"author_profile": "https://Stackoverflow.com/users/4922716",
"pm_score": 2,
"selected": false,
"text": "<p>The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point. </p>\n\n<pre><code>>>>print 5//2\n2\n>>> print 5.0//2\n2.0\n>>>print 5//2.0\n2.0\n>>>print 5.0//2.0\n2.0\n</code></pre>\n"
},
{
"answer_id": 38552114,
"author": "N Randhawa",
"author_id": 4854721,
"author_profile": "https://Stackoverflow.com/users/4854721",
"pm_score": 5,
"selected": false,
"text": "<p><strong>/</strong> → Floating point division</p>\n<p><strong>//</strong> → Floor division</p>\n<p>Let’s see some examples in both Python 2.7 and in Python 3.5.</p>\n<p><strong>Python 2.7.10 vs. Python 3.5</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>print (2/3) ----> 0 Python 2.7\nprint (2/3) ----> 0.6666666666666666 Python 3.5\n</code></pre>\n<p><strong>Python 2.7.10 vs. Python 3.5</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>print (4/2) ----> 2 Python 2.7\nprint (4/2) ----> 2.0 Python 3.5\n</code></pre>\n<p>Now if you want to have (in Python 2.7) the same output as in Python 3.5, you can do the following:</p>\n<p><strong>Python 2.7.10</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>from __future__ import division\nprint (2/3) ----> 0.6666666666666666 # Python 2.7\nprint (4/2) ----> 2.0 # Python 2.7\n</code></pre>\n<p>Whereas there isn't any difference between <em>floor</em> division in both Python 2.7 and in Python 3.5.</p>\n<pre class=\"lang-none prettyprint-override\"><code>138.93//3 ---> 46.0 # Python 2.7\n138.93//3 ---> 46.0 # Python 3.5\n4//3 ---> 1 # Python 2.7\n4//3 ---> 1 # Python 3.5\n</code></pre>\n"
},
{
"answer_id": 42053200,
"author": "Abrar Ahmad",
"author_id": 7519298,
"author_profile": "https://Stackoverflow.com/users/7519298",
"pm_score": 3,
"selected": false,
"text": "<p>Python 2.7 and other upcoming versions of Python:</p>\n<ul>\n<li>Division (<code>/</code>)</li>\n</ul>\n<p>Divides left hand operand by right hand operand</p>\n<p>Example: <code>4 / 2 = 2</code></p>\n<ul>\n<li>Floor division (<code>//</code>)</li>\n</ul>\n<p>The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):</p>\n<p>Examples: <code>9//2 = 4</code> and <code>9.0//2.0 = 4.0</code>, <code>-11//3 = -4</code>, <code>-11.0//3 = -4.0</code></p>\n<p>Both <code>/</code> division and <code>//</code> floor division operator are operating in similar fashion.</p>\n"
},
{
"answer_id": 53234075,
"author": "Sebastian Purakan",
"author_id": 10631176,
"author_profile": "https://Stackoverflow.com/users/10631176",
"pm_score": -1,
"selected": false,
"text": "<p><code>5.0//2</code> results in <code>2.0</code>, and not <code>2</code>, because the <strong>return type</strong> of the return value from <code>//</code> operator follows Python coercion (type casting) rules.</p>\n<p>Python promotes conversion of lower data type (integer) to higher data type (float) to avoid data loss.</p>\n"
},
{
"answer_id": 55317456,
"author": "Fatema Tuz Zuhora",
"author_id": 5403883,
"author_profile": "https://Stackoverflow.com/users/5403883",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><code>//</code> is floor division. It will always give you the floor value of the result.</li>\n<li>And the other one, <code>/</code>, is the floating-point division.</li>\n</ul>\n<p>In the following is the difference between <code>/</code> and <code>//</code>;\nI have run these arithmetic operations in Python 3.7.2.</p>\n<pre><code>>>> print (11 / 3)\n3.6666666666666665\n\n>>> print (11 // 3)\n3\n\n>>> print (11.3 / 3)\n3.7666666666666667\n\n>>> print (11.3 // 3)\n3.0\n</code></pre>\n"
},
{
"answer_id": 56470206,
"author": "jaya ram",
"author_id": 10974987,
"author_profile": "https://Stackoverflow.com/users/10974987",
"pm_score": 2,
"selected": false,
"text": "<p>The previous answers are good. I want to add another point. Up to some values both of them result in the same quotient. After that floor division operator (<code>//</code>) works fine but not division (<code>/</code>) operator:</p>\n<pre><code>>>> int(755349677599789174 / 2) # Wrong answer\n377674838799894592\n</code></pre>\n<pre><code>>>> 755349677599789174 // 2 # Correct answer\n377674838799894587\n</code></pre>\n"
},
{
"answer_id": 66189553,
"author": "villamejia",
"author_id": 3147690,
"author_profile": "https://Stackoverflow.com/users/3147690",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Python 3.x Clarification</strong></p>\n<p>Just to complement some previous answers.</p>\n<p>It is important to remark that:</p>\n<blockquote>\n<p>a // b</p>\n</blockquote>\n<ul>\n<li><p>Is <strong>floor division</strong>. As in:</p>\n<blockquote>\n<p>math.floor(a/b)</p>\n</blockquote>\n</li>\n<li><p>Is not <strong>int division</strong>. As in:</p>\n<blockquote>\n<p>int(a/b)</p>\n</blockquote>\n</li>\n<li><p>Is not <strong>round to 0 float division</strong>. As in:</p>\n<blockquote>\n<p>round(a/b,0)</p>\n</blockquote>\n</li>\n</ul>\n<p>As a consequence, the way of behaving is different when it comes to positives an negatives numbers as in the following example:</p>\n<p>1 // 2 is 0, as in:</p>\n<blockquote>\n<p>math.floor(1/2)</p>\n</blockquote>\n<p>-1 // 2 is -1, as in:</p>\n<blockquote>\n<p>math.floor(-1/2)</p>\n</blockquote>\n"
},
{
"answer_id": 66835078,
"author": "iacob",
"author_id": 9067615,
"author_profile": "https://Stackoverflow.com/users/9067615",
"pm_score": 0,
"selected": false,
"text": "<h3><a href=\"https://docs.python.org/3/library/stdtypes.html#typesnumeric\" rel=\"nofollow noreferrer\">Python 3</a></h3>\n<blockquote>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Operation</th>\n<th>Result</th>\n<th>Notes</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>x / y</code></td>\n<td>quotient of <em>x</em> and <em>y</em></td>\n<td></td>\n</tr>\n<tr>\n<td><code>x // y</code></td>\n<td>floored quotient of <em>x</em> and <em>y</em></td>\n<td>(1)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Notes:</p>\n<ol>\n<li>Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: <code>1//2</code> is <code>0</code>, <code>(-1)//2</code> is <code>-1</code>, <code>1//(-2)</code> is <code>-1</code>, and <code>(-1)//(-2)</code> is <code>0</code>.</li>\n</ol>\n</blockquote>\n<h3><a href=\"https://docs.python.org/2/library/stdtypes.html#typesnumeric\" rel=\"nofollow noreferrer\">Python 2</a></h3>\n<blockquote>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Operation</th>\n<th>Result</th>\n<th>Notes</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>x / y</code></td>\n<td>quotient of <em>x</em> and <em>y</em></td>\n<td>(1)</td>\n</tr>\n<tr>\n<td><code>x // y</code></td>\n<td>(floored) quotient of <em>x</em> and <em>y</em></td>\n<td>(4)(5)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Notes:</p>\n<p>1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>4. <em>Deprecated since version 2.3:</em> The floor division operator, the modulo operator, and the <a href=\"https://docs.python.org/2/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod()</code></a> function are no longer defined for complex numbers. Instead, convert to a floating point number using the <a href=\"https://docs.python.org/2/library/functions.html#abs\" rel=\"nofollow noreferrer\"><code>abs()</code></a> function if appropriate.</th>\n</tr>\n</thead>\n</table>\n</div>\n<p>5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.</p>\n</blockquote>\n"
},
{
"answer_id": 68579034,
"author": "naoki fujita",
"author_id": 5225993,
"author_profile": "https://Stackoverflow.com/users/5225993",
"pm_score": 0,
"selected": false,
"text": "<h2>Summary</h2>\n<ul>\n<li>x//y : <strong>EXACT</strong> integer division</li>\n<li>int(x/y) OR math.floor(x/y): <strong>INEXACT</strong> integer division (but almost correct)</li>\n<li>x/y: floating point division (that has the loss of significance)</li>\n</ul>\n<h2>Remarkable Calculation Result</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nN = 1004291331219602346 # huge number \n\nprint(N//100) #=> 10042913312196023 is correct answer\nprint(math.floor(N/100)) #=> 10042913312196024 is wrong answer\nprint(math.ceil(N/100)) #=> 10042913312196024 is wrong answer\nprint(int(N/100)) #=> 10042913312196024 is wrong answer\n</code></pre>\n<h2>Consideration</h2>\n<p>I think about the evaluation of <code>int(x/y)</code>.<br />\nAt first, Python evaluate the expression <code>x/y</code> and get INEXACT floating number z.<br />\nSecond, Python evaluate the expression <code>int(z)</code>.<br />\nWe get a wrong result when the loss of significance cannot be ignored.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:
```
>>> 6/3
2
>>> 6//3
2
```
|
In Python 3.x, `5 / 2` will return `2.5` and `5 // 2` will return `2`. The former is floating point division, and the latter is ***floor division***, sometimes also called ***integer division***.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a `from __future__ import division`, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, `5.0 // 2` will return `2.0` since that's the floor division result of the operation.
You can find a detailed description at *[PEP 238: Changing the Division Operator](https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator)*.
|
183,856 |
<p>Is there any way to clean up this type of loop using LINQ?</p>
<pre><code> List<Car> result;
List<string> makes;
List<string> models;
for (int i = 0; i < makes.Count() && i < models.Count(); i++)
{
result.Add(new Car() { Make = makes[i], Model = models[i] });
}
</code></pre>
<p>Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields. </p>
|
[
{
"answer_id": 183891,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 4,
"selected": true,
"text": "<p>You could use <code>Enumerable.Range</code>, like so:</p>\n\n<pre><code>List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))\n .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();\n</code></pre>\n\n<p>If <code>makes</code> and <code>models</code> always contain the same number of items, you can use more compact syntax:</p>\n\n<pre><code>List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();\n</code></pre>\n"
},
{
"answer_id": 184064,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how frequently you are going to need to write LINQ queries against these arrays, it may be worth building a class that wraps the arrays and implements <code>IEnumerable<Car></code>. Then your code looks like this:</p>\n\n<pre><code>IEnumerable<Car> cars = new MyClass(makes, models);\nvar result = from cars...\n</code></pre>\n\n<p>It's not especially complicated to build this; it's just four simple methods (well, six, if you count constructors) spread across two classes (you also need to implement <code>IEnumerator<Car></code>). </p>\n\n<p>This approach keeps you from having to embed implementation details in all of your LINQ queries. Also, if you've never done this, it's really something worth learning. Being comfortable implementing <code>IEnumerable<T></code> significantly expands the space of things that you can readily use LINQ for.</p>\n"
},
{
"answer_id": 184106,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you really need a new LINQ operator - one which wasn't included in LINQ, somewhat accidentally: Zip. It would basically take two enumerables and return a single enumerable which paired entries, until one or other of the original sequences finished.</p>\n\n<p>I don't have anything like that up my sleeve, but it shouldn't take too long to write if you're interested. The resulting code would be something like:</p>\n\n<pre><code>List<Car> cars = makes.Zip(models)\n .Select(pair => new Car(pair.First, pair.Second))\n .ToList();\n</code></pre>\n\n<p>Let me know if you'd be interested in this and I'll code it up in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">MiscUtil</a>.</p>\n"
},
{
"answer_id": 187883,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 1,
"selected": false,
"text": "<pre><code>List<Car> result = makes\n .Take(model.Count)\n .Select((make, index) => new Car {Make = make, Model = models[index]});\n</code></pre>\n\n<p>Note that this works even if makes and models aren't the same length.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
Is there any way to clean up this type of loop using LINQ?
```
List<Car> result;
List<string> makes;
List<string> models;
for (int i = 0; i < makes.Count() && i < models.Count(); i++)
{
result.Add(new Car() { Make = makes[i], Model = models[i] });
}
```
Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields.
|
You could use `Enumerable.Range`, like so:
```
List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
.Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();
```
If `makes` and `models` always contain the same number of items, you can use more compact syntax:
```
List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();
```
|
183,859 |
<p>Our base Masterpage has something like the following</p>
<pre><code> <head runat="server">
<title></title>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script>
<asp:contentplaceholder id="cph_htmlhead" runat="server">
</asp:contentplaceholder>
</head>
</code></pre>
<p>If this Masterpage is the Masterpage for an ASPX page things work fine.</p>
<p>If this Masterpage is the Masterpage for a child Masterpage and then a new ASPX page uses the child Masterpage as it's MasterPage we see:</p>
<p>Server Error in '' Application. </p>
<p>The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).</p>
<p><strong>What is the preferred way to include global resources (Javascript/CSS) in a base Masterpage preserving tilde(~) style relative pathing?</strong></p>
|
[
{
"answer_id": 183879,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>As per <a href=\"http://weblogs.asp.net/scottgu/archive/2006/12/19/tip-trick-how-to-run-a-root-site-with-the-local-web-server-using-vs-2005-sp1.aspx\" rel=\"nofollow noreferrer\">ScottGu</a>,</p>\n\n<p>One tip to take advantage of is the relative path fix-up support provided by the head runat=\"server\" control. You can use this within Master Pages to easily reference a .CSS stylesheet that is re-used across the entire project (regardless of whether the project is root referenced or a sub-application):</p>\n\n<p>The path fix-up feature of the head control will then take the relative .CSS stylesheet path and correctly output the absolute path to the stylesheet at runtime regardless of whether it is a root referenced web-site or part of a sub-application. </p>\n"
},
{
"answer_id": 183905,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code><script type=\"text/javascript\" src='<%= Page.ResolveClientUrl(\"~/javascript/actions.js\") %>'></script>\n</code></pre>\n"
},
{
"answer_id": 184952,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 5,
"selected": true,
"text": "<p>Use the ScriptManager server control:</p>\n\n<pre><code> <asp:ScriptManager ID=\"myScriptManager\" runat=\"server\">\n <Scripts>\n <asp:ScriptReference Path = \"~/javascript/actions.js\" /> \n <asp:ScriptReference Path = \"~/javascript/jquery/jquery-1.2.6.min.js\" />\n </Scripts>\n </asp:ScriptManager>\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439/"
] |
Our base Masterpage has something like the following
```
<head runat="server">
<title></title>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script>
<asp:contentplaceholder id="cph_htmlhead" runat="server">
</asp:contentplaceholder>
</head>
```
If this Masterpage is the Masterpage for an ASPX page things work fine.
If this Masterpage is the Masterpage for a child Masterpage and then a new ASPX page uses the child Masterpage as it's MasterPage we see:
Server Error in '' Application.
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
**What is the preferred way to include global resources (Javascript/CSS) in a base Masterpage preserving tilde(~) style relative pathing?**
|
Use the ScriptManager server control:
```
<asp:ScriptManager ID="myScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Path = "~/javascript/actions.js" />
<asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" />
</Scripts>
</asp:ScriptManager>
```
|
183,881 |
<p>I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach). I wanted to know what my options are in regards to web cams or other image capture devices that:</p>
<ul>
<li>Are easy to work with with the
Windows SDK (particularly
<a href="http://msdn.microsoft.com/en-us/library/ms783323(VS.85).aspx" rel="nofollow noreferrer">DirectShow</a>, which I plan to use
with C#) </li>
<li>Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)</li>
</ul>
<p>I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at. I suspect that any old web cam will do but I'd rather be safe than sorry.</p>
|
[
{
"answer_id": 183879,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>As per <a href=\"http://weblogs.asp.net/scottgu/archive/2006/12/19/tip-trick-how-to-run-a-root-site-with-the-local-web-server-using-vs-2005-sp1.aspx\" rel=\"nofollow noreferrer\">ScottGu</a>,</p>\n\n<p>One tip to take advantage of is the relative path fix-up support provided by the head runat=\"server\" control. You can use this within Master Pages to easily reference a .CSS stylesheet that is re-used across the entire project (regardless of whether the project is root referenced or a sub-application):</p>\n\n<p>The path fix-up feature of the head control will then take the relative .CSS stylesheet path and correctly output the absolute path to the stylesheet at runtime regardless of whether it is a root referenced web-site or part of a sub-application. </p>\n"
},
{
"answer_id": 183905,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code><script type=\"text/javascript\" src='<%= Page.ResolveClientUrl(\"~/javascript/actions.js\") %>'></script>\n</code></pre>\n"
},
{
"answer_id": 184952,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 5,
"selected": true,
"text": "<p>Use the ScriptManager server control:</p>\n\n<pre><code> <asp:ScriptManager ID=\"myScriptManager\" runat=\"server\">\n <Scripts>\n <asp:ScriptReference Path = \"~/javascript/actions.js\" /> \n <asp:ScriptReference Path = \"~/javascript/jquery/jquery-1.2.6.min.js\" />\n </Scripts>\n </asp:ScriptManager>\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645/"
] |
I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach). I wanted to know what my options are in regards to web cams or other image capture devices that:
* Are easy to work with with the
Windows SDK (particularly
[DirectShow](http://msdn.microsoft.com/en-us/library/ms783323(VS.85).aspx), which I plan to use
with C#)
* Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)
I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at. I suspect that any old web cam will do but I'd rather be safe than sorry.
|
Use the ScriptManager server control:
```
<asp:ScriptManager ID="myScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Path = "~/javascript/actions.js" />
<asp:ScriptReference Path = "~/javascript/jquery/jquery-1.2.6.min.js" />
</Scripts>
</asp:ScriptManager>
```
|
183,898 |
<p>How do I do forward referencing / declaration in C++ to avoid circular header file references?</p>
<p>I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how. </p>
|
[
{
"answer_id": 183908,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 5,
"selected": true,
"text": "<p>You predeclare the class without including it. For example:</p>\n\n<pre><code>//#include \"Foo.h\" // including Foo.h causes circular reference\nclass Foo;\n\nclass Bar\n{\n...\n};\n</code></pre>\n"
},
{
"answer_id": 183915,
"author": "Joe Schneider",
"author_id": 1541,
"author_profile": "https://Stackoverflow.com/users/1541",
"pm_score": -1,
"selected": false,
"text": "<p>You won't get circular header files references if you have #ifndef guards. That's the point. </p>\n\n<p>Forward referencing is used to avoid #include(ing) header files for objects you use only by pointer or reference. However, in this case you are not solving a circular reference problem, you're just practicing good design and decoupling the .h file from details it doesn't need to know.</p>\n"
},
{
"answer_id": 185219,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 1,
"selected": false,
"text": "<p>I believe the correct term for what you are talking about is \"forward declaration\". \"Forward referencing\" would be a bit confusing.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] |
How do I do forward referencing / declaration in C++ to avoid circular header file references?
I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how.
|
You predeclare the class without including it. For example:
```
//#include "Foo.h" // including Foo.h causes circular reference
class Foo;
class Bar
{
...
};
```
|
183,904 |
<p>In the following code below:</p>
<pre><code>Image img = new Image();
img.Source = new BitmapImage(new Uri("http://someURL/somefilename.jpg", UriKind.Absolute));
</code></pre>
<p>how can I determine if the image successfully loaded (when there's a valid URI)? i.e., The URI is a valid format, but the file may not exist. </p>
|
[
{
"answer_id": 184069,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "<p><code>Image</code> has an <code>ImageFailed</code> event.</p>\n\n<p><code>BitmapSource</code> (base for <code>BitmapImage</code>) has an <code>IsDownloading</code> property, as well as <code>DownloadProgress</code>, <code>DownloadCompleted</code>, and <code>DownloadFailed</code> events.</p>\n"
},
{
"answer_id": 189278,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>If you run your example code above (with a valid url but invalid image file) you will get an exception thrown:</p>\n\n<pre><code>Error: Sys.InvalidOperationException: ImageError error #4001 in control 'Xaml1': AG_E_NETWORK_ERROR\n</code></pre>\n\n<p>So if you wrap your code in a try/catch block you can determine if the image loaded property or not.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26218/"
] |
In the following code below:
```
Image img = new Image();
img.Source = new BitmapImage(new Uri("http://someURL/somefilename.jpg", UriKind.Absolute));
```
how can I determine if the image successfully loaded (when there's a valid URI)? i.e., The URI is a valid format, but the file may not exist.
|
`Image` has an `ImageFailed` event.
`BitmapSource` (base for `BitmapImage`) has an `IsDownloading` property, as well as `DownloadProgress`, `DownloadCompleted`, and `DownloadFailed` events.
|
183,907 |
<p>Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string. </p>
<p>Example:</p>
<blockquote>
<p>"The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'."</p>
</blockquote>
|
[
{
"answer_id": 183909,
"author": "jr.",
"author_id": 2415,
"author_profile": "https://Stackoverflow.com/users/2415",
"pm_score": 7,
"selected": true,
"text": "<p>The answer is simple and works well with strings up to at least several thousand characters.</p>\n\n<p>Example 1:</p>\n\n<pre><code>Regex rx = new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\nresult = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );\n</code></pre>\n\n<p>Example 2:</p>\n\n<pre><code>Regex rx = new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\nresult = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );\n</code></pre>\n\n<p>The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0.</p>\n\n<p>To break down what's going on here, first we create a regular expression:</p>\n\n<pre><code>new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\n</code></pre>\n\n<p>Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string.</p>\n\n<p>The Unicode escape is processed like this:</p>\n\n<pre><code>((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });\n</code></pre>\n\n<p>Get the string representing the number part of the escape (skip the first two characters).</p>\n\n<pre><code>match.Value.Substring(2)\n</code></pre>\n\n<p>Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number.</p>\n\n<pre><code>NumberStyles.HexNumber\n</code></pre>\n\n<p>Then we cast the resulting number to a Unicode character:</p>\n\n<pre><code>(char)\n</code></pre>\n\n<p>And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace():</p>\n\n<pre><code>.ToString()\n</code></pre>\n\n<p>Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable.</p>\n"
},
{
"answer_id": 462586,
"author": "George Tsiokos",
"author_id": 5869,
"author_profile": "https://Stackoverflow.com/users/5869",
"pm_score": 3,
"selected": false,
"text": "<p>Refactored a little more:</p>\n\n<pre><code>Regex regex = new Regex (@\"\\\\U([0-9A-F]{4})\", RegexOptions.IgnoreCase);\nstring line = \"...\";\nline = regex.Replace (line, match => ((char)int.Parse (match.Groups[1].Value,\n NumberStyles.HexNumber)).ToString ());\n</code></pre>\n"
},
{
"answer_id": 11330975,
"author": "Baseem Najjar",
"author_id": 1472118,
"author_profile": "https://Stackoverflow.com/users/1472118",
"pm_score": 1,
"selected": false,
"text": "<p>I think you better add the small letters to your regular expression. It worked better for me.</p>\n\n<pre><code>Regex rx = new Regex(@\"\\\\[uU]([0-9A-Fa-f]{4})\");\nresult = rx.Replace(result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());\n</code></pre>\n"
},
{
"answer_id": 13142504,
"author": "Tarık Özgün Güner",
"author_id": 1786056,
"author_profile": "https://Stackoverflow.com/users/1786056",
"pm_score": 3,
"selected": false,
"text": "<p>This is the VB.NET equivalent:</p>\n\n<pre><code>Dim rx As New RegularExpressions.Regex(\"\\\\[uU]([0-9A-Fa-f]{4})\")\nresult = rx.Replace(result, Function(match) CChar(ChrW(Int32.Parse(match.Value.Substring(2), Globalization.NumberStyles.HexNumber))).ToString())\n</code></pre>\n"
},
{
"answer_id": 70197702,
"author": "Darzi",
"author_id": 17548939,
"author_profile": "https://Stackoverflow.com/users/17548939",
"pm_score": 1,
"selected": false,
"text": "<p>add <code>UnicodeExtensions.cs</code> class to your project:</p>\n<pre><code>public static class UnicodeExtensions\n{\n private static readonly Regex Regex = new Regex(@"\\\\[uU]([0-9A-Fa-f]{4})");\n\n public static string UnescapeUnicode(this string str)\n {\n return Regex.Replace(str,\n match => ((char) int.Parse(match.Value.Substring(2),\n NumberStyles.HexNumber)).ToString());\n }\n}\n</code></pre>\n<p>usage:</p>\n<pre><code>var test = "\\\\u0074\\\\u0068\\\\u0069\\\\u0073 \\\\u0069\\\\u0073 \\\\u0074\\\\u0065\\\\u0073\\\\u0074\\\\u002e";\nvar output = test.UnescapeUnicode(); // output is => this is test.\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2415/"
] |
Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string.
Example:
>
> "The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'."
>
>
>
|
The answer is simple and works well with strings up to at least several thousand characters.
Example 1:
```
Regex rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );
```
Example 2:
```
Regex rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );
```
The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0.
To break down what's going on here, first we create a regular expression:
```
new Regex( @"\\[uU]([0-9A-F]{4})" );
```
Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string.
The Unicode escape is processed like this:
```
((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });
```
Get the string representing the number part of the escape (skip the first two characters).
```
match.Value.Substring(2)
```
Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number.
```
NumberStyles.HexNumber
```
Then we cast the resulting number to a Unicode character:
```
(char)
```
And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace():
```
.ToString()
```
Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable.
|
183,914 |
<pre><code>echo $_POST["name"]; //returns the value a user typed into the "name" field
</code></pre>
<p>I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?</p>
|
[
{
"answer_id": 183917,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 1,
"selected": false,
"text": "<pre><code>array_keys($_POST)\n</code></pre>\n\n<p><a href=\"http://de.php.net/array_keys\" rel=\"nofollow noreferrer\">Manual</a></p>\n"
},
{
"answer_id": 183924,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 5,
"selected": true,
"text": "<p>Check out the array_keys() function assuming this is PHP.</p>\n\n<p><a href=\"http://us2.php.net/array_keys\" rel=\"noreferrer\">http://us2.php.net/array_keys</a></p>\n"
},
{
"answer_id": 184104,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "<p>$_POST is just a normal associative array so you can also loop over the entire thing like this:</p>\n\n<pre><code>foreach($_POST as $key=>$value)\n{\n echo \"$key=$value\";\n}\n</code></pre>\n"
},
{
"answer_id": 261281,
"author": "Tim",
"author_id": 33914,
"author_profile": "https://Stackoverflow.com/users/33914",
"pm_score": 2,
"selected": false,
"text": "<pre><code>while( list( $field, $value ) = each( $_POST )) {\n echo \"<p>\" . $field . \" = \" . $value . \"</p>\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 1137018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>@Tim: there was a <code>)</code> missing. so it should be:</p>\n\n<pre><code>while( list( $field, $value ) = each( $_POST )) {\n echo \"<p>\" . $field . \" = \" . $value . \"</p>\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 7777353,
"author": "Uğur Gümüşhan",
"author_id": 964196,
"author_profile": "https://Stackoverflow.com/users/964196",
"pm_score": 1,
"selected": false,
"text": "<pre><code>foreach($_POST as $rvar)\n{\n $rvarkey=key($_POST)\n $$rvarkey=mysql_real_escape_string($rvar);\n}\n\nit creates variables having the name of the request parameters which is pretty awesome.\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
```
echo $_POST["name"]; //returns the value a user typed into the "name" field
```
I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?
|
Check out the array\_keys() function assuming this is PHP.
<http://us2.php.net/array_keys>
|
183,921 |
<p>I'd like all queries like</p>
<pre><code>http://mysite.com/something/otherthing?foo=bar&x=y
</code></pre>
<p>to be rewritten as</p>
<pre><code>http://mysite.com/something/otherthing.php?foo=bar&x=y
</code></pre>
<p>In other words, just make the .php extension optional, universally.</p>
|
[
{
"answer_id": 183931,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 0,
"selected": false,
"text": "<p>Something like...</p>\n\n<pre><code>RewriteRule /something/(.+)?(.+) /something/$1.php?$2\n</code></pre>\n\n<p>would probably work.</p>\n"
},
{
"answer_id": 183969,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 1,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^.+$\nRewriteRule ^/?([^/\\.]+)$ /$1.php [L]\n</code></pre>\n\n<p>The idea is to make sure there's a query string (question mark plus stuff) and if so check if the stuff before the question mark has no extension and if so, append .php.</p>\n"
},
{
"answer_id": 184544,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>If you can change the httpd.conf and what to, you can also put:</p>\n\n<pre><code>ForceType application/x-httpd-php\n</code></pre>\n\n<p>in the file as it will force all the paths called to be PHP files. I think this also works with query strings.</p>\n"
},
{
"answer_id": 190364,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<p>Matches only paths with no extension:</p>\n\n<pre><code>RewriteRule ^(([^/]+/+)*[^\\.]+)$ $1.php\n</code></pre>\n\n<p>Edit: In my testing, the query string gets passed on automatically. If it doesn't, you can use this instead:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^(([^/]+/+)*[^\\.]+)$ $1.php?%1\n</code></pre>\n"
},
{
"answer_id": 383672,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 4,
"selected": true,
"text": "<p>I would do it this way. Basically, if file doesn't exist, try adding .php to it.</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.+)$ $1.php [QSA,L]\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
I'd like all queries like
```
http://mysite.com/something/otherthing?foo=bar&x=y
```
to be rewritten as
```
http://mysite.com/something/otherthing.php?foo=bar&x=y
```
In other words, just make the .php extension optional, universally.
|
I would do it this way. Basically, if file doesn't exist, try adding .php to it.
```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ $1.php [QSA,L]
```
|
183,923 |
<p>I have a class that has a Generic type "G"</p>
<p>In my class model i have</p>
<pre><code>public class DetailElement : ElementDefinition
</code></pre>
<p>Let's say i have a method like this</p>
<pre><code> public void DoSomething<G>(G generic)
where G : ElementDefinition
{
if (generic is DetailElement)
{
((DetailElement)generic).DescEN = "Hello people"; //line 1
//////
ElementDefinition element = generic;
((DetailElement)element).DescEN = "Hello again"; //line 3
//////
(generic as DetailElement).DescEN = "Howdy"; //line 5
}
else
{
//do other stuff
}
}
</code></pre>
<p>Compiler reports one error in line 1:</p>
<pre><code>Cannot convert type 'G' to 'DetailElement'
</code></pre>
<p>But line 3 works fine.
I can workaround this issue by doing the code written in line 5.</p>
<p><strong>What i would like to know is why does the compiler reports the error in line 1 and not the one in line 3, given that, as far as i know, they are identical.</strong></p>
<p>edit: I am afraid i might be missing some important piece of the framework logic</p>
<p>edit2: Although solutions for the compiler error are important, my question is about why the compiler reports an error on line 1 and not in line 3.</p>
|
[
{
"answer_id": 183949,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 1,
"selected": false,
"text": "<p>Shouldn't your where clause be \"where G : DetailElement\"?</p>\n\n<p>In the code you've written, a DetailElement is an ElementDefinition, but an ElementDefinition is not necessarily a DetailElement. So the implicit conversion is illegal.</p>\n\n<p>Are there other types of ElementDefinition that you might pass into this method? If so, they'll throw an exception when you try to cast them into DetailElement instances.</p>\n\n<p>EDIT:</p>\n\n<p>Okay, so now that you've changed your code listing, I can see that you're checking the type to make sure it really is a DetailElement before entering that block of code. Unfortunately, the fact of the matter is that you can't implicitly downcast, even if you've already checked the types yourself. I think you really ought to use the \"as\" keyword at the beginning of your block:</p>\n\n<pre><code>DetailElement detail = generic as DetailElement;\nif (detail == null) {\n // process other types of ElementDefinition\n} else {\n // process DetailElement objects\n}\n</code></pre>\n\n<p>Better yet, why not use polymorphism to allow each kind of ElementDefinition to define its own DoSomething method, and let the CLR take care of type-checking and method invocation for you?</p>\n"
},
{
"answer_id": 183951,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>If <code>G</code> was constrained to be a <code>DetailElement</code> (<code>where G : DetailElement</code>) then you can go ahead and cast <code>G</code> to ElementDefinition, i.e., \"<code>(ElementDefinition) generic</code>\". But because <code>G</code> might be another subclass of <code>ElementDefinition</code> other than <code>DetailElement</code> at run-time it won't allow it at compile-time where the type is unknown and unverifiable.</p>\n\n<p><strong>In line 3 the type you cast from <em>is</em> known to be an <code>ElementDefinition</code> so all you're doing is an up-cast</strong>. The compiler doesn't know if it will be a succcesful cast at run-time but it will trust you there. The compiler is not so trusting for generics.</p>\n\n<p>The <em><code>as</code></em> operator in line 5 might also return null and the compiler doesn't statically check the type to see if it's safe in that case. You can use <code>as</code> with <em>any</em> type, not just ones that are compatible with <code>ElementDefinition</code>. </p>\n\n<p>From <em><a href=\"http://msdn.microsoft.com/en-us/library/aa479858.aspx#bestpractices_topic5\" rel=\"nofollow noreferrer\" title=\"Generics FAQ: Best Practices\">Can I Cast to and from Generic Type Parameters?</a></em> on MSDN:</p>\n\n<blockquote>\n <p>The compiler will only let you implicitly cast generic type parameters to object, or to constraint-specified types.</p>\n \n <p>Such implicit casting is of course type safe, because any incompatibility is discovered at compile-time. </p>\n \n <p>The compiler will let you explicitly cast generic type parameters to any interface, but not to a class:</p>\n\n<pre><code> interface ISomeInterface {...}\n class SomeClass {...}\n class MyClass<T> \n {\n void SomeMethod(T t)\n {\n ISomeInterface obj1 = (ISomeInterface)t;//Compiles\n SomeClass obj2 = (SomeClass)t; //Does not compile\n }\n }\n</code></pre>\n \n <p>However, you can force a cast from a generic type parameter to any other type using a temporary object variable</p>\n\n<pre><code> void SomeMethod<T>(T t) \n { object temp = t;\n MyOtherClass obj = (MyOtherClass)temp; \n }\n</code></pre>\n \n <p>Needless to say, such explicit casting is dangerous because it may throw an exception at run-time if the concrete type used instead of the generic type parameter does not derive from the type you explicitly cast to. </p>\n \n <p>Instead of risking a casting exception, a better approach is to use the <code>is</code> or <code>as</code> operators. The <code>is</code> operator returns true if the generic type parameter is of the queried type, and <code>as</code> will perform a cast if the types are compatible, and will return null otherwise. </p>\n\n<pre><code>public void SomeMethod(T t)\n {\n if(t is int) {...}\n\n string str = t as string;\n if(str != null) {...}\n }\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 184208,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 0,
"selected": false,
"text": "<p>This will lead to a bit more code if you have a lot of ElementDefinitions you are worried about, but is probably the slickest you will get that doesn't involve is then as nonsense.</p>\n\n<pre><code> public void DoSomething<G>(G generic)\n where G : ElementDefinition\n {\n DetailElement detail = generic as DetailElement;\n if (detail != null)\n {\n detail.DescEN = \"Hello people\";\n }\n else\n {\n //do other stuff\n }\n }\n</code></pre>\n\n<p>Another possible solution that I have used when I needed such information, in loo of a temporary object variable.</p>\n\n<pre><code>DetailElement detail = (DetailElement)(object)generic;\n</code></pre>\n\n<p>It works, but the as form is probably the best. </p>\n"
},
{
"answer_id": 184393,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 1,
"selected": false,
"text": "<p>Generally, upcasting is a code smell. You can avoid it by method overloading. Try this:</p>\n\n<pre><code>public void DoSomething(DetailElement detailElement)\n{\n // do DetailElement specific stuff\n}\n\npublic void DoSomething<G>(G elementDefinition)\n where G : ElementDefinition\n{\n // do generic ElementDefinition stuff\n}\n</code></pre>\n\n<p>You can then take advantage of method overloading by using this code:</p>\n\n<pre><code>DetailElement foo = new DetailElement();\n\nDoSomething(foo); // calls the non-generic method\nDoSomething((ElementDefinition) foo); // calls the generic method\n</code></pre>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
] |
I have a class that has a Generic type "G"
In my class model i have
```
public class DetailElement : ElementDefinition
```
Let's say i have a method like this
```
public void DoSomething<G>(G generic)
where G : ElementDefinition
{
if (generic is DetailElement)
{
((DetailElement)generic).DescEN = "Hello people"; //line 1
//////
ElementDefinition element = generic;
((DetailElement)element).DescEN = "Hello again"; //line 3
//////
(generic as DetailElement).DescEN = "Howdy"; //line 5
}
else
{
//do other stuff
}
}
```
Compiler reports one error in line 1:
```
Cannot convert type 'G' to 'DetailElement'
```
But line 3 works fine.
I can workaround this issue by doing the code written in line 5.
**What i would like to know is why does the compiler reports the error in line 1 and not the one in line 3, given that, as far as i know, they are identical.**
edit: I am afraid i might be missing some important piece of the framework logic
edit2: Although solutions for the compiler error are important, my question is about why the compiler reports an error on line 1 and not in line 3.
|
If `G` was constrained to be a `DetailElement` (`where G : DetailElement`) then you can go ahead and cast `G` to ElementDefinition, i.e., "`(ElementDefinition) generic`". But because `G` might be another subclass of `ElementDefinition` other than `DetailElement` at run-time it won't allow it at compile-time where the type is unknown and unverifiable.
**In line 3 the type you cast from *is* known to be an `ElementDefinition` so all you're doing is an up-cast**. The compiler doesn't know if it will be a succcesful cast at run-time but it will trust you there. The compiler is not so trusting for generics.
The *`as`* operator in line 5 might also return null and the compiler doesn't statically check the type to see if it's safe in that case. You can use `as` with *any* type, not just ones that are compatible with `ElementDefinition`.
From *[Can I Cast to and from Generic Type Parameters?](http://msdn.microsoft.com/en-us/library/aa479858.aspx#bestpractices_topic5 "Generics FAQ: Best Practices")* on MSDN:
>
> The compiler will only let you implicitly cast generic type parameters to object, or to constraint-specified types.
>
>
> Such implicit casting is of course type safe, because any incompatibility is discovered at compile-time.
>
>
> The compiler will let you explicitly cast generic type parameters to any interface, but not to a class:
>
>
>
> ```
> interface ISomeInterface {...}
> class SomeClass {...}
> class MyClass<T>
> {
> void SomeMethod(T t)
> {
> ISomeInterface obj1 = (ISomeInterface)t;//Compiles
> SomeClass obj2 = (SomeClass)t; //Does not compile
> }
> }
>
> ```
>
> However, you can force a cast from a generic type parameter to any other type using a temporary object variable
>
>
>
> ```
> void SomeMethod<T>(T t)
> { object temp = t;
> MyOtherClass obj = (MyOtherClass)temp;
> }
>
> ```
>
> Needless to say, such explicit casting is dangerous because it may throw an exception at run-time if the concrete type used instead of the generic type parameter does not derive from the type you explicitly cast to.
>
>
> Instead of risking a casting exception, a better approach is to use the `is` or `as` operators. The `is` operator returns true if the generic type parameter is of the queried type, and `as` will perform a cast if the types are compatible, and will return null otherwise.
>
>
>
> ```
> public void SomeMethod(T t)
> {
> if(t is int) {...}
>
> string str = t as string;
> if(str != null) {...}
> }
>
> ```
>
>
|
183,928 |
<p>How do I create subdomain like <code>http://user.mywebsite.example</code>? Do I have to access <code>.htaccess</code> somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?</p>
<p>To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?</p>
|
[
{
"answer_id": 183939,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.</p>\n\n<p>Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.</p>\n"
},
{
"answer_id": 183944,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "<p>You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.</p>\n"
},
{
"answer_id": 183971,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 8,
"selected": true,
"text": "<p>You're looking to create a custom <strong>A record</strong>.</p>\n<p>I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:</p>\n<pre><code>*.mywebsite.example IN A 127.0.0.1\n</code></pre>\n<p><em><code>127.0.0.1</code> would be the IP address of your webserver. The method of actually adding the record will depend on your host.</em></p>\n<hr />\n<p>Then you need to configure your web-server to serve all subdomains.</p>\n<ul>\n<li>Nginx: <code>server_name .mywebsite.example</code></li>\n<li>Apache: <code>ServerAlias *.mywebsite.example</code></li>\n</ul>\n<p>Regarding .htaccess, you don't really need any rewrite rules. The <code>HTTP_HOST</code> header is available in PHP as well, so you can get it already, like</p>\n<pre><code>$username = strtok($_SERVER['HTTP_HOST'], ".");\n</code></pre>\n<hr />\n<p>If you don't have access to DNS/web-server config, doing it like <code>http://mywebsite.example/user</code> would be a lot easier to set up if it's an option.</p>\n"
},
{
"answer_id": 184217,
"author": "gradbot",
"author_id": 17919,
"author_profile": "https://Stackoverflow.com/users/17919",
"pm_score": 5,
"selected": false,
"text": "<p>I do it a little different from Mark. I pass the entire domain and grab the subdomain in PHP.</p>\n<pre><code>RewriteCond {REQUEST_URI} !\\.(png|gif|jpg)$\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}\n</code></pre>\n<p>This ignores images and maps everything else to my <code>index.php</code> file. So if I go to</p>\n<pre><code>http://fred.mywebsite.example/album/Dance/now\n</code></pre>\n<p>I get back</p>\n<pre><code>http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example\n</code></pre>\n<p>Then in my <code>index.php</code> code I just explode my username off of the hostName. This gives me nice pretty SEO URLs.</p>\n"
},
{
"answer_id": 185275,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 3,
"selected": false,
"text": "<p>Don't fuss around with <code>.htaccess</code> files when you can use [Apache mass virtual hosting][1].</p>\n<p>From the documentation:</p>\n<blockquote>\n<p><code>#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs</code></p>\n</blockquote>\n<p>In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.</p>\n<p>The only drawback is that the environment variable <code>DOCUMENT_ROOT</code> is not correctly set to the <em>used</em> subdirectory, but the default document_root in de htconfig.\n[1]: <a href=\"http://httpd.apache.org/docs/2.0/vhosts/mass.html\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/2.0/vhosts/mass.html</a></p>\n"
},
{
"answer_id": 602683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>We setup wildcard DNS like they explained above. So the a record is <code>*.yourname.example</code></p>\n<p>Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.</p>\n<p>We use the following code:</p>\n<pre><code>$url=$_SERVER["REQUEST_URI"];\n$account=str_replace(".yourdomain.com","",$url);\n</code></pre>\n<p>This code just sets the <code>$account</code> variable the same as the subdomain. You could then retrieve their files and other information based on their account.</p>\n<p>This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited <code>.htaccess</code> this method should work (as long as your host will setup the wildcard for you).</p>\n<p>We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.</p>\n"
},
{
"answer_id": 3617461,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 5,
"selected": false,
"text": "<p>The feature you are after is called <a href=\"http://www.google.com.au/search?sourceid=chrome&ie=UTF-8&q=wildcard+subdomains\" rel=\"nofollow noreferrer\">Wildcard Subdomains</a>. It allows you not have to setup DNS for each subdomain, and instead use Apache rewrites for the redirection. You can find a nice tutorial <a href=\"http://steinsoft.net/static/archive/2014/steinsoft.net/index5d37.html?site=Programming/Articles/apachewildcarddomain\" rel=\"nofollow noreferrer\">here</a>, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:</p>\n<pre><code><VirtualHost 111.22.33.55>\n DocumentRoot /www/subdomain\n ServerName www.domain.example\n ServerAlias *.domain.example\n</VirtualHost>\n</code></pre>\n<p>However as it required the use of VirtualHosts it must be set in the server's <code>httpd.conf</code> file, instead of a local <code>.htaccess</code>.</p>\n"
},
{
"answer_id": 25284034,
"author": "kiwixz",
"author_id": 3494492,
"author_profile": "https://Stackoverflow.com/users/3494492",
"pm_score": 1,
"selected": false,
"text": "<p>I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.</p>\n"
},
{
"answer_id": 27627125,
"author": "Alex Khimich",
"author_id": 2213708,
"author_profile": "https://Stackoverflow.com/users/2213708",
"pm_score": 3,
"selected": false,
"text": "<p>Simple PHP solution for subdomains and multi-domain web apps</p>\n<p>Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve <code>example.org</code></p>\n<pre><code>A record => *.example.org\nA record => *.example.net\n</code></pre>\n<p>Step 2. Check uniquity of logins when user registering or changing login.\nAlso, avoid dots in those logins.</p>\n<p>Step 3. Then check the query\n<?php</p>\n<pre><code> // Request was http://qwerty.example.org\n $q = explode('.', $_SERVER['HTTP_HOST']);\n /*\n We get following array\n Array\n (\n [0] => qwerty\n [1] => example\n [2] => org\n )\n */\n\n // Step 4.\n // If second piece of array exists, request was for\n // SUBDOMAIN which is stored in zero-piece $q[0]\n // otherwise it was for DOMAIN\n\n if(isset($q[2])) {\n // Find stuff in database for login $q[0] or here it is "qwerty"\n // Use $q[1] to check which domain is asked if u serve multiple domains\n }\n\n?>\n</code></pre>\n<p>This solution may serve different domains</p>\n<pre><code>qwerty.example.org\nqwerty.example.net\n\njohnsmith.somecompany.example\npaulsmith.somecompany.example\n</code></pre>\n<p>If you need same nicks on different domains served differently,\nyou may need to store user choise for domain when registering login.</p>\n<pre><code>smith.example.org // Show info about John Smith\nsmith.example.net // Show info about Paul Smith\n</code></pre>\n"
},
{
"answer_id": 36459894,
"author": "Dan Bray",
"author_id": 2452680,
"author_profile": "https://Stackoverflow.com/users/2452680",
"pm_score": 2,
"selected": false,
"text": "<p>This can be achieved in <code>.htaccess</code> provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named <code>*</code> and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your <code>.htaccess</code> file:</p>\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} !^www\\.website\\.example$\nRewriteCond %{HTTP_HOST} ^(\\w+)\\.website\\.example$\nRewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\\1\nRewriteRule ^(.*)$ /%1/$1 [QSA]\n</code></pre>\n<p>Finally, create a folder for your subdomain and place the subdomains files.</p>\n"
},
{
"answer_id": 58730883,
"author": "Abdo-Host",
"author_id": 2262856,
"author_profile": "https://Stackoverflow.com/users/2262856",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>Create Dynamic Subdomains using PHP and <code>.htaccess</code></p>\n</blockquote>\n<p>#(1) Root <code>.htaccess</code>\nThis file is redirection <code>http://www.yourwebsite.example</code> to <code>http://yourwebsite.example</code> for home page use. All of the subdomain redirection to yourwebsite_folder</p>\n<pre><code>RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^www.yourwebsite.example\nRewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]\n\nRewriteCond %{HTTP_HOST} ^yourwebsite\\.example $\nRewriteCond %{REQUEST_URI} !^/yourwebsite_folder/\nRewriteRule (.*) /yourwebsite_folder/$1\n\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteCond %{REQUEST_URI} !^/yourwebsite_folder/\nRewriteRule (.*) /yourwebsite_folder/$1\n</code></pre>\n<p>#(2) Inside Folder <code>.htaccess</code>\nThis file is rewriting the subdomain URLs.</p>\n<p><code>http://yourwebsite.example/index.php?siteName=9lessons</code>\nto\n<code>http://9lessons.yourwebsite.example</code></p>\n<pre><code>Options +FollowSymLinks\nRewriteEngine On\n\nRewriteBase /\n\nRewriteRule ^([aA-zZ])$ index.php?siteName=$1\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteRule (.*) index.php?siteName=%1\n</code></pre>\n<p>More <code>.htaccess</code> tips: <a href=\"https://www.9lessons.info/2013/11/htaccess-file-tutorial-and-tips.html\" rel=\"nofollow noreferrer\">Htaccess File Tutorial and Tips.</a></p>\n<p>#index.php\nThis file contains simple PHP code, using regular expressions validating the subdomain value.</p>\n<pre><code><?php\n$siteName='';\nif($_GET['siteName'] )\n{\n$sitePostName=$_GET['siteName'];\n$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);\n if($siteNameCheck)\n {\n //Do something. Eg: Connect database and validate the siteName.\n }\n else\n {\n header("Location: http://yourwebsite.example/404.php");\n }\n}\n?>\n//HTML Code\n<!DOCTYPE html>\n<html>\n<head>\n<title>Project Title</title>\n</head>\n<body>\n<?php if($siteNameCheck) { ?>\n//Home Page\n<?php } else { ?>\n//Redirect to Subdomain Page.\n<?php } ?>\n</body>\n</html>\n</code></pre>\n<p>#No Subdomain Folder\nIf you are using root directory(htdocs/public_html) as a project directory, use this following <code>.htaccess</code> file.</p>\n<pre><code>Options +FollowSymLinks\nRewriteEngine On\n\nRewriteBase /\n\nRewriteCond %{HTTP_HOST} ^www.yourwebsite.example\nRewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]\n\nRewriteRule ^([aA-zZ])$ index.php?siteName=$1\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteRule (.*) index.php?siteName=%1\n</code></pre>\n"
},
{
"answer_id": 73524700,
"author": "David Warutumo",
"author_id": 14574573,
"author_profile": "https://Stackoverflow.com/users/14574573",
"pm_score": -1,
"selected": false,
"text": "<h3>You can accomplish this via two steps.</h3>\n<ol>\n<li>Setup wildcard subdomain</li>\n<li>Get the subdomain entered by user</li>\n<li>Validate the subdomain</li>\n</ol>\n<hr />\n<h3>1. Setup wildcard subdomain</h3>\n<p>This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows\n<a href=\"https://i.stack.imgur.com/ZAGKC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZAGKC.png\" alt=\"creating a sub domain in namecheap\" /></a></p>\n<ul>\n<li>go to cPanel</li>\n<li>go to sub domains</li>\n<li>enter "*" as the value of subdomain</li>\n</ul>\n<p>Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.</p>\n<h3>2. Get the subdomain entered by user</h3>\n<p>You can now add a php file in the wildcard directory in file manager.</p>\n<pre><code><?php\n \n$link = $_SERVER['HTTP_HOST'];\n$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n?>\n\n<!DOCTYPE html>\n<html lang="en">\n \n <head>\n \n <title>Wildcard Subdomain</title>\n \n </head>\n \n <body>\n <h1>The visitor went to \n <?php \n \n echo "<br>";\n \n print("link is: ".$link);\n \n print("<br><br>");\n \n echo "actual file: ".$actual_link;\n ?> \n </h1>\n \n </body>\n</html>\n</code></pre>\n\n<h3>3. Validate the subdomain</h3>\n<p>You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
How do I create subdomain like `http://user.mywebsite.example`? Do I have to access `.htaccess` somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?
To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?
|
You're looking to create a custom **A record**.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
```
*.mywebsite.example IN A 127.0.0.1
```
*`127.0.0.1` would be the IP address of your webserver. The method of actually adding the record will depend on your host.*
---
Then you need to configure your web-server to serve all subdomains.
* Nginx: `server_name .mywebsite.example`
* Apache: `ServerAlias *.mywebsite.example`
Regarding .htaccess, you don't really need any rewrite rules. The `HTTP_HOST` header is available in PHP as well, so you can get it already, like
```
$username = strtok($_SERVER['HTTP_HOST'], ".");
```
---
If you don't have access to DNS/web-server config, doing it like `http://mywebsite.example/user` would be a lot easier to set up if it's an option.
|
183,932 |
<p>I have an app using PHP and the PayPal API. The basic way it works to get a payment is that you do a web service call to PayPal to get a token and then do a browser redirect to PayPal with that token for the user to pay. After the payment details have been confirmed, PayPal redirects back to the URL you originally set in the service call.</p>
<p>This all works, millions of people use it every day, et cetera.</p>
<p>Strange thing is, when PayPal redirects back, the PHP session is gone. It's a <a href="http://www.paypaldeveloper.com/pdn/board/message?board.id=sandbox&thread.id=8672" rel="nofollow noreferrer">well-documented issue</a>.</p>
<p>First question: why is this happening? Both pages are on the same domain, both use HTTPS. The session works for all requests up until the PayPal redirect back.</p>
<p>The linked forum thread suggests a workaround, to persist the session ID in the PayPal request and then to retrieve it later and restore the session. Great, except it doesn't seem to work.</p>
<p>I can add some log statements:</p>
<pre><code>log(session_id());
</code></pre>
<p>before and after the various redirects. When coming back from PayPal, I log some more.</p>
<pre><code>log("session id is " . session_id());
$session_id = get_session_id_from_paypal();
log("setting it back to " . $session_id);
session_id($session_id);
session_start();
log("session id is now " . session_id());
</code></pre>
<p>The result is not at all what I'd expect:</p>
<blockquote>
<p><code>session_id</code> is fc8f459a186a3f4695ff9ac71b563825<br>
setting it back to 82460dcf8c8ddd538466e7cb89712e72<br>
<code>session_id</code> is now 360ba3fd99d233e0735397278d2b2e55 </p>
</blockquote>
<p>Second question: why is the session id not at all what I set it to? What am I doing wrong? Or, at least, why do none of the session variables come back?</p>
|
[
{
"answer_id": 184003,
"author": "vIceBerg",
"author_id": 17766,
"author_profile": "https://Stackoverflow.com/users/17766",
"pm_score": 1,
"selected": false,
"text": "<p>Can you do a phpinfo() and tell if session.auto_start is true?</p>\n"
},
{
"answer_id": 184429,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p>Just an idea ...</p>\n\n<p>Do you have <code>session.referer_check</code> set to your host perhaps?\nThe default is the empty string, but it might have been changed ... and when the page 'comes back' from PayPal, php will trash the session info.</p>\n\n<p>You can check the <code>session.referer_check</code> with phpinfo().</p>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6010/"
] |
I have an app using PHP and the PayPal API. The basic way it works to get a payment is that you do a web service call to PayPal to get a token and then do a browser redirect to PayPal with that token for the user to pay. After the payment details have been confirmed, PayPal redirects back to the URL you originally set in the service call.
This all works, millions of people use it every day, et cetera.
Strange thing is, when PayPal redirects back, the PHP session is gone. It's a [well-documented issue](http://www.paypaldeveloper.com/pdn/board/message?board.id=sandbox&thread.id=8672).
First question: why is this happening? Both pages are on the same domain, both use HTTPS. The session works for all requests up until the PayPal redirect back.
The linked forum thread suggests a workaround, to persist the session ID in the PayPal request and then to retrieve it later and restore the session. Great, except it doesn't seem to work.
I can add some log statements:
```
log(session_id());
```
before and after the various redirects. When coming back from PayPal, I log some more.
```
log("session id is " . session_id());
$session_id = get_session_id_from_paypal();
log("setting it back to " . $session_id);
session_id($session_id);
session_start();
log("session id is now " . session_id());
```
The result is not at all what I'd expect:
>
> `session_id` is fc8f459a186a3f4695ff9ac71b563825
>
> setting it back to 82460dcf8c8ddd538466e7cb89712e72
>
> `session_id` is now 360ba3fd99d233e0735397278d2b2e55
>
>
>
Second question: why is the session id not at all what I set it to? What am I doing wrong? Or, at least, why do none of the session variables come back?
|
Just an idea ...
Do you have `session.referer_check` set to your host perhaps?
The default is the empty string, but it might have been changed ... and when the page 'comes back' from PayPal, php will trash the session info.
You can check the `session.referer_check` with phpinfo().
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.