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
|
---|---|---|---|---|---|---|
220,188 |
<p><a href="http://www.w3.org/TR/REC-html40/interact/scripts.html" rel="noreferrer"><strong>According to spec</strong></a>, only the <code>BODY</code> and <code>FRAMESET</code> elements provide an "onload" event to attach to, but I would like to know when a dynamically-created DOM element has been added to the DOM in JavaScript.</p>
<p>The super-naive heuristics I am currently using, which work, are as follows:</p>
<ul>
<li>Traverse the <strong>parentNode</strong> property of the element back until I find the ultimate ancestor (i.e. parentNode.parentNode.parentNode.etc until parentNode is null)<br /><br /></li>
<li>If the ultimate ancestor has a defined, non-null <strong>body</strong> property<br /><br />
<ul>
<li>assume the element in question is part of the dom</li>
</ul></li>
<li>else<br /><br />
<ul>
<li>repeat these steps again in 100 milliseconds</li>
</ul></li>
</ul>
<p>What I am after is either confirmation that what I am doing is sufficient (again, it is working in both IE7 and FF3) or a better solution that, for whatever reason, I have been completely oblivious to; perhaps other properties I should be checking, etc.</p>
<hr>
<p>EDIT: I want a browser-agnostic way of doing this, I don't live in a one-browser world, unfortunately; that said, browser-specific information is appreciated, but please note which browser you know that it <em>does</em> work in. Thanks!</p>
|
[
{
"answer_id": 220192,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 1,
"selected": false,
"text": "<p>You want the <code>DOMNodeInserted</code> event (or <code>DOMNodeInsertedIntoDocument</code>).</p>\n\n<p>Edit: It is entirely possible these events are not supported by IE, but I can't test that right now.</p>\n"
},
{
"answer_id": 220224,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": false,
"text": "<p>Can you no do a <code>document.getElementById('newElementId');</code> and see if that returns true. If not, like you say, wait 100ms and try again?</p>\n"
},
{
"answer_id": 220248,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": -1,
"selected": false,
"text": "<p>Neither of <strong>DOMNodeInserted</strong> or <strong>DOMNodeInsertedIntoDocument</strong> events is supported in IE. Another missing from IE [only] feature of DOM is <strong>compareDocumentPosition</strong> function that is designed to do what its name suggests. </p>\n\n<p>As for the suggested solution, I think there is no better one (unless you do some dirty tricks like overwriting native DOM members implementations)</p>\n\n<p>Also, correcting the title of the question: dynamically created Element is part of the DOM from the moment it is created, it can be appended to a document fragment, or to another element, but it might not be appended to a document.</p>\n\n<p>I also think that the problem you described is not the problem that you have, this one looks to be rather one of the potential solutions to you problem. Can you probably explain in details the use case?</p>\n"
},
{
"answer_id": 220893,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<p>You could query <strong>document.getElementsByTagName(\"*\").length</strong> or create a custom appendChild function like the folllowing:</p>\n\n<pre><code>var append = function(parent, child, onAppend) {\n parent.appendChild(child);\n if (onAppend) onAppend(child);\n}\n\n//inserts a div into body and adds the class \"created\" upon insertion\nappend(document.body, document.createElement(\"div\"), function(el) {\n el.className = \"created\";\n});\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p><em>By request, adding the information from my comments into my post</em></p>\n\n<p>There was a <a href=\"http://ajaxian.com/archives/peppy-css3-selector-engine#comments\" rel=\"nofollow noreferrer\">comment by John Resig</a> on the Peppy library on Ajaxian today that seemed to suggest that his Sizzle library might be able to handle DOM insertion events. I'm curious to see if there will be code to handle IE as well</p>\n\n<p>Following on the idea of polling, I've read that some element properties are not available until the element has been appended to the document (for example element.scrollTop), maybe you could poll that instead of doing all the DOM traversal.</p>\n\n<p>One last thing: in IE, one approach that might be worth exploring is to play with the onpropertychange event. I reckon appending it to the document is bound to trigger that event for at least one property.</p>\n"
},
{
"answer_id": 222441,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 2,
"selected": false,
"text": "<p>In a perfect world you could hook the mutation events. I have doubts that they work reliably even on standards browsers. It sounds like you've already implemented a mutation event so you could possibly add this to use a native mutation event rather than timeout polling on browsers that support those. </p>\n\n<p>I've seen DOM-change implementations that monitor changes by comparing <code>document.body.innerHTML</code> to last saved <code>.innerHTML</code>, which isn't exactly elegant (but works). Since you're ultimately going to check if a specific node has been added yet, then you're better off just checking that each interrupt.</p>\n\n<p>Improvements I can think of are <del>using <code>.offsetParent</code> rather than <code>.parentNode</code> as it will likely cut a few parents out of your loop</del> (see comments). Or using <code>compareDocumentIndex()</code> on all but IE and testing <code>.sourceIndex</code> propery for IE (should be -1 if node isn't in the DOM).</p>\n\n<p>This might also help: <a href=\"http://ejohn.org/blog/comparing-document-position/\" rel=\"nofollow noreferrer\">X browser compareDocumentIndex implementaion by John Resig</a>.</p>\n"
},
{
"answer_id": 850995,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "<p>UPDATE: For anyone interested in it, here is the implementation I finally used:</p>\n\n<pre><code>function isInDOMTree(node) {\n // If the farthest-back ancestor of our node has a \"body\"\n // property (that node would be the document itself), \n // we assume it is in the page's DOM tree.\n return !!(findUltimateAncestor(node).body);\n}\nfunction findUltimateAncestor(node) {\n // Walk up the DOM tree until we are at the top (parentNode \n // will return null at that point).\n // NOTE: this will return the same node that was passed in \n // if it has no ancestors.\n var ancestor = node;\n while(ancestor.parentNode) {\n ancestor = ancestor.parentNode;\n }\n return ancestor;\n}\n</code></pre>\n\n<p>The reason I wanted this is to provide a way of synthesizing the <code>onload</code> event for DOM elements. Here is that function (although I am using something slightly different because I am using it in conjunction with <a href=\"http://www.mochikit.com/\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a>):</p>\n\n<pre><code>function executeOnLoad(node, func) {\n // This function will check, every tenth of a second, to see if \n // our element is a part of the DOM tree - as soon as we know \n // that it is, we execute the provided function.\n if(isInDOMTree(node)) {\n func();\n } else {\n setTimeout(function() { executeOnLoad(node, func); }, 100);\n }\n}\n</code></pre>\n\n<p>For an example, this setup could be used as follows:</p>\n\n<pre><code>var mySpan = document.createElement(\"span\");\nmySpan.innerHTML = \"Hello world!\";\nexecuteOnLoad(mySpan, function(node) { \n alert('Added to DOM tree. ' + node.innerHTML);\n});\n\n// now, at some point later in code, this\n// node would be appended to the document\ndocument.body.appendChild(mySpan);\n\n// sometime after this is executed, but no more than 100 ms after,\n// the anonymous function I passed to executeOnLoad() would execute\n</code></pre>\n\n<p>Hope that is useful to someone.</p>\n\n<p>NOTE: the reason I ended up with this solution rather than <a href=\"https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224\"><strong>Darryl's answer</strong></a> was because the getElementById technique only works if you are within the same document; I have some iframes on a page and the pages communicate between each other in some complex ways - when I tried this, the problem was that it couldn't find the element because it was part of a different document than the code it was executing in.</p>\n"
},
{
"answer_id": 2413678,
"author": "nik",
"author_id": 290112,
"author_profile": "https://Stackoverflow.com/users/290112",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another solution to the problem extracted from the jQuery code.\nThe following function can be used to check if a node is attached to the DOM or if it is \"disconnected\".</p>\n\n<pre>\nfunction isDisconnected( node ) {\n return !node || !node.parentNode || node.parentNode.nodeType === 11;\n}\n</pre>\n\n<p>A nodeType === 11 defines a DOCUMENT_FRAGMENT_NODE, which is a node not connected to the document object.</p>\n\n<p>For further information see the following article by John Resig:\n<a href=\"http://ejohn.org/blog/dom-documentfragments/\" rel=\"nofollow noreferrer\">http://ejohn.org/blog/dom-documentfragments/</a></p>\n"
},
{
"answer_id": 13725984,
"author": "Chris Calo",
"author_id": 101869,
"author_profile": "https://Stackoverflow.com/users/101869",
"pm_score": 4,
"selected": false,
"text": "<p>The most straightforward answer is to make use of the <a href=\"https://developer.mozilla.org/en-US/docs/DOM/Node.contains\" rel=\"noreferrer\"><code>Node.contains</code></a> method, supported by Chrome, Firefox (Gecko), Internet Explorer, Opera, and Safari. Here is an example:</p>\n\n<pre><code>var el = document.createElement(\"div\");\nconsole.log(document.body.contains(el)); // false\ndocument.body.appendChild(el);\nconsole.log(document.body.contains(el)); // true\ndocument.body.removeChild(el);\nconsole.log(document.body.contains(el)); // false\n</code></pre>\n\n<p>Ideally, we would use <code>document.contains(el)</code>, but that doesn't work in IE, so we use <code>document.body.contains(el)</code>.</p>\n\n<p>Unfortunately, you still have to poll, but checking whether an element is in the document yet is very simple:</p>\n\n<pre><code>setTimeout(function test() {\n if (document.body.contains(node)) {\n func();\n } else {\n setTimeout(test, 50);\n }\n}, 50);\n</code></pre>\n\n<p>If you're okay with adding some CSS to your page, here's another clever technique that uses animations to detect node insertions: <a href=\"http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/\" rel=\"noreferrer\">http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/</a></p>\n"
},
{
"answer_id": 15845595,
"author": "ydaniv",
"author_id": 531132,
"author_profile": "https://Stackoverflow.com/users/531132",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of walking the DOM tree up to the document element just use <code>element.ownerDocument</code>.\nsee here: <a href=\"https://developer.mozilla.org/en-US/docs/DOM/Node.ownerDocument\">https://developer.mozilla.org/en-US/docs/DOM/Node.ownerDocument</a>\nand do this:</p>\n\n<pre><code>element.ownerDocument.body.contains(element)\n</code></pre>\n\n<p>and you're good.</p>\n"
},
{
"answer_id": 15938845,
"author": "user1403517",
"author_id": 1403517,
"author_profile": "https://Stackoverflow.com/users/1403517",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var finalElement=null; \n</code></pre>\n\n<p>I am building dom objects in a loop, when the loop is on the last cycle and the <code>lastDomObject</code> is created then: </p>\n\n<pre><code> finalElement=lastDomObject; \n</code></pre>\n\n<p>leave loop:</p>\n\n<pre><code>while (!finalElement) { } //this is the delay... \n</code></pre>\n\n<p>The next action can use any of the newly created dom objects. It worked on the first try.</p>\n"
},
{
"answer_id": 48514909,
"author": "Elliot B.",
"author_id": 1215133,
"author_profile": "https://Stackoverflow.com/users/1215133",
"pm_score": 2,
"selected": false,
"text": "<p><strong>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver\" rel=\"nofollow noreferrer\">MutationObserver</a> is what you should use to detect when an element has been added to the DOM.</strong> MutationObservers are now widely supported across all modern browsers (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc).</p>\n\n<p>Here's a simple example of how you can use a <code>MutationObserver</code> to listen for when an element is added to the DOM. </p>\n\n<p>For brevity, I'm using jQuery syntax to build the node and insert it into the DOM.</p>\n\n<pre><code>var myElement = $(\"<div>hello world</div>\")[0];\n\nvar observer = new MutationObserver(function(mutations) {\n if (document.contains(myElement)) {\n console.log(\"It's in the DOM!\");\n observer.disconnect();\n }\n});\n\nobserver.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});\n\n$(\"body\").append(myElement); // console.log: It's in the DOM!\n</code></pre>\n\n<p>The <code>observer</code> event handler will trigger whenever any node is added or removed from the <code>document</code>. Inside the handler, we then perform a <code>contains</code> check to determine if <code>myElement</code> is now in the <code>document</code>.</p>\n\n<p>You don't need to iterate over each MutationRecord stored in <code>mutations</code> because you can perform the <code>document.contains</code> check directly upon <code>myElement</code>.</p>\n\n<p>To improve performance, replace <code>document</code> with the specific element that will contain <code>myElement</code> in the DOM.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790/"
] |
[**According to spec**](http://www.w3.org/TR/REC-html40/interact/scripts.html), only the `BODY` and `FRAMESET` elements provide an "onload" event to attach to, but I would like to know when a dynamically-created DOM element has been added to the DOM in JavaScript.
The super-naive heuristics I am currently using, which work, are as follows:
* Traverse the **parentNode** property of the element back until I find the ultimate ancestor (i.e. parentNode.parentNode.parentNode.etc until parentNode is null)
* If the ultimate ancestor has a defined, non-null **body** property
+ assume the element in question is part of the dom
* else
+ repeat these steps again in 100 milliseconds
What I am after is either confirmation that what I am doing is sufficient (again, it is working in both IE7 and FF3) or a better solution that, for whatever reason, I have been completely oblivious to; perhaps other properties I should be checking, etc.
---
EDIT: I want a browser-agnostic way of doing this, I don't live in a one-browser world, unfortunately; that said, browser-specific information is appreciated, but please note which browser you know that it *does* work in. Thanks!
|
UPDATE: For anyone interested in it, here is the implementation I finally used:
```
function isInDOMTree(node) {
// If the farthest-back ancestor of our node has a "body"
// property (that node would be the document itself),
// we assume it is in the page's DOM tree.
return !!(findUltimateAncestor(node).body);
}
function findUltimateAncestor(node) {
// Walk up the DOM tree until we are at the top (parentNode
// will return null at that point).
// NOTE: this will return the same node that was passed in
// if it has no ancestors.
var ancestor = node;
while(ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
return ancestor;
}
```
The reason I wanted this is to provide a way of synthesizing the `onload` event for DOM elements. Here is that function (although I am using something slightly different because I am using it in conjunction with [**MochiKit**](http://www.mochikit.com/)):
```
function executeOnLoad(node, func) {
// This function will check, every tenth of a second, to see if
// our element is a part of the DOM tree - as soon as we know
// that it is, we execute the provided function.
if(isInDOMTree(node)) {
func();
} else {
setTimeout(function() { executeOnLoad(node, func); }, 100);
}
}
```
For an example, this setup could be used as follows:
```
var mySpan = document.createElement("span");
mySpan.innerHTML = "Hello world!";
executeOnLoad(mySpan, function(node) {
alert('Added to DOM tree. ' + node.innerHTML);
});
// now, at some point later in code, this
// node would be appended to the document
document.body.appendChild(mySpan);
// sometime after this is executed, but no more than 100 ms after,
// the anonymous function I passed to executeOnLoad() would execute
```
Hope that is useful to someone.
NOTE: the reason I ended up with this solution rather than [**Darryl's answer**](https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224) was because the getElementById technique only works if you are within the same document; I have some iframes on a page and the pages communicate between each other in some complex ways - when I tried this, the problem was that it couldn't find the element because it was part of a different document than the code it was executing in.
|
220,202 |
<p>The subject doesn't say much cause it is not easy to question in one line.
I have to execute a few programs which I read from the registry. I have to read from a field where somebody saves the whole paths and arguments.<br>
I've been using System.Diagnostics.ProcessStartInfo setting the name of the program and its arguments but I've found a wide variety of arguments which I have to parse to save the process executable file in one field and its arguments in the other. </p>
<p>Is there a way to just execute the whole string as is?</p>
|
[
{
"answer_id": 220227,
"author": "Michael Madsen",
"author_id": 27528,
"author_profile": "https://Stackoverflow.com/users/27528",
"pm_score": 0,
"selected": false,
"text": "<p>There are several, in fact.</p>\n\n<ol>\n<li>You can call cmd.exe with /C [your command line] as the arguments. This causes cmd.exe to process your command, and then quit.</li>\n<li>You could write the command to a batch file and launch that.</li>\n</ol>\n\n<p>And of course there's the approach you're taking now, namely parsing the command line.</p>\n"
},
{
"answer_id": 220553,
"author": "Danny Frencham",
"author_id": 29830,
"author_profile": "https://Stackoverflow.com/users/29830",
"pm_score": 4,
"selected": true,
"text": "<p>I have tackled this the same way as the poster above, using cmd.exe with process start info.</p>\n\n<pre><code>Process myProcess = New Process;\nmyProcess.StartInfo.FileName = \"cmd.exe\";\nmyProcess.StartInfo.Arguments = \"/C \" + cmd;\nmyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nmyProcess.StartInfo.CreateNoWindow = True;\nmyProcess.Start();\nmyProcess.WaitForExit();\nmyProcess.Close();\n</code></pre>\n\n<p>cmd /c carries out the command, and then terminates.\nWaitForExit will terminate the process if it runs for too long.</p>\n"
},
{
"answer_id": 800680,
"author": "Luke Quinane",
"author_id": 18437,
"author_profile": "https://Stackoverflow.com/users/18437",
"pm_score": 0,
"selected": false,
"text": "<p>When '<a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.useshellexecute.aspx\" rel=\"nofollow noreferrer\">UseShellExecute</a>' is not set, System.Diagnostics.Process calls either <a href=\"http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateProcess</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms682429.aspx\" rel=\"nofollow noreferrer\">CreateProcessAsUser</a> to actually start a program (it uses the second one if you specify a user/domain/password). And both of those calls can take the command and file as a single argument. From MSDN:</p>\n\n<blockquote>\n <p>The lpApplicationName parameter can be\n NULL. In that case, the module name\n must be the first white\n space–delimited token in the\n lpCommandLine string. ...</p>\n</blockquote>\n\n<p>lpApplication name maps to ProcessStartInfo.Filename and lpCommandLine maps to Arguments. So you should be albe to just go:</p>\n\n<pre><code>var processStartInfo = new ProcessStartInfo()\n{\n UseShellExecute = false,\n Arguments = cmd\n};\nProcess.Start(processStartInfo);\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23893/"
] |
The subject doesn't say much cause it is not easy to question in one line.
I have to execute a few programs which I read from the registry. I have to read from a field where somebody saves the whole paths and arguments.
I've been using System.Diagnostics.ProcessStartInfo setting the name of the program and its arguments but I've found a wide variety of arguments which I have to parse to save the process executable file in one field and its arguments in the other.
Is there a way to just execute the whole string as is?
|
I have tackled this the same way as the poster above, using cmd.exe with process start info.
```
Process myProcess = New Process;
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/C " + cmd;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = True;
myProcess.Start();
myProcess.WaitForExit();
myProcess.Close();
```
cmd /c carries out the command, and then terminates.
WaitForExit will terminate the process if it runs for too long.
|
220,211 |
<p>I'm creating a web application for work where the user has to enter the name of the person that requested the job. I'd like to create a simple AJAX auto-suggest dropdown so they don't need to type the entire name. On the backend, the database will provide suggestions based on previous entries. The website is built using CakePHP 1.1.</p>
<p>I know there are a lot of libraries out there, some better than others. Which do you think is the fastest and easiest to implement?</p>
|
[
{
"answer_id": 220238,
"author": "yalestar",
"author_id": 2177,
"author_profile": "https://Stackoverflow.com/users/2177",
"pm_score": 2,
"selected": false,
"text": "<p>I've had great success with <a href=\"http://www.brandspankingnew.net/archive/2007/02/ajax_auto_suggest_v2.html\" rel=\"nofollow noreferrer\">Brand Spanking New</a>'s Auto-Suggest implementation. It includes PHP examples too.</p>\n"
},
{
"answer_id": 220259,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 1,
"selected": false,
"text": "<p>You can't go wrong with jQuery. <a href=\"http://nodstrum.com/2007/09/19/autocompleter/\" rel=\"nofollow noreferrer\">http://nodstrum.com/2007/09/19/autocompleter/</a></p>\n"
},
{
"answer_id": 220264,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 4,
"selected": true,
"text": "<p>Since you are using CakePHP 1.1 I suggest you check out the Manual portion that deals with <a href=\"http://book.cakephp.org/view/316/Helpers\" rel=\"nofollow noreferrer\">Helpers</a></p>\n\n<p>If you go down to 'AJAX', you can see you can do something like this in your controller:</p>\n\n<pre><code>function autocomplete () {\n $this->set('people',\n $this->Person->findAll(\"name LIKE '%{$this->data['Person']['name']}%'\")\n );\n $this->layout = \"ajax\";\n}\n</code></pre>\n\n<p>And in your <code>autocomplete.thtml</code> view, you would have:</p>\n\n<pre><code><ul>\n<?php foreach($people as $person): ?>\n<li><?php echo $person['Person']['name']; ?></li>\n<?php endforeach; ?>\n</ul>\n</code></pre>\n\n<p>And to create the autocomplete field in another view, you would do:</p>\n\n<pre><code><form action=\"/people/index\" method=\"POST\">\n<?php echo $ajax->autoComplete('Person/name', '/people/autocomplete/')?>\n<?php echo $html->submit('View Person')?>\n</form>\n</code></pre>\n\n<p>In order for this to work you need to have 'Ajax' in your <code>helpers</code> array, and have the Prototype/script.aculo.us libraries included.</p>\n\n<p>Good luck.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5982/"
] |
I'm creating a web application for work where the user has to enter the name of the person that requested the job. I'd like to create a simple AJAX auto-suggest dropdown so they don't need to type the entire name. On the backend, the database will provide suggestions based on previous entries. The website is built using CakePHP 1.1.
I know there are a lot of libraries out there, some better than others. Which do you think is the fastest and easiest to implement?
|
Since you are using CakePHP 1.1 I suggest you check out the Manual portion that deals with [Helpers](http://book.cakephp.org/view/316/Helpers)
If you go down to 'AJAX', you can see you can do something like this in your controller:
```
function autocomplete () {
$this->set('people',
$this->Person->findAll("name LIKE '%{$this->data['Person']['name']}%'")
);
$this->layout = "ajax";
}
```
And in your `autocomplete.thtml` view, you would have:
```
<ul>
<?php foreach($people as $person): ?>
<li><?php echo $person['Person']['name']; ?></li>
<?php endforeach; ?>
</ul>
```
And to create the autocomplete field in another view, you would do:
```
<form action="/people/index" method="POST">
<?php echo $ajax->autoComplete('Person/name', '/people/autocomplete/')?>
<?php echo $html->submit('View Person')?>
</form>
```
In order for this to work you need to have 'Ajax' in your `helpers` array, and have the Prototype/script.aculo.us libraries included.
Good luck.
|
220,231 |
<p>How do I access a page's HTTP response headers via JavaScript?</p>
<p>Related to <a href="https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript"><strong>this question</strong></a>, which was modified to ask about accessing two specific HTTP headers.</p>
<blockquote>
<p><strong>Related:</strong><br>
<a href="https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript">How do I access the HTTP request header fields via JavaScript?</a></p>
</blockquote>
|
[
{
"answer_id": 220233,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 9,
"selected": true,
"text": "<p>Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been <a href=\"https://stackoverflow.com/questions/12258705/how-can-i-read-the-current-headers-without-making-a-new-request-with-js\">repeatedly asked</a>, too, because some people would like to get the actual response headers of the original page request without issuing another one.</p>\n<h1><br/>For AJAX Requests:</h1>\n<p>If an HTTP request is made over AJAX, it is possible to get the response headers with the <strong><code>getAllResponseHeaders()</code></strong> method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the <em><code>fetchSimilarHeaders()</code></em> function below. Note that this is a work-around to the problem that won't be reliable for some applications.</p>\n<pre><code>myXMLHttpRequest.getAllResponseHeaders();\n</code></pre>\n<ul>\n<li><p>The API was specified in the following candidate recommendation for XMLHttpRequest: <a href=\"http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader-method\" rel=\"noreferrer\">XMLHttpRequest - W3C Candidate Recommendation 3 August 2010</a></p>\n</li>\n<li><p>Specifically, the <code>getAllResponseHeaders()</code> method was specified in the following section: <a href=\"http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method\" rel=\"noreferrer\">w3.org: <code>XMLHttpRequest</code>: the <code>getallresponseheaders()</code> method</a></p>\n</li>\n<li><p>The MDN documentation is good, too: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\" rel=\"noreferrer\">developer.mozilla.org: <code>XMLHttpRequest</code></a>.</p>\n</li>\n</ul>\n<p>This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.</p>\n<h1><br/>Getting header values from the Initial Page Request:</h1>\n<p>This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the <em>current page</em> (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.</p>\n<p>The following are a few suggestions for getting around that problem.</p>\n<h2><br/>1. Requests on Resources which are largely static</h2>\n<p>If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.</p>\n<pre><code>function fetchSimilarHeaders (callback) {\n var request = new XMLHttpRequest();\n request.onreadystatechange = function () {\n if (request.readyState === XMLHttpRequest.DONE) {\n //\n // The following headers may often be similar\n // to those of the original page request...\n //\n if (callback && typeof callback === 'function') {\n callback(request.getAllResponseHeaders());\n }\n }\n };\n\n //\n // Re-request the same page (document.location)\n // We hope to get the same or similar response headers to those which \n // came with the current page, but we have no guarantee.\n // Since we are only after the headers, a HEAD request may be sufficient.\n //\n request.open('HEAD', document.location, true);\n request.send(null);\n}\n</code></pre>\n<p>This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.</p>\n<h2><br/>2. Make Inferences</h2>\n<p>There are <strong>some BOM properties</strong> (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. <code>navigator.userAgent</code> is set to the value of the HTTP <code>User-Agent</code> header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.</p>\n<h2><br/>3. Stash them</h2>\n<p>If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.</p>\n"
},
{
"answer_id": 220312,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 4,
"selected": false,
"text": "<p>Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a <code>Set-Cookie</code> response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.</p>\n"
},
{
"answer_id": 220883,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 3,
"selected": false,
"text": "<p>If we're talking about <em>Request</em> headers, you can create your own headers when doing XmlHttpRequests.</p>\n\n<pre><code>var request = new XMLHttpRequest();\nrequest.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\nrequest.open(\"GET\", path, true);\nrequest.send(null);\n</code></pre>\n"
},
{
"answer_id": 260117,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 5,
"selected": false,
"text": "<p>Using <code>XmlHttpRequest</code> you can pull up the current page and then examine the http headers of the response.</p>\n\n<p>Best case is to just do a <code>HEAD</code> request and then examine the headers.</p>\n\n<p>For some examples of doing this have a look at <a href=\"http://www.jibbering.com/2002/4/httprequest.html\" rel=\"noreferrer\">http://www.jibbering.com/2002/4/httprequest.html</a></p>\n\n<p>Just my 2 cents.</p>\n"
},
{
"answer_id": 277761,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Using mootools, you can use <code>this.xhr.getAllResponseHeaders()</code></p>\n"
},
{
"answer_id": 4847090,
"author": "dlo",
"author_id": 580394,
"author_profile": "https://Stackoverflow.com/users/580394",
"pm_score": -1,
"selected": false,
"text": "<p>This is an old question. Not sure when support became more broad, but <code>getAllResponseHeaders()</code> and <code>getResponseHeader()</code> appear to now be fairly standard: <a href=\"http://www.w3schools.com/xml/dom_http.asp\" rel=\"nofollow\">http://www.w3schools.com/xml/dom_http.asp</a></p>\n"
},
{
"answer_id": 4881836,
"author": "Raja",
"author_id": 600903,
"author_profile": "https://Stackoverflow.com/users/600903",
"pm_score": 9,
"selected": false,
"text": "<p>It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.</p>\n\n<hr>\n\n<p>Use the following JavaScript code to get all the HTTP headers by performing a <code>get</code> request:</p>\n\n<pre><code>var req = new XMLHttpRequest();\nreq.open('GET', document.location, false);\nreq.send(null);\nvar headers = req.getAllResponseHeaders().toLowerCase();\nalert(headers);\n</code></pre>\n"
},
{
"answer_id": 14594446,
"author": "David Winiecki",
"author_id": 724752,
"author_profile": "https://Stackoverflow.com/users/724752",
"pm_score": 3,
"selected": false,
"text": "<p>You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like \"http referer javascript\".</p>\n\n<p>I know this should be obvious, but I kept searching for stuff like \"http headers javascript\" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.</p>\n"
},
{
"answer_id": 18278054,
"author": "rushmore",
"author_id": 2690114,
"author_profile": "https://Stackoverflow.com/users/2690114",
"pm_score": 2,
"selected": false,
"text": "<p>I've just tested, and this works for me using Chrome Version 28.0.1500.95.</p>\n\n<p>I was needing to download a file and read the file name. The file name is in the header so I did the following:</p>\n\n<pre><code>var xhr = new XMLHttpRequest(); \nxhr.open('POST', url, true); \nxhr.responseType = \"blob\";\nxhr.onreadystatechange = function () { \n if (xhr.readyState == 4) {\n success(xhr.response); // the function to proccess the response\n\n console.log(\"++++++ reading headers ++++++++\");\n var headers = xhr.getAllResponseHeaders();\n console.log(headers);\n console.log(\"++++++ reading headers end ++++++++\");\n\n }\n};\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Date: Fri, 16 Aug 2013 16:21:33 GMT\nContent-Disposition: attachment;filename=testFileName.doc\nContent-Length: 20\nServer: Apache-Coyote/1.1\nContent-Type: application/octet-stream\n</code></pre>\n"
},
{
"answer_id": 26381576,
"author": "Fulup",
"author_id": 3986849,
"author_profile": "https://Stackoverflow.com/users/3986849",
"pm_score": 3,
"selected": false,
"text": "<p>Like many people I've been digging the net with no real answer :(</p>\n\n<p>I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.</p>\n\n<pre><code> case \".html\":\n response.setHeader(\"Content-Type\", \"text/html\");\n response.write (\"<script>location['GPSD_HTTP_AJAX']=true</script>\")\n // process the real contend of my page\n</code></pre>\n\n<p>Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]</p>\n\n<p>On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile</p>\n\n<pre><code> // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP\n var corsbypass = true; \n if (location['GPSD_HTTP_AJAX']) corsbypass = false;\n\n if (corsbypass) { // Json & html served from two different web servers\n var gpsdApi = \"http://localhost:4080/geojson.rest?jsoncallback=?\";\n } else { // Json & html served from same web server [no ?jsoncallback=]\n var gpsdApi = \"geojson.rest?\";\n }\n var gpsdRqt = \n {key :123456789 // user authentication key\n ,cmd :'list' // rest command\n ,group :'all' // group to retreive\n ,round : true // ask server to round numbers\n };\n $.getJSON(gpsdApi,gpsdRqt, DevListCB);\n</code></pre>\n\n<p>For who ever would like to check my code: \n<a href=\"https://www.npmjs.org/package/gpsdtracking\" rel=\"noreferrer\">https://www.npmjs.org/package/gpsdtracking</a></p>\n"
},
{
"answer_id": 37762564,
"author": "Gaël Métais",
"author_id": 4716391,
"author_profile": "https://Stackoverflow.com/users/4716391",
"pm_score": 5,
"selected": false,
"text": "<h1>A solution with Service Workers</h1>\n\n<p>Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.</p>\n\n<h2>How it works:</h2>\n\n<ol>\n<li>Add a service worker on your website.</li>\n<li>Watch every request that's being sent.</li>\n<li>Make the service worker <code>fetch</code> the request with the <code>respondWith</code> function.</li>\n<li>When the response arrives, read the headers.</li>\n<li>Send the headers from the service worker to the page with the <code>postMessage</code> function.</li>\n</ol>\n\n<h2>Working example:</h2>\n\n<p>Service workers are a bit complicated to understand, so I've built a small library that does all this. It is available on github: <a href=\"https://github.com/gmetais/sw-get-headers\" rel=\"noreferrer\">https://github.com/gmetais/sw-get-headers</a>.</p>\n\n<h2>Limitations:</h2>\n\n<ul>\n<li>the website needs to be on <strong>HTTPS</strong></li>\n<li>the browser needs to support the <a href=\"https://developer.mozilla.org/fr/docs/Web/API/Service_Worker_API\" rel=\"noreferrer\">Service Workers</a> API</li>\n<li>the same-domain/cross-domain policies are in action, just like on XMLHttpRequest</li>\n</ul>\n"
},
{
"answer_id": 47724317,
"author": "Diego",
"author_id": 498609,
"author_profile": "https://Stackoverflow.com/users/498609",
"pm_score": 4,
"selected": false,
"text": "<p>For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary <code>headers[\"content-type\"]</code>, I've created a function <code>parseHttpHeaders</code>:</p>\n\n<pre><code>function parseHttpHeaders(httpHeaders) {\n return httpHeaders.split(\"\\n\")\n .map(x=>x.split(/: */,2))\n .filter(x=>x[0])\n .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});\n}\n\nvar req = new XMLHttpRequest();\nreq.open('GET', document.location, false);\nreq.send(null);\nvar headers = parseHttpHeaders(req.getAllResponseHeaders());\n// Now we can do: headers[\"content-type\"]\n</code></pre>\n"
},
{
"answer_id": 47782657,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 2,
"selected": false,
"text": "<p>This is my script to get all the response headers:</p>\n\n<pre><code>var url = \"< URL >\";\n\nvar req = new XMLHttpRequest();\nreq.open('HEAD', url, false);\nreq.send(null);\nvar headers = req.getAllResponseHeaders();\n\n//Show alert with response headers.\nalert(headers);\n</code></pre>\n\n<p>Having as a result the response headers.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8Gs1v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8Gs1v.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is a comparison test using Hurl.it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/NVJIx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NVJIx.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 49471801,
"author": "Ollie Williams",
"author_id": 6854859,
"author_profile": "https://Stackoverflow.com/users/6854859",
"pm_score": -1,
"selected": false,
"text": "<p>As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response. </p>\n\n<p>In Express, for example, the following works:</p>\n\n<p><code>app.get('/somepage', (req, res) => {\n res.render('somepage.hbs', {headers: req.headers});\n})\n</code>\nThe headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.</p>\n"
},
{
"answer_id": 51842418,
"author": "shaedrich",
"author_id": 7451109,
"author_profile": "https://Stackoverflow.com/users/7451109",
"pm_score": 3,
"selected": false,
"text": "<p>To get the headers as an object which is handier (improvement of <a href=\"https://stackoverflow.com/a/4881836/7451109\">Raja's answer</a>):</p>\n<pre><code>var req = new XMLHttpRequest();\nreq.open('GET', document.location, false);\nreq.send(null);\nvar headers = req.getAllResponseHeaders().toLowerCase();\nheaders = headers.split(/\\n|\\r|\\r\\n/g).reduce(function(a, b) {\n if (b.length) {\n var [ key, value ] = b.split(': ');\n a[key] = value;\n }\n return a;\n}, {});\n</code></pre>\n"
},
{
"answer_id": 53637297,
"author": "Santhosh N",
"author_id": 8774514,
"author_profile": "https://Stackoverflow.com/users/8774514",
"pm_score": -1,
"selected": false,
"text": "<p>I think the question went in the wrong way, \n If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header. \n Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..</p>\n"
},
{
"answer_id": 58791949,
"author": "j.j.",
"author_id": 5807141,
"author_profile": "https://Stackoverflow.com/users/5807141",
"pm_score": 3,
"selected": false,
"text": "<p>Allain Lalonde's link made my day. \nJust adding some simple working html code here.\n<br>Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.</p>\n\n<pre><code><!DOCTYPE html>\n<title>(XHR) Show all response headers</title>\n\n<h1>All Response Headers with XHR</h1>\n<script>\n var X= new XMLHttpRequest();\n X.open(\"HEAD\", location);\n X.send();\n X.onload= function() { \n document.body.appendChild(document.createElement(\"pre\")).textContent= X.getAllResponseHeaders();\n }\n</script>\n</code></pre>\n\n<p>Note: You get headers of a second request, the result may differ from the initial request.</p>\n\n<p><hr>\n<strong>Another way</strong> <br>is the more modern <code>fetch()</code> API\n<br><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch</a>\n<br>Per <a href=\"https://caniuse.com/#feat=fetch\" rel=\"nofollow noreferrer\">caniuse.com</a> it's supported by Firefox 40, Chrome 42, Edge 14, Safari 11\n<br>Working example code:</p>\n\n<pre><code><!DOCTYPE html>\n<title>fetch() all Response Headers</title>\n\n<h1>All Response Headers with fetch()</h1>\n<script>\n var x= \"\";\n if(window.fetch)\n fetch(location, {method:'HEAD'})\n .then(function(r) {\n r.headers.forEach(\n function(Value, Header) { x= x + Header + \"\\n\" + Value + \"\\n\\n\"; }\n );\n })\n .then(function() {\n document.body.appendChild(document.createElement(\"pre\")).textContent= x;\n });\n else\n document.write(\"This does not work in your browser - no support for fetch API\");\n</script>\n</code></pre>\n"
},
{
"answer_id": 66211531,
"author": "jakub.g",
"author_id": 245966,
"author_profile": "https://Stackoverflow.com/users/245966",
"pm_score": 5,
"selected": false,
"text": "<h1>(2021) An answer <em>without</em> additional HTTP call</h1>\n<p>While it's not possible <em>in general</em> to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can't be exposed easily in any other way than via a header:</p>\n<p><strong>You may use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing\" rel=\"noreferrer\"><code>Server-Timing</code></a> header to expose arbitrary key-value data, and it will be readable by JavaScript.</strong></p>\n<p><em>(*in supported browsers: Firefox 61, Chrome 65, Edge 79; <strong><a href=\"https://bugs.webkit.org/show_bug.cgi?id=185870#c15\" rel=\"noreferrer\">no Safari yet</a> and no immediate plans for shipping as of 2021.09; no IE)</strong></em></p>\n<p>Example:</p>\n<pre><code>server-timing: key;desc="value"\n</code></pre>\n<ul>\n<li>You can use this header <a href=\"https://w3c.github.io/server-timing/#examples\" rel=\"noreferrer\">multiple times for multiple pieces of data</a>:</li>\n</ul>\n<pre><code>server-timing: key1;desc="value1"\nserver-timing: key2;desc="value2"\n</code></pre>\n<ul>\n<li>or use its compact version where you expose multiple pieces of data in one header, comma-separated.</li>\n</ul>\n<pre><code>server-timing: key1;desc="value1", key2;desc="value2"\n</code></pre>\n<p>Example of how <a href=\"https://www.wikipedia.org/\" rel=\"noreferrer\">Wikipedia</a> uses this header to expose info about cache hit/miss:</p>\n<p><a href=\"https://i.stack.imgur.com/EfChY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/EfChY.png\" alt=\"Usage of server-timing response header on Wikipedia\" /></a></p>\n<p>Code example (need to account for lack of browser support in Safari and IE):</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers\n let navTiming = performance.getEntriesByType('navigation')\n if (navTiming.length > 0) { // still not supported as of Safari 14...\n let serverTiming = navTiming[0].serverTiming\n if (serverTiming && serverTiming.length > 0) {\n for (let i=0; i<serverTiming.length; i++) {\n console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)\n }\n }\n }\n}\n</code></pre>\n<p>This logs <code>cache = hit-front</code> in supported browsers.</p>\n<p>Notes:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming\" rel=\"noreferrer\">as mentioned on MDN</a>, the API is only supported over HTTPS</li>\n<li>if your JS is served from another domain, you have to add <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin\" rel=\"noreferrer\">Timing-Allow-Origin</a> response header to make the data readable to JS (<code>Timing-Allow-Origin: *</code> or <code>Timing-Allow-Origin: https://www.example.com</code>)</li>\n<li><code>Server-Timing</code> headers support also <code>dur</code>(header) field, readable as <code>duration</code> on JS side, but it's optional and defaults to <code>0</code> in JS if not passed</li>\n<li>regarding Safari support: see <a href=\"https://bugs.webkit.org/show_bug.cgi?id=184363\" rel=\"noreferrer\">bug 1</a> and <a href=\"https://bugs.webkit.org/show_bug.cgi?id=190609\" rel=\"noreferrer\">bug 2</a> and <a href=\"https://bugs.webkit.org/show_bug.cgi?id=185870\" rel=\"noreferrer\">bug 3</a></li>\n<li>You can read more on server-timing in <a href=\"https://calendar.perfplanet.com/2018/server-timing/\" rel=\"noreferrer\">this blog post</a></li>\n<li>Note that performance entries buffers might get cleaned by JS on the page (via an API call), or by the browser, if the page issues too many calls for subresources. For that reason, you should capture the data as soon as possible, and/or use <code>PerformanceObserver</code> API instead. See the <a href=\"https://vaz.ac/post/clearresourcetimings/\" rel=\"noreferrer\">blog post</a> for details.</li>\n</ul>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
How do I access a page's HTTP response headers via JavaScript?
Related to [**this question**](https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript), which was modified to ask about accessing two specific HTTP headers.
>
> **Related:**
>
> [How do I access the HTTP request header fields via JavaScript?](https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript)
>
>
>
|
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been [repeatedly asked](https://stackoverflow.com/questions/12258705/how-can-i-read-the-current-headers-without-making-a-new-request-with-js), too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
==================
If an HTTP request is made over AJAX, it is possible to get the response headers with the **`getAllResponseHeaders()`** method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the *`fetchSimilarHeaders()`* function below. Note that this is a work-around to the problem that won't be reliable for some applications.
```
myXMLHttpRequest.getAllResponseHeaders();
```
* The API was specified in the following candidate recommendation for XMLHttpRequest: [XMLHttpRequest - W3C Candidate Recommendation 3 August 2010](http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader-method)
* Specifically, the `getAllResponseHeaders()` method was specified in the following section: [w3.org: `XMLHttpRequest`: the `getallresponseheaders()` method](http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method)
* The MDN documentation is good, too: [developer.mozilla.org: `XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest).
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
====================================================
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the *current page* (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
-------------------------------------------------
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
```
function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};
//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}
```
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
2. Make Inferences
------------------
There are **some BOM properties** (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. `navigator.userAgent` is set to the value of the HTTP `User-Agent` header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
3. Stash them
-------------
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.
|
220,234 |
<p>In the <code>IDisposable.Dispose</code> method is there a way to figure out if an exception is being thrown?</p>
<pre><code>using (MyWrapper wrapper = new MyWrapper())
{
throw new Exception("Bad error.");
}
</code></pre>
<p>If an exception is thrown in the <code>using</code> statement I want to know about it when the <code>IDisposable</code> object is disposed.</p>
|
[
{
"answer_id": 220249,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of the syntactic sugar of the using statement, why not just implement your own logic for this. Something like:</p>\n\n<pre><code>try\n{\n MyWrapper wrapper = new MyWrapper();\n\n}\ncatch (Exception e)\n{\n wrapper.CaughtException = true;\n}\nfinally\n{\n if (wrapper != null)\n {\n wrapper.Dispose();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 221440,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 5,
"selected": true,
"text": "<p><strong>No</strong>, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause. </p>\n\n<p>See this <a href=\"http://samsaffron.com/blog/archive/2007/08/06/16.aspx\" rel=\"noreferrer\">post on my blog</a>, for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with the IDisposable pattern. </p>\n\n<p>Ayende has a trick that will allow you to <a href=\"http://ayende.com/Blog/archive/2007/06/20/Did-you-know-Find-out-if-an-exception-was-thrown.aspx\" rel=\"noreferrer\">detect an exception happened</a>, however, it will not tell you which exception it was.</p>\n"
},
{
"answer_id": 223435,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "<p>James, All <code>wrapper</code> can do is log it's own exceptions. You can't force the consumer of <code>wrapper</code> to log their own exceptions. That's not what IDisposable is for. IDisposable is meant for semi-deterministic release of resources for an object. Writing correct IDisposable code is not trivial.</p>\n\n<p>In fact, the consumer of the class isn't even required to call your classes dispose method, nor are they required to use a using block, so it all rather breaks down.</p>\n\n<p>If you look at it from the point of view of the wrapper class, why should it care that it was present inside a using block and there was an exception? What knowledge does that bring? Is it a security risk to have 3rd party code privy to exception details and stack trace? What can <code>wrapper</code> do if there is a divide-by-zero in a calculation?</p>\n\n<p>The only way to log exceptions, irrespective of IDisposable, is try-catch and then to re-throw in the catch.</p>\n\n<pre><code>try\n{\n // code that may cause exceptions.\n}\ncatch( Exception ex )\n{\n LogExceptionSomewhere(ex);\n throw;\n}\nfinally\n{\n // CLR always tries to execute finally blocks\n}\n</code></pre>\n\n<hr>\n\n<p>You mention you're creating an external API. You would have to wrap every call at your API's public boundary with try-catch in order to log that the exception came from your code.</p>\n\n<p>If you're writing a public API then you really ought to read <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321545613\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series) - 2nd Edition</a> .. <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321246756\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">1st Edition</a>.</p>\n\n<hr>\n\n<p>While I don't advocate them, I have seen IDisposable used for other interesting patterns:</p>\n\n<ol>\n<li>Auto-rollback transaction semantics. The transaction class would rollback the transaction on Dispose if not already committed.</li>\n<li>Timed code blocks for logging. During object creation a timestamp was recorded, and on Dispose the TimeSpan was calculated and a log event was written.</li>\n</ol>\n\n<p>* These patterns can be achieved with another layer of indirection and anonymous delegates easily and without having to overload IDisposable semantics. The important note is that your IDisposable wrapper is useless if you or a team member forget to use it properly. </p>\n"
},
{
"answer_id": 223469,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>This will catch exceptions thrown either directly or inside the dispose method:</p>\n\n<pre><code>try\n{\n using (MyWrapper wrapper = new MyWrapper())\n {\n throw new MyException(\"Bad error.\");\n }\n}\ncatch ( MyException myex ) {\n //deal with your exception\n}\ncatch ( Exception ex ) {\n //any other exception thrown by either\n //MyWrapper..ctor() or MyWrapper.Dispose()\n}\n</code></pre>\n\n<p>But this is relying on them using this this code - it sounds like you want MyWrapper to do that instead.</p>\n\n<p>The using statement is just to make sure that Dispose always gets called. It's really doing this:</p>\n\n<pre><code>MyWrapper wrapper;\ntry\n{\n wrapper = new MyWrapper();\n}\nfinally {\n if( wrapper != null )\n wrapper.Dispose();\n}\n</code></pre>\n\n<p>It sounds like what you want is:</p>\n\n<pre><code>MyWrapper wrapper;\ntry\n{\n wrapper = new MyWrapper();\n}\nfinally {\n try{\n if( wrapper != null )\n wrapper.Dispose();\n }\n catch {\n //only errors thrown by disposal\n }\n}\n</code></pre>\n\n<p>I would suggest dealing with this in your implementation of Dispose - you should handle any issues during Disposal anyway.</p>\n\n<p>If you're tying up some resource where you need users of your API to free it in some way consider having a <code>Close()</code> method. Your dispose should call it too (if it hasn't been already) but users of your API could also call it themselves if they needed finer control.</p>\n"
},
{
"answer_id": 6984563,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to stay purely within .net, two approaches I would suggest would be writing a \"try-catch-finally\" wrapper, which would accept delegates for the different parts, or else writing a \"using-style\" wrapper, which accept a method to be invoked, along with one or more IDisposable objects which should be disposed after it completes.</p>\n\n<p>A \"using-style\" wrapper could handle the disposal in a try-catch block and, if any exceptions are thrown in disposal, either wrap them in a CleanupFailureException which would hold the disposal failures as well as any exception that occurred in the main delegate, or else add something to the exception's \"Data\" property with the original exception. I would favor wrapping things in a CleanupFailureException, since an exception that occurs during cleanup will generally indicate a much bigger problem than one which occurs in main-line processing; further, a CleanupFailureException could be written to include multiple nested exceptions (if there are 'n' IDisposable objects, there could be n+1 nested exceptions: one from the mainline and one from each Dispose).</p>\n\n<p>A \"try-catch-finally\" wrapper written in vb.net, while callable from C#, could include some features that are otherwise unavailable in C#, including the ability to expand it to a \"try-filter-catch-fault-finally\" block, where the \"filter\" code would be executed before the stack is unwound from an exception and determine whether the exception should be caught, the \"fault\" block would contain code that would only run if an exception occurred, but would not actually catch it, and both the \"fault\" and \"finally\" blocks would receive parameters indicating both what exception (if any) occurred during the execution of the \"try\", and whether the \"try\" completed successfully (note, btw, that it would be possible for the exception parameter to be non-null even if the mainline completes; pure C# code couldn't detect such a condition, but the vb.net wrapper could).</p>\n"
},
{
"answer_id": 9730775,
"author": "sammyboy",
"author_id": 569208,
"author_profile": "https://Stackoverflow.com/users/569208",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this buy implementing the Dispose method for the \"MyWrapper\" class. In the dispose method you can check to see if there is an exception as follows</p>\n\n<pre><code>public void Dispose()\n{\n bool ExceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero\n || Marshal.GetExceptionCode() != 0;\n if(ExceptionOccurred)\n {\n System.Diagnostics.Debug.WriteLine(\"We had an exception\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10236572,
"author": "Jo VdB",
"author_id": 861358,
"author_profile": "https://Stackoverflow.com/users/861358",
"pm_score": 3,
"selected": false,
"text": "<p>It is <strong>not possible</strong> to capture the Exception in the <code>Dispose()</code> method.</p>\n\n<p>However, it is possible to check <code>Marshal.GetExceptionCode()</code> in the Dispose to detect if an Exception did occur, but I wouldn't rely on that.</p>\n\n<p>If you don't need a class and want just want to capture the Exception, you can create a function that accepts a lambda that is executed within a try/catch block, something like this: </p>\n\n<pre><code>HandleException(() => {\n throw new Exception(\"Bad error.\");\n});\n\npublic static void HandleException(Action code)\n{\n try\n {\n if (code != null)\n code.Invoke();\n }\n catch\n {\n Console.WriteLine(\"Error handling\");\n throw;\n }\n}\n</code></pre>\n\n<p>As example, You can use a method that automatically does a Commit() or Rollback() of a transaction and do some logging.\nAt this way you don't always need a try/catch block.</p>\n\n<pre><code>public static int? GetFerrariId()\n{\n using (var connection = new SqlConnection(\"...\"))\n {\n connection.Open();\n using (var transaction = connection.BeginTransaction())\n {\n return HandleTranaction(transaction, () =>\n {\n using (var command = connection.CreateCommand())\n {\n command.Transaction = transaction;\n command.CommandText = \"SELECT CarID FROM Cars WHERE Brand = 'Ferrari'\";\n return (int?)command.ExecuteScalar();\n }\n });\n }\n }\n}\n\npublic static T HandleTranaction<T>(IDbTransaction transaction, Func<T> code)\n{\n try\n {\n var result = code != null ? code.Invoke() : default(T);\n transaction.Commit();\n return result;\n }\n catch\n {\n transaction.Rollback();\n throw;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 14321555,
"author": "Kelqualyn",
"author_id": 682696,
"author_profile": "https://Stackoverflow.com/users/682696",
"pm_score": 5,
"selected": false,
"text": "<p>You can extend <code>IDisposable</code> with method <code>Complete</code> and use pattern like that:</p>\n\n<pre><code>using (MyWrapper wrapper = new MyWrapper())\n{\n throw new Exception(\"Bad error.\");\n wrapper.Complete();\n}\n</code></pre>\n\n<p>If an exception is thrown inside the <code>using</code> statement <code>Complete</code> will not be called before <code>Dispose</code>. </p>\n\n<p>If you want to know what exact exception is thrown, then subscribe on <code>AppDomain.CurrentDomain.FirstChanceException</code> event and store last thrown exception in <code>ThreadLocal<Exception></code> variable.</p>\n\n<p>Such pattern implemented in <code>TransactionScope</code> class.</p>\n"
},
{
"answer_id": 33004568,
"author": "Chad Hedgcock",
"author_id": 591097,
"author_profile": "https://Stackoverflow.com/users/591097",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, I wanted to do this to log when an microservice crashes. I already have in place a <code>using</code> to properly clean up right before an instance shut down, but if that's because of an exception I want to see why, and I hate no for an answer.</p>\n\n<p>Instead of trying to make it work in <code>Dispose()</code>, perhaps make a delegate for the work you need to do, and then wrap your exception-capturing in there. So in my MyWrapper logger, I add a method that takes an Action / Func:</p>\n\n<pre><code> public void Start(Action<string, string, string> behavior)\n try{\n var string1 = \"my queue message\";\n var string2 = \"some string message\";\n var string3 = \"some other string yet;\"\n behaviour(string1, string2, string3);\n }\n catch(Exception e){\n Console.WriteLine(string.Format(\"Oops: {0}\", e.Message))\n }\n }\n</code></pre>\n\n<p>To implement:</p>\n\n<pre><code>using (var wrapper = new MyWrapper())\n {\n wrapper.Start((string1, string2, string3) => \n {\n Console.WriteLine(string1);\n Console.WriteLine(string2);\n Console.WriteLine(string3);\n }\n }\n</code></pre>\n\n<p>Depending on what you need to do, this may be too restrictive, but it worked for what I needed.</p>\n"
},
{
"answer_id": 49680507,
"author": "mattias",
"author_id": 1766380,
"author_profile": "https://Stackoverflow.com/users/1766380",
"pm_score": 1,
"selected": false,
"text": "<p>Now, in 2017, this is the generic way to do it, incl handling rollback for exceptions.</p>\n\n<pre><code> public static T WithinTransaction<T>(this IDbConnection cnn, Func<IDbTransaction, T> fn)\n {\n cnn.Open();\n using (var transaction = cnn.BeginTransaction())\n {\n try\n {\n T res = fn(transaction);\n transaction.Commit();\n return res;\n }\n catch (Exception)\n {\n transaction.Rollback();\n throw;\n }\n finally\n {\n cnn.Close();\n }\n }\n }\n</code></pre>\n\n<p>and you call it like this:</p>\n\n<pre><code> cnn.WithinTransaction(\n transaction =>\n {\n var affected = ..sqlcalls..(cnn, ..., transaction);\n return affected;\n });\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11829/"
] |
In the `IDisposable.Dispose` method is there a way to figure out if an exception is being thrown?
```
using (MyWrapper wrapper = new MyWrapper())
{
throw new Exception("Bad error.");
}
```
If an exception is thrown in the `using` statement I want to know about it when the `IDisposable` object is disposed.
|
**No**, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause.
See this [post on my blog](http://samsaffron.com/blog/archive/2007/08/06/16.aspx), for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with the IDisposable pattern.
Ayende has a trick that will allow you to [detect an exception happened](http://ayende.com/Blog/archive/2007/06/20/Did-you-know-Find-out-if-an-exception-was-thrown.aspx), however, it will not tell you which exception it was.
|
220,236 |
<p>I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen <a href="http://web.archive.org/web/20100208164146/http://www.spoono.com/html/tutorials/tutorial.php?id=19" rel="noreferrer">the W3C solution</a>, which doesn't even work on Firefox, and <a href="http://web.archive.org/web/20130127125919/http://wiki.novemberborn.net/sifr/How+to+use" rel="noreferrer">this pretty cool solution</a>. The second solution is for titles only. Is there a solution available for full text? I'm tired of the standard fonts for web pages.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 220257,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 2,
"selected": false,
"text": "<p>And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE. Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism. A list apart had a good discussion about this a while <a href=\"http://www.alistapart.com/articles/cssatten\" rel=\"nofollow noreferrer\">back</a>.</p>\n"
},
{
"answer_id": 220276,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>I asked this <a href=\"https://stackoverflow.com/questions/16233/fonts-on-the-web\">a while back</a>. The answer is basically that it doesn't work. :(</p>\n"
},
{
"answer_id": 220277,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 3,
"selected": false,
"text": "<p>No, there isn't a decent solution for body type, unless you're willing to cater only to those with bleeding-edge browsers.</p>\n\n<p>Microsoft has <a href=\"http://en.wikipedia.org/wiki/Web_Embedding_Fonts_Tool\" rel=\"nofollow noreferrer\">WEFT</a>, their own proprietary font-embedding technology, but I haven't heard it talked about in years, and I know no one who uses it.</p>\n\n<p>I get by with sIFR for display type (headlines, titles of blog posts, etc.) and using one of the less-worn-out web-safe fonts for body type (like Trebuchet MS). If you're bored with all the web-safe fonts, you're probably defining the term too narrowly — look at <a href=\"http://dustinbrewer.com/fonts-on-the-web-and-a-list-of-web-safe-fonts/\" rel=\"nofollow noreferrer\">this matrix of stock fonts</a> that ship with major OSes and chances are you'll be able to find a font cascade that will catch nearly all web users.</p>\n\n<p>For instance: <code>font-family: \"Lucida Grande\", \"Verdana\", sans-serif</code> is a common font cascade; OS X comes with Lucida Grande, but those with Windows will get Verdana, a web-safe font with letters of similar size and shape to Lucida Grande. Linux users will also get Verdana if they've installed the web-safe fonts package that exists in most distros' package managers, or else they'll fall back to an ordinary sans-serif.</p>\n"
},
{
"answer_id": 550735,
"author": "Martin Meixger",
"author_id": 64466,
"author_profile": "https://Stackoverflow.com/users/64466",
"pm_score": 3,
"selected": false,
"text": "<p>Try <a href=\"https://gero3.github.io/facetype.js/\" rel=\"nofollow noreferrer\" title=\"Facetype.js\">Facetype.js</a>, you convert your .TTF font into a Javascript file. Full SEO compatible, supports FF, IE6 and Safari and degrades gracefully on other browsers.</p>\n"
},
{
"answer_id": 1967226,
"author": "fencepost",
"author_id": 221818,
"author_profile": "https://Stackoverflow.com/users/221818",
"pm_score": 8,
"selected": true,
"text": "<p><strong>Things have changed</strong> since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.</p>\n<p>Paul Irish put together <a href=\"http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/\" rel=\"noreferrer\">Bulletproof @font-face syntax</a> combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.</p>\n<p>Snipped from his article:</p>\n<pre><code>@font-face {\n font-family: 'Graublau Web';\n src: url('GraublauWeb.eot');\n src: local('Graublau Web Regular'), local('Graublau Web'),\n url("GraublauWeb.woff") format("woff"),\n url("GraublauWeb.otf") format("opentype"),\n url("GraublauWeb.svg#grablau") format("svg");\n}\n</code></pre>\n<p>Working from that base, <a href=\"http://www.fontsquirrel.com/\" rel=\"noreferrer\">Font Squirrel</a> put together a variety of useful tools including the <a href=\"http://www.fontsquirrel.com/fontface/generator\" rel=\"noreferrer\"><strong>@font-face Generator</strong></a> which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has <a href=\"http://www.fontsquirrel.com/fontface\" rel=\"noreferrer\">Hundreds of @font-face kits</a>.</p>\n<p>Soma Design also put together the <a href=\"http://somadesign.ca/projects/fontfriend/\" rel=\"noreferrer\">FontFriend Bookmarklet</a>, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.</p>\n<p>More recently, Google has started to provide the <a href=\"http://www.google.com/webfonts\" rel=\"noreferrer\">Google Web Fonts</a>, an assortment of fonts available under an Open Source license and served from Google's servers.</p>\n<p><strong>License Restrictions</strong></p>\n<p>Finally, WebFonts.info has put together a nice wiki'd list of <a href=\"https://web.archive.org/web/20140713192153/http://www.webfonts.info/fonts-available-font-face-embedding\" rel=\"noreferrer\">Fonts available for @font-face embedding</a> based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. <strong>It's important to read the licenses</strong>, because there are some limitations that aren't pushed forward obviously on the font downloads.</p>\n"
},
{
"answer_id": 1967232,
"author": "philfreo",
"author_id": 137067,
"author_profile": "https://Stackoverflow.com/users/137067",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://typekit.com/\" rel=\"nofollow noreferrer\">Typekit</a>, a commercial option (they have a free package available too). </p>\n\n<p>It uses different techniques depending on which browser is being used (<code>@font-face</code> vs. <code>EOT</code> format), and they take care of all the font licensing issues for you also. It supports everything down to IE6.</p>\n\n<p>Here's some more info about how Typekit works:</p>\n\n<ul>\n<li><a href=\"http://forabeautifulweb.com/blog/about/first_impressions_of_typekit\" rel=\"nofollow noreferrer\">http://forabeautifulweb.com/blog/about/first_impressions_of_typekit</a></li>\n<li><a href=\"http://www.sitepoint.com/blogs/2009/06/01/web-fonts-get-real-with-typekit/\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/blogs/2009/06/01/web-fonts-get-real-with-typekit/</a></li>\n</ul>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8047/"
] |
I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen [the W3C solution](http://web.archive.org/web/20100208164146/http://www.spoono.com/html/tutorials/tutorial.php?id=19), which doesn't even work on Firefox, and [this pretty cool solution](http://web.archive.org/web/20130127125919/http://wiki.novemberborn.net/sifr/How+to+use). The second solution is for titles only. Is there a solution available for full text? I'm tired of the standard fonts for web pages.
Thanks!
|
**Things have changed** since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.
Paul Irish put together [Bulletproof @font-face syntax](http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/) combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.
Snipped from his article:
```
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
```
Working from that base, [Font Squirrel](http://www.fontsquirrel.com/) put together a variety of useful tools including the [**@font-face Generator**](http://www.fontsquirrel.com/fontface/generator) which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has [Hundreds of @font-face kits](http://www.fontsquirrel.com/fontface).
Soma Design also put together the [FontFriend Bookmarklet](http://somadesign.ca/projects/fontfriend/), which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.
More recently, Google has started to provide the [Google Web Fonts](http://www.google.com/webfonts), an assortment of fonts available under an Open Source license and served from Google's servers.
**License Restrictions**
Finally, WebFonts.info has put together a nice wiki'd list of [Fonts available for @font-face embedding](https://web.archive.org/web/20140713192153/http://www.webfonts.info/fonts-available-font-face-embedding) based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. **It's important to read the licenses**, because there are some limitations that aren't pushed forward obviously on the font downloads.
|
220,243 |
<p>How can I comment a JSP expression like: <code><%= map.size() %></code></p>
<p>Is there something like <code><%= // map.size() %>?</code></p>
|
[
{
"answer_id": 220251,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": -1,
"selected": false,
"text": "<p>One of:</p>\n\n<p>In html</p>\n\n<pre><code><!-- map.size here because --> \n<%= map.size() %>\n</code></pre>\n\n<p>theoretically the following should work, but i never used it this way.</p>\n\n<pre><code><%= map.size() // map.size here because %>\n</code></pre>\n"
},
{
"answer_id": 220275,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 9,
"selected": true,
"text": "<p>Pure JSP comments look like this:</p>\n\n<pre><code><%-- Comment --%>\n</code></pre>\n\n<p>So if you want to retain the \"<code>=</code>\".you could do something like:</p>\n\n<pre><code><%--= map.size() --%>\n</code></pre>\n\n<p>The key thing is that <code><%=</code> defines the beginning of an expression, in which you can't leave the body empty, but you could do something like this instead if the pure JSP comment doesn't appeal to you:</p>\n\n<pre><code><% /*= map.size()*/ %>\n</code></pre>\n\n<p><a href=\"http://www.oracle.com/technetwork/articles/javase/code-convention-138726.html\" rel=\"noreferrer\">Code Conventions for the JavaServer Pages Technology Version 1.x Language</a> has details about the different commenting options available to you (but has a complete lack of link targets, so I can't link you directly to the relevant section - boo!)</p>\n"
},
{
"answer_id": 220304,
"author": "lock",
"author_id": 24744,
"author_profile": "https://Stackoverflow.com/users/24744",
"pm_score": 2,
"selected": false,
"text": "<p>your <code><%= //map.size() %></code> doesnt simply work because it should have been</p>\n\n<pre><code><% //= map.size() %>\n</code></pre>\n"
},
{
"answer_id": 21775583,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You can use this comment in jsp page </p>\n\n<pre><code> <%--your comment --%>\n</code></pre>\n\n<p>Second way of comment declaration in jsp page you can use the comment of two typ in jsp code </p>\n\n<pre><code> single line comment\n <% your code //your comment%>\n\nmultiple line comment \n\n<% your code \n/**\nyour another comment\n**/\n\n%>\n</code></pre>\n\n<p>And you can also comment on jsp page from html code for example:</p>\n\n<pre><code><!-- your commment -->\n</code></pre>\n"
},
{
"answer_id": 27956938,
"author": "Jflywheel",
"author_id": 1301982,
"author_profile": "https://Stackoverflow.com/users/1301982",
"pm_score": 3,
"selected": false,
"text": "<p>When you don't want the user to see the comment use:</p>\n\n<pre><code><%-- comment --%>\n</code></pre>\n\n<p>If you don't care / want the user to be able to view source and see the comment you can use:</p>\n\n<pre><code><!-- comment -->\n</code></pre>\n\n<p>When in doubt use the JSP comment.</p>\n"
},
{
"answer_id": 30295023,
"author": "kavi temre",
"author_id": 4062987,
"author_profile": "https://Stackoverflow.com/users/4062987",
"pm_score": 6,
"selected": false,
"text": "<p>There are multiple way to comment in a JSP file.</p>\n\n<pre><code>1. <%-- comment --%>\n</code></pre>\n\n<p>A JSP comment. Ignored by the JSP engine.\n Not visible in client machine (Browser source code).</p>\n\n<pre><code>2. <!-- comment -->\n</code></pre>\n\n<p>An HTML comment. Ignored by the browser.\n It is visible in client machine (Browser source code) as a comment.</p>\n\n<pre><code>3. <% my code //my comment %>\n</code></pre>\n\n<p>Java Single line comment. Ignored by the Compiler.\n Not visible in client machine (Browser source code).</p>\n\n<pre><code>4. <% my code /**\n my comment **/ \n %>\n</code></pre>\n\n<p>Java Multi line comment. Ignored by the compiler.\n Not visible in client machine (Browser source code).</p>\n\n<p>But one should use only comment type 1 and 2 because java documentation suggested. these two comment types (1 & 2) are designed for JSP.</p>\n"
},
{
"answer_id": 44278752,
"author": "Mani Kasi",
"author_id": 2175165,
"author_profile": "https://Stackoverflow.com/users/2175165",
"pm_score": 2,
"selected": false,
"text": "<p>My Suggestion best way use comments in JSP page <code><%-- Comment --%></code>\n. Because It will not displayed (will not rendered in HTML pages) in client browsers.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14015/"
] |
How can I comment a JSP expression like: `<%= map.size() %>`
Is there something like `<%= // map.size() %>?`
|
Pure JSP comments look like this:
```
<%-- Comment --%>
```
So if you want to retain the "`=`".you could do something like:
```
<%--= map.size() --%>
```
The key thing is that `<%=` defines the beginning of an expression, in which you can't leave the body empty, but you could do something like this instead if the pure JSP comment doesn't appeal to you:
```
<% /*= map.size()*/ %>
```
[Code Conventions for the JavaServer Pages Technology Version 1.x Language](http://www.oracle.com/technetwork/articles/javase/code-convention-138726.html) has details about the different commenting options available to you (but has a complete lack of link targets, so I can't link you directly to the relevant section - boo!)
|
220,250 |
<p>I am curious as to why an implicit cast fails in...</p>
<pre><code>int? someValue = SomeCondition ? ResultOfSomeCalc() : null;
</code></pre>
<p>and why I have to perform an explicit cast instead</p>
<pre><code>int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;
</code></pre>
<p>It seems to me that the compiler has all the information it need to make an implicit casting decision, no?</p>
|
[
{
"answer_id": 220268,
"author": "Brian Liang",
"author_id": 5853,
"author_profile": "https://Stackoverflow.com/users/5853",
"pm_score": 6,
"selected": true,
"text": "<p>The relevant section of the C# 3.0 spec is 7.13, the conditional operator:</p>\n\n<p>The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,</p>\n\n<p>If X and Y are the same type, then this is the type of the conditional\nOtherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.\nOtherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.\nOtherwise, no expression type can be determined, and a compile-time error occurs.</p>\n"
},
{
"answer_id": 220269,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 4,
"selected": false,
"text": "<p>I also am annoyed that it can't infer the type based on the assignment, especially when it's a value type. There are reasons though when you get into object heirarchies. </p>\n\n<p><strong>If \"ResultOfSomeCalc()\" returned a \"int?\", then this would work</strong>. C# needs to figure out the type regardless of what is to the left of the assignment. So you are telling it that you'll return a null or an int - and the logic in the compiler doesn't exist to have it substitute a Nullable as a common denominator.</p>\n\n<p>Notice that these variants DO work, and it may help you understand:</p>\n\n<pre><code>object someValue = true ? new Nullable<int>(ResultOfSomeCalc()) : null;\n\nobject someValue = true ? (int?)ResultOfSomeCalc() : null;\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 220295,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p>See also <a href=\"https://stackoverflow.com/questions/202271/why-is-this-code-invalid-in-c\">Why is this code invalid in C#?</a></p>\n"
},
{
"answer_id": 220300,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If your function ResultofSomeCalc() returns int? then this will work.</p>\n\n<p>If your function returns int, then the compiler issues the warning:\n Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''<br>\nI'm guessing that is what you are seeing. Both expressions in the conditional operator \"?:\" must have the same type, or must be convertible to the same type via an implicit cast.</p>\n\n<p>Change the return type of ResultOfSomeCalc to int?, or you will need to have the cast on the null expression.</p>\n"
},
{
"answer_id": 522404,
"author": "Mr. Putty",
"author_id": 63513,
"author_profile": "https://Stackoverflow.com/users/63513",
"pm_score": 3,
"selected": false,
"text": "<p>It sure seems like this is something the compiler should be able to figure out for itself, but there is one other way to do this, using the default keyword. It might be the tiniest bit less ugly than the cast:</p>\n\n<pre><code>int? someValue = SomeCondition ? ResultofSomeCalc() : default(int?);\n</code></pre>\n\n<p>This use of default doesn't seem to be well documented, but is does work. At least it keeps you from having to litter your code with magic values (I contend that null/zero/false/etc. are indeed magic values). </p>\n"
},
{
"answer_id": 29624697,
"author": "Abdus Salam Azad",
"author_id": 2738695,
"author_profile": "https://Stackoverflow.com/users/2738695",
"pm_score": 0,
"selected": false,
"text": "<p>Make your function ResultOfSomeCalc()'s return type as nullabel int like (int?)<br>\nint? someValue =(int?) SomeCondition ? ResultofSomeCalc() : (int?)null;</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10387/"
] |
I am curious as to why an implicit cast fails in...
```
int? someValue = SomeCondition ? ResultOfSomeCalc() : null;
```
and why I have to perform an explicit cast instead
```
int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;
```
It seems to me that the compiler has all the information it need to make an implicit casting decision, no?
|
The relevant section of the C# 3.0 spec is 7.13, the conditional operator:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.
|
220,254 |
<p>I have been using code similar to this</p>
<pre><code>MessageDlg('', mtWarning, [mbOK], 0);
</code></pre>
<p>throughout my project, (thanks to the GExperts Message Dialog tool :) ) and i was wondering if anyone knows of a way do override the call and show my own custom Form.</p>
<p>The only way i can think to do it its make a New Form with something like</p>
<pre><code>function MessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
begin
//show my own code here
end;
</code></pre>
<p>and put it each of my uses lists before the Dialogs unit but is there a guaranteed way to make sure it uses my code not the Dialogs unit Code.<br>
I don't like the idea of copying the dialogs unit to a local dir and making changes to it.</p>
<p>Or is this all to much work and should i just use my own function call and replace all the MessageDlg with my own. (which would not be fun, ive prob used MessageDlg too much) </p>
|
[
{
"answer_id": 220270,
"author": "Fabio Gomes",
"author_id": 727,
"author_profile": "https://Stackoverflow.com/users/727",
"pm_score": 2,
"selected": false,
"text": "<p>I would recommend you to encapsulate the MessageDlg inside of you own procedures, this way if you change your procedures all your Message dialogs will be changed and you keep a standard.</p>\n\n<p>Example: Create some procedures like, Alert(), Error(), Warning(), etc. If you ever need to change your error message looks, you need to do it only in one place.</p>\n\n<p>Someday you might want to add a picture to your error messages, alerts... whatever, who knows?</p>\n"
},
{
"answer_id": 220297,
"author": "Argalatyr",
"author_id": 18484,
"author_profile": "https://Stackoverflow.com/users/18484",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a tool like <a href=\"http://www.textpad.com\" rel=\"nofollow noreferrer\">TextPad</a> to search/replace all instances of a string across folders and subfolders. So, I would suggest that you replace \"MessageDlg(\" with \"MyMessageDlg(\" so that you can customize it at will. Should take all of 5 minutes.</p>\n\n<p>I think it would cause you problems to create a replacement and leave it named as it is currently in conflict with the VCL.</p>\n"
},
{
"answer_id": 220389,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 4,
"selected": true,
"text": "<p>BTW, you want to add it after the <strong>Dialogs</strong> unit in your uses clause. </p>\n\n<p>You have three choices in my opinion:</p>\n\n<ol>\n<li>Add your own unit after the <em>Dialogs</em> unit that has a method called MessageDlg and has the same signature to create your own form.</li>\n<li>Or create a whole new method, or set of methods, that creates specific dialogs using your own form. </li>\n<li>Do a global Search & Replace for <em>MessageDlg</em> with <em>DarkAxi0mMessageDlg</em> and then add your DarkAxi0mDialogs unit to your uses clause.</li>\n</ol>\n\n<p>The first one is problematic because you might miss a unit and still get the old MessageDlg. The second one takes a lot more use, but provides better flexibility in the long run. The third one is probably the easiest and with the least downsides. Make sure you backup before doing the replace, and then use a diff tool (like <a href=\"http://www.ScooterSoftware.com/\" rel=\"noreferrer\">Beyond Compare</a>) to check your changes.</p>\n"
},
{
"answer_id": 220506,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 0,
"selected": false,
"text": "<p>You can <strong>hijack the MessageDlg function</strong> and make it point to your own MyMessageDlg function (with same signature) but I think it would the least safe of all the solutions.<br>\n<strong>A bad hack in lieu of clean code IMO.</strong></p>\n\n<p>Save the original opcodes of MessageDlg (asm generated by the compiler)<br>\nPut a hard jump to your MyMessageDlg code<br>\n...then any call to MessageDlg will actually execute YOUR code ...<br>\nRestore the original code to MessageDlg<br>\nMessageDlg now behaves as usual</p>\n\n<p>It works but should be <strong>reserved for desperate situations</strong>...</p>\n"
},
{
"answer_id": 222330,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 0,
"selected": false,
"text": "<p>i made a MessageDlgEx function based on MessageDlg and dropped it into one of my \"library\" files so all my apps can use it. my function allows you to specify default & cancel buttons, give button texts, etc. it'd be a bad practice to modify/replace the built-in function. i still use the built-in function but keep this function on hand for situations where a little more is needed.</p>\n\n<p>FYI--the function returns the number of the button pressed. the first button is 1. pressing Close causes a return value of 0. the buttons have no glyphs.</p>\n\n<p>i have been using this for about 5 years & it's served me well.</p>\n\n<pre><code>function MessageDlgEx(Caption, Msg: string; AType: TMsgDlgType;\n AButtons: array of string;\n DefBtn, CanBtn: Integer; iWidth:integer=450;bCourier:boolean=false): Word;\nconst\n icMin=50;\n icButtonHeight=25;\n icInterspace=10;\n icButtonResultStart=100;\n icFirstButtonReturnValue=1;\nvar\n I, iButtonWidth, iAllButtonsWidth,\n iIconWidth,iIconHeight:Integer;\n LabelText:String;\n Frm: TForm;\n Lbl: TLabel;\n Btn: TBitBtn;\n Glyph: TImage;\n FIcon: TIcon;\n Rect:TRect;\n Caption_ca:Array[0..2000] of Char;\nbegin\n { Create the form.}\n Frm := TForm.Create(Application);\n Frm.BorderStyle := bsDialog;\n Frm.BorderIcons := [biSystemMenu];\n Frm.FormStyle := fsStayOnTop;\n Frm.Height := 185;\n Frm.Width := iWidth;\n Frm.Position := poScreenCenter;\n Frm.Caption := Caption;\n Frm.Font.Name:='MS Sans Serif';\n Frm.Font.Style:=[];\n Frm.Scaled:=false;\n\n if ResIDs[AType] <> nil then\n begin\n Glyph := TImage.Create(Frm);\n Glyph.Name := 'Image';\n Glyph.Parent := Frm;\n\n FIcon := TIcon.Create;\n try\n FIcon.Handle := LoadIcon(HInstance, ResIDs[AType]);\n iIconWidth:=FIcon.Width;\n iIconHeight:=FIcon.Height;\n Glyph.Picture.Graphic := FIcon;\n Glyph.BoundsRect := Bounds(icInterspace, icInterspace, FIcon.Width, FIcon.Height);\n finally\n FIcon.Free;\n end;\n end\n else\n begin\n iIconWidth:=0;\n iIconHeight:=0;\n end;\n\n { Loop through buttons to determine the longest caption. }\n iButtonWidth := 0;\n for I := 0 to High(AButtons) do\n iButtonWidth := Max(iButtonWidth, frm.Canvas.TextWidth(AButtons[I]));\n\n { Add padding for the button's caption}\n iButtonWidth := iButtonWidth + 18;\n\n {assert a minimum button width}\n If iButtonWidth<icMin Then\n iButtonWidth:=icMin;\n\n { Determine space required for all buttons}\n iAllButtonsWidth := iButtonWidth * (High(AButtons) + 1);\n\n { Each button has padding on each side}\n iAllButtonsWidth := iAllButtonsWidth +icInterspace*High(AButtons);\n\n { The form has to be at least as wide as the buttons with space on each side}\n if iAllButtonsWidth+icInterspace*2 > Frm.Width then\n Frm.Width := iAllButtonsWidth+icInterspace*2;\n\n if Length(Msg)>sizeof(Caption_ca) then\n SetLength(Msg,sizeof(Caption_ca));\n\n { Create the message control}\n Lbl := TLabel.Create(Frm);\n Lbl.AutoSize := False;\n Lbl.Left := icInterspace*2+iIconWidth;\n Lbl.Top := icInterspace;\n Lbl.Height := 200;\n Lbl.Width := Frm.ClientWidth - icInterspace*3-iIconWidth;\n Lbl.WordWrap := True;\n Lbl.Caption := Msg;\n Lbl.Parent := Frm;\n\n if bCourier then\n lbl.Font.Name:='Courier New';\n\n Rect := Lbl.ClientRect;\n LabelText:=Lbl.Caption;\n StrPCopy(Caption_ca, LabelText);\n\n Lbl.Height:=DrawText(Lbl.Canvas.Handle,\n Caption_ca,\n Length(LabelText),\n Rect,\n DT_CalcRect or DT_ExpandTabs or DT_WordBreak Or DT_Left);\n\n\n If Lbl.Height<iIconHeight Then\n Lbl.Height:=iIconHeight;\n\n { Adjust the form's height accomodating the message, padding and the buttons}\n Frm.ClientHeight := Lbl.Height + 3*icInterspace + icButtonHeight;\n\n { Create the pusbuttons}\n for I := 0 to High(AButtons) do\n begin\n Btn := TBitBtn.Create(Frm);\n Btn.Height := icButtonHeight;\n Btn.Width := iButtonWidth;\n Btn.Left:=((Frm.Width-iAllButtonsWidth) Div 2)+I*(iButtonWidth+icInterspace);\n Btn.Top := Frm.ClientHeight - Btn.height-icInterspace;\n Btn.Caption := AButtons[I];\n Btn.ModalResult := I + icButtonResultStart + icFirstButtonReturnValue;\n Btn.Parent := Frm;\n\n If I=DefBtn-1 Then\n Begin\n Frm.ActiveControl:=Btn;\n Btn.Default:=True;\n End\n Else\n Btn.Default:=False;\n\n If I=CanBtn-1 Then\n Btn.Cancel:=True\n Else\n Btn.Cancel:=False;\n end;\n\n Application.BringToFront;\n\n Result := Frm.ShowModal;\n\n {trap and convert user Close into mrNone}\n If Result=mrCancel Then\n Result:=mrNone\n Else\n If Result>icButtonResultStart Then\n Result:=Result - icButtonResultStart\n Else\n Exception.Create('Unknown MessageDlgEx result');\n\n Frm.Free;\nend;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11016/"
] |
I have been using code similar to this
```
MessageDlg('', mtWarning, [mbOK], 0);
```
throughout my project, (thanks to the GExperts Message Dialog tool :) ) and i was wondering if anyone knows of a way do override the call and show my own custom Form.
The only way i can think to do it its make a New Form with something like
```
function MessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
begin
//show my own code here
end;
```
and put it each of my uses lists before the Dialogs unit but is there a guaranteed way to make sure it uses my code not the Dialogs unit Code.
I don't like the idea of copying the dialogs unit to a local dir and making changes to it.
Or is this all to much work and should i just use my own function call and replace all the MessageDlg with my own. (which would not be fun, ive prob used MessageDlg too much)
|
BTW, you want to add it after the **Dialogs** unit in your uses clause.
You have three choices in my opinion:
1. Add your own unit after the *Dialogs* unit that has a method called MessageDlg and has the same signature to create your own form.
2. Or create a whole new method, or set of methods, that creates specific dialogs using your own form.
3. Do a global Search & Replace for *MessageDlg* with *DarkAxi0mMessageDlg* and then add your DarkAxi0mDialogs unit to your uses clause.
The first one is problematic because you might miss a unit and still get the old MessageDlg. The second one takes a lot more use, but provides better flexibility in the long run. The third one is probably the easiest and with the least downsides. Make sure you backup before doing the replace, and then use a diff tool (like [Beyond Compare](http://www.ScooterSoftware.com/)) to check your changes.
|
220,273 |
<p>Given a template where the HTML cannot be modified because of other requirements, how is it possible to display (rearrange) a <code>div</code> above another <code>div</code> when they are not in that order in the HTML? Both <code>div</code>s contain data that varies in height and width.</p>
<pre><code><div id="wrapper">
<div id="firstDiv">
Content to be below in this situation
</div>
<div id="secondDiv">
Content to be above in this situation
</div>
</div>
Other elements
</code></pre>
<p>Hopefully it is obvious that the desired result is:</p>
<pre class="lang-none prettyprint-override"><code>Content to be above in this situation
Content to be below in this situation
Other elements
</code></pre>
<p>When the dimensions are fixed it easy to position them where needed, but I need some ideas for when the content is variable. For the sake of this scenario, please just consider the width to be 100% on both.</p>
<p>I am specifically looking for a CSS-only solution (and it will probably have to be met with other solutions if that doesn't pan out). </p>
<p>There are other elements following this. A good suggestion was mentioned given the limited scenario I demonstrated—given that it might be the best answer, but I am looking to also make sure elements following this aren't impacted.</p>
|
[
{
"answer_id": 220321,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 2,
"selected": false,
"text": "<p>Well, with a bit of absolute positioning and some dodgy margin setting, I can get close, but it's not perfect or pretty:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#wrapper { position: relative; margin-top: 4em; }\n#firstDiv { position: absolute; top: 0; width: 100%; }\n#secondDiv { position: absolute; bottom: 0; width: 100%; }\n</code></pre>\n\n<p>The \"margin-top: 4em\" is the particularly nasty bit: this margin needs to be adjusted according to the amount of content in the firstDiv. Depending on your exact requirements, this might be possible, but I'm hoping anyway that someone might be able to build on this for a solid solution.</p>\n\n<p>Eric's comment about JavaScript should probably be pursued.</p>\n"
},
{
"answer_id": 220326,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 3,
"selected": false,
"text": "<p>If you know, or can enforce the size for the to-be-upper element, you could use </p>\n\n<pre><code>position : absolute;\n</code></pre>\n\n<p>In your css and give the divs their position.</p>\n\n<p>otherwise javascript seems the only way to go:</p>\n\n<pre><code>fd = document.getElementById( 'firstDiv' );\nsd = document.getElementById( 'secondDiv' );\nfd.parentNode.removeChild( fd );\nsd.parentNode.insertAfter( fd, sd );\n</code></pre>\n\n<p>or something similar.</p>\n\n<p>edit: I just found this which might be useful: <a href=\"http://www.w3.org/TR/2003/WD-css3-content-20030514/#move-to\" rel=\"nofollow noreferrer\">w3 document css3 move-to</a></p>\n"
},
{
"answer_id": 220335,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "<p>As others have said, this isn't something you'd want to be doing in CSS. You can fudge it with absolute positioning and strange margins, but it's just not a robust solution. The best option in your case would be to turn to javascript. In jQuery, this is a very simple task:</p>\n\n<pre><code>$('#secondDiv').insertBefore('#firstDiv');\n</code></pre>\n\n<p>or more generically:</p>\n\n<pre><code>$('.swapMe').each(function(i, el) {\n $(el).insertBefore($(el).prev());\n});\n</code></pre>\n"
},
{
"answer_id": 220336,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a solution:</p>\n\n<pre><code><style>\n#firstDiv {\n position:absolute; top:100%;\n}\n#wrapper {\n position:relative; \n}\n</code></pre>\n\n<p>But I suspect you have some content that follows the wrapper div...</p>\n"
},
{
"answer_id": 224224,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 3,
"selected": false,
"text": "<p>Negative top margins can achieve this effect, but they would need to be customized for each page. For instance, this markup...</p>\n\n<pre><code><div class=\"product\">\n<h2>Greatest Product Ever</h2>\n<p class=\"desc\">This paragraph appears in the source code directly after the heading and will appear in the search results.</p>\n<p class=\"sidenote\">Note: This information appears in HTML after the product description appearing below.</p>\n</div>\n</code></pre>\n\n<p>...and this CSS...</p>\n\n<pre><code>.product { width: 400px; }\n.desc { margin-top: 5em; }\n.sidenote { margin-top: -7em; }\n</code></pre>\n\n<p>...would allow you to pull the second paragraph above the first.</p>\n\n<p>Of course, you'll have to manually tweak your CSS for different description lengths so that the intro paragraph jumps up the appropriate amount, but if you have limited control over the other parts and full control over markup and CSS then this might be an option.</p>\n"
},
{
"answer_id": 549760,
"author": "user65952",
"author_id": 65952,
"author_profile": "https://Stackoverflow.com/users/65952",
"pm_score": -1,
"selected": false,
"text": "<p>CSS really shouldn't be used to restructure the HTML backend. However, it is possible if you know the height of both elements involved and are feeling hackish. Also, text selection will be messed up when going between the divs, but that's because the HTML and CSS order are opposite.</p>\n\n<pre><code>#firstDiv { position: relative; top: YYYpx; height: XXXpx; }\n#secondDiv { position: relative; top: -XXXpx; height: YYYpx; }\n</code></pre>\n\n<p>Where XXX and YYY are the heights of firstDiv and secondDiv respectively. This will work with trailing elements, unlike the top answer.</p>\n"
},
{
"answer_id": 549921,
"author": "Matt Howell",
"author_id": 2321,
"author_profile": "https://Stackoverflow.com/users/2321",
"pm_score": 5,
"selected": false,
"text": "<p>There is absolutely no way to achieve what you want through CSS alone while supporting pre-flexbox user agents (<a href=\"https://caniuse.com/#feat=flexbox\" rel=\"nofollow noreferrer\">mostly old IE</a>) -- <strong>unless</strong>:</p>\n\n<ol>\n<li>You know the exact rendered height of each element (if so, you can absolutely position the content). If you're dealing with dynamically generated content, you're out of luck.</li>\n<li>You know the exact number of these elements there will be. Again, if you need to do this for several chunks of content that are generated dynamically, you're out of luck, especially if there are more than three or so.</li>\n</ol>\n\n<p>If the above are true then you can do what you want by absolutely positioning the elements --</p>\n\n<pre><code>#wrapper { position: relative; }\n#firstDiv { position: absolute; height: 100px; top: 110px; }\n#secondDiv { position: absolute; height: 100px; top: 0; }\n</code></pre>\n\n<p>Again, if you don't know the height want for at least #firstDiv, there's no way you can do what you want via CSS alone. If any of this content is dynamic, you will have to use javascript.</p>\n"
},
{
"answer_id": 2950011,
"author": "KoolKabin",
"author_id": 178301,
"author_profile": "https://Stackoverflow.com/users/178301",
"pm_score": -1,
"selected": false,
"text": "<p>For CSS Only solution\n1. Either height of wrapper should be fixed or\n2. height of second div should be fixed</p>\n"
},
{
"answer_id": 4984052,
"author": "Reza Amya",
"author_id": 615014,
"author_profile": "https://Stackoverflow.com/users/615014",
"pm_score": 2,
"selected": false,
"text": "<p>In your CSS, float the first div by left or right. Float the second div by left or right same as first. Apply <code>clear: left</code> or <code>right</code> the same as the above two divs for the second div.</p>\n\n<p>For example:</p>\n\n<pre><code>#firstDiv {\n float: left;\n}\n\n#secondDiv {\n float: left;\n clear: left;\n}\n</code></pre>\n"
},
{
"answer_id": 6711150,
"author": "Tom Denley",
"author_id": 846927,
"author_profile": "https://Stackoverflow.com/users/846927",
"pm_score": -1,
"selected": false,
"text": "<p>Or set an absolute position to the element and work off the margins by declaring them from the edge of the page rather than the edge of the object. Use % as its more suitable for other screen sizes ect. This is how i overcame the issue...Thanks, hope its what your looking for...</p>\n"
},
{
"answer_id": 7514803,
"author": "z666zz666z",
"author_id": 608040,
"author_profile": "https://Stackoverflow.com/users/608040",
"pm_score": -1,
"selected": false,
"text": "<p>I have a much better code, made by me, it is so big, just to show both things... create a 4x4 table and vertical align more than just one cell.</p>\n\n<p>It does not use any IE hack, no vertical-align:middle; at all... </p>\n\n<p>It does not use for vertical centering display-table, display:table-rom; display:table-cell;</p>\n\n<p>It uses the trick of a container that has two divs, one hidden (position is not the correct but makes parent have the correct variable size), one visible just after the hidden but with top:-50%; so it is mover to correct position.</p>\n\n<p>See div classes that make the trick:\n BloqueTipoContenedor\n BloqueTipoContenedor_VerticalmenteCentrado\n BloqueTipoContenido_VerticalmenteCentrado_Oculto\n BloqueTipoContenido_VerticalmenteCentrado_Visible</p>\n\n<p>Please sorry for using Spanish on classes names (it is because i speak spanish and this is so tricky that if i use English i get lost).</p>\n\n<p>The full code:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n<meta http-equiv=\"Content-Language\" content=\"en\" />\n<meta name=\"language\" content=\"en\" />\n<title>Vertical Centering in CSS2 - Example (IE, FF & Chrome tested) - This is so tricky!!!</title>\n<style type=\"text/css\">\n html,body{\n margin:0px;\n padding:0px;\n width:100%;\n height:100%;\n }\n div.BloqueTipoTabla{\n display:table;margin:0px;border:0px;padding:0px;width:100%;height:100%;\n }\n div.BloqueTipoFila_AltoAjustadoAlContenido{\n display:table-row;margin:0px;border:0px;padding:0px;width:100%;height:auto;\n }\n div.BloqueTipoFila_AltoRestante{\n display:table-row;margin:0px;border:0px;padding:0px;width:100%;height:100%;\n }\n div.BloqueTipoCelda_AjustadoAlContenido{\n display:table-cell;margin:0px;border:0px;padding:0px;width:auto;height:auto;\n }\n div.BloqueTipoCelda_RestanteAncho{\n display:table-cell;margin:0px;border:0px;padding:0px;width:100%;height:auto;\n }\n div.BloqueTipoCelda_RestanteAlto{\n display:table-cell;margin:0px;border:0px;padding:0px;width:auto;height:100%;\n }\n div.BloqueTipoCelda_RestanteAnchoAlto{\n display:table-cell;margin:0px;border:0px;padding:0px;width:100%;height:100%;\n }\n div.BloqueTipoContenedor{\n display:block;margin:0px;border:0px;padding:0px;width:100%;height:100%;position:relative;\n }\n div.BloqueTipoContenedor_VerticalmenteCentrado{\n display:block;margin:0px;border:0px;padding:0px;width:100%;height:auto;position:relative;top:50%;\n }\n div.BloqueTipoContenido_VerticalmenteCentrado_Oculto{\n display:block;margin:0px;border:0px;padding:0px;width:100%;height:auto;visibility:hidden;position:relative;top:50%;\n }\n div.BloqueTipoContenido_VerticalmenteCentrado_Visible{\n display:block;margin:0px;border:0px;padding:0px;width:100%;height:auto;visibility:visible;position:absolute;top:-50%;\n }\n</style>\n</head>\n<body>\n<h1>Vertical Centering in CSS2 - Example<br />(IE, FF & Chrome tested)<br />This is so tricky!!!</h1>\n<div class=\"BloqueTipoTabla\" style=\"margin:0px 0px 0px 25px;width:75%;height:66%;border:1px solid blue;\">\n <div class=\"BloqueTipoFila_AltoAjustadoAlContenido\">\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [1,1]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [1,2]\n </div>\n <div class=\"BloqueTipoCelda_RestanteAncho\">\n [1,3]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [1,4]\n </div>\n </div>\n <div class=\"BloqueTipoFila_AltoAjustadoAlContenido\">\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [2,1]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [2,2]\n </div>\n <div class=\"BloqueTipoCelda_RestanteAncho\">\n [2,3]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [2,4]\n </div>\n</div>\n <div class=\"BloqueTipoFila_AltoRestante\">\n <div class=\"BloqueTipoCelda_RestanteAlto\">\n <div class=\"BloqueTipoContenedor\" style=\"border:1px solid lime;\">\n <div class=\"BloqueTipoContenedor_VerticalmenteCentrado\" style=\"border:1px dotted red;\">\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Oculto\">\n The cell [3,1]\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n Now&nbsp;is&nbsp;the&nbsp;highest&nbsp;one\n </div>\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Visible\" style=\"border:1px dotted blue;\">\n The cell [3,1]\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n *&nbsp;*&nbsp;*&nbsp;*\n <br />\n Now&nbsp;is&nbsp;the&nbsp;highest&nbsp;one\n </div>\n </div>\n </div>\n </div>\n <div class=\"BloqueTipoCelda_RestanteAlto\">\n <div class=\"BloqueTipoContenedor\" style=\"border:1px solid lime;\">\n <div class=\"BloqueTipoContenedor_VerticalmenteCentrado\" style=\"border:1px dotted red;\">\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Oculto\">\n This&nbsp;is<br />cell&nbsp;[3,2]\n </div>\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Visible\" style=\"border:1px dotted blue;\">\n This&nbsp;is<br />cell&nbsp;[3,2]\n </div>\n </div>\n </div>\n </div>\n <div class=\"BloqueTipoCelda_RestanteAnchoAlto\">\n <div class=\"BloqueTipoContenedor\" style=\"border:1px solid lime;\">\n <div class=\"BloqueTipoContenedor_VerticalmenteCentrado\" style=\"border:1px dotted red;\">\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Oculto\">\n This is cell [3,3]\n <br/>\n It is duplicated on source to make the trick to know its variable height\n <br />\n First copy is hidden and second copy is visible\n <br/>\n Other cells of this row are not correctly aligned only on IE!!!\n </div>\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Visible\" style=\"border:1px dotted blue;\">\n This is cell [3,3]\n <br/>\n It is duplicated on source to make the trick to know its variable height\n <br />\n First copy is hidden and second copy is visible\n <br/>\n Other cells of this row are not correctly aligned only on IE!!!\n </div>\n </div>\n </div>\n </div>\n <div class=\"BloqueTipoCelda_RestanteAlto\">\n <div class=\"BloqueTipoContenedor\" style=\"border:1px solid lime;\">\n <div class=\"BloqueTipoContenedor_VerticalmenteCentrado\" style=\"border:1px dotted red;\">\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Oculto\">\n This&nbsp;other is<br />the cell&nbsp;[3,4]\n </div>\n <div class=\"BloqueTipoContenido_VerticalmenteCentrado_Visible\" style=\"border:1px dotted blue;\">\n This&nbsp;other is<br />the cell&nbsp;[3,4]\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"BloqueTipoFila_AltoAjustadoAlContenido\">\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [4,1]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [4,2]\n </div>\n <div class=\"BloqueTipoCelda_RestanteAncho\">\n [4,3]\n </div>\n <div class=\"BloqueTipoCelda_AjustadoAlContenido\">\n [4,4]\n </div>\n </div>\n</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 12069537,
"author": "Jordi",
"author_id": 1134242,
"author_profile": "https://Stackoverflow.com/users/1134242",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://tanalin.com/en/articles/css-block-order/\" rel=\"noreferrer\">This solution</a> uses only CSS and works with variable content</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#wrapper { display: table; }\n#firstDiv { display: table-footer-group; }\n#secondDiv { display: table-header-group; }\n</code></pre>\n"
},
{
"answer_id": 13332006,
"author": "Pmillan",
"author_id": 920123,
"author_profile": "https://Stackoverflow.com/users/920123",
"pm_score": -1,
"selected": false,
"text": "<p>It is easy with css, just use <code>display:block</code> and <code>z-index</code> property</p>\n\n<p>Here is an example:</p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code><body>\n <div class=\"wrapper\">\n\n <div class=\"header\">\n header\n </div>\n\n <div class=\"content\">\n content\n </div>\n </div>\n</body>\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>.wrapper\n{\n [...]\n}\n\n.header\n{\n [...]\n z-index:9001;\n display:block;\n [...]\n}\n\n.content\n{\n [...]\n z-index:9000;\n [...]\n}\n</code></pre>\n\n<p>Edit: It is good to set some <code>background-color</code> to the <code>div-s</code> to see things properly.</p>\n"
},
{
"answer_id": 17364200,
"author": "Jose Paitamala",
"author_id": 2531748,
"author_profile": "https://Stackoverflow.com/users/2531748",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking for a way to change the orders of the divs only for mobile version so then I can style it nicely. Thanks to nickf reply I got to make this piece of code which worked well for what I wanted, so i though of sharing it with you guys:</p>\n\n<pre><code>// changing the order of the sidebar so it goes after the content for mobile versions\njQuery(window).resize(function(){\n if ( jQuery(window).width() < 480 )\n {\n jQuery('#main-content').insertBefore('#sidebar');\n }\n if ( jQuery(window).width() > 480 )\n {\n jQuery('#sidebar').insertBefore('#main-content');\n }\n jQuery(window).height(); // New height\n jQuery(window).width(); // New width\n});\n</code></pre>\n"
},
{
"answer_id": 24214855,
"author": "BlakePetersen",
"author_id": 2510949,
"author_profile": "https://Stackoverflow.com/users/2510949",
"pm_score": 5,
"selected": false,
"text": "<p>This can be done using Flexbox. </p>\n\n<p>Create a container that applies both <strong>display:flex</strong> and <strong>flex-flow:column-reverse</strong>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* -- Where the Magic Happens -- */\r\n\r\n.container {\r\n \r\n /* Setup Flexbox */\r\n display: -webkit-box;\r\n display: -moz-box;\r\n display: -ms-flexbox;\r\n display: -webkit-flex;\r\n display: flex;\r\n\r\n /* Reverse Column Order */\r\n -webkit-flex-flow: column-reverse;\r\n flex-flow: column-reverse;\r\n\r\n}\r\n\r\n\r\n/* -- Styling Only -- */\r\n\r\n.container > div {\r\n background: red;\r\n color: white;\r\n padding: 10px;\r\n}\r\n\r\n.container > div:last-of-type {\r\n background: blue;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"container\">\r\n \r\n <div class=\"first\">\r\n\r\n first\r\n\r\n </div>\r\n \r\n <div class=\"second\">\r\n\r\n second\r\n\r\n </div>\r\n \r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Sources:</p>\n\n<ul>\n<li><a href=\"https://css-tricks.com/using-flexbox/\">https://css-tricks.com/using-flexbox/</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow#Browser_compatibility\">https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow#Browser_compatibility</a></li>\n</ul>\n"
},
{
"answer_id": 27861762,
"author": "K.Kutschera",
"author_id": 4437027,
"author_profile": "https://Stackoverflow.com/users/4437027",
"pm_score": -1,
"selected": false,
"text": "<pre><code>.move-wrap {\n display: table;\n table-layout: fixed; // prevent some responsive bugs\n width: 100%; // set a width if u like\n /* TODO: js-fallback IE7 if u like ms */\n}\n\n.move-down {\n display: table-footer-group;\n}\n\n.move-up {\n display: table-header-group;\n}\n</code></pre>\n"
},
{
"answer_id": 28159766,
"author": "Justin",
"author_id": 922522,
"author_profile": "https://Stackoverflow.com/users/922522",
"pm_score": 8,
"selected": false,
"text": "<p><strong>A CSS-only solution</strong> (works for <a href=\"http://caniuse.com/flexbox\" rel=\"noreferrer\">IE10+</a>) – use Flexbox's <code>order</code> property:</p>\n\n<p>Demo: <a href=\"http://jsfiddle.net/hqya7q6o/596/\" rel=\"noreferrer\">http://jsfiddle.net/hqya7q6o/596/</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-css lang-css prettyprint-override\"><code>#flex { display: flex; flex-direction: column; }\r\n#a { order: 2; }\r\n#b { order: 1; }\r\n#c { order: 3; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"flex\">\r\n <div id=\"a\">A</div>\r\n <div id=\"b\">B</div>\r\n <div id=\"c\">C</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>More info: <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/order\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/CSS/order</a></p>\n"
},
{
"answer_id": 28207196,
"author": "Gian Miller",
"author_id": 4505835,
"author_profile": "https://Stackoverflow.com/users/4505835",
"pm_score": -1,
"selected": false,
"text": "<p>I have a simple way to do this.</p>\n\n<pre><code><!-- HTML -->\n\n<div class=\"wrapper\">\n\n <div class=\"sm-hide\">This content hides when at your layouts chosen breaking point.</div>\n\n <div>Content that stays in place</div>\n\n <div class=\"sm-show\">This content is set to show at your layouts chosen breaking point.</div>\n\n</div>\n\n<!-- CSS -->\n\n .sm-hide {display:block;}\n .sm-show {display:none;}\n\n@media (max-width:598px) {\n .sm-hide {display:none;}\n .sm-show {display:block;}\n}\n</code></pre>\n"
},
{
"answer_id": 30380136,
"author": "jansmolders86",
"author_id": 1077230,
"author_profile": "https://Stackoverflow.com/users/1077230",
"pm_score": 2,
"selected": false,
"text": "<p>This can be done with CSS only! </p>\n\n<p>Please check my answer to this similar question:</p>\n\n<p><a href=\"https://stackoverflow.com/a/25462829/1077230\">https://stackoverflow.com/a/25462829/1077230</a></p>\n\n<p>I don't want to double post my answer but the short of it is that the parent needs to become a flexbox element. Eg: </p>\n\n<p>(only using the webkit vendor prefix here.)</p>\n\n<pre><code>#main {\n display: -webkit-box;\n display: -webkit-flex;\n display: flex;\n -webkit-box-orient: vertical;\n -webkit-flex-direction: column;\n flex-direction: column;\n -webkit-box-align: start;\n -webkit-align-items: flex-start;\n align-items: flex-start;\n}\n</code></pre>\n\n<p>Then, swap divs around by indicating their order with:</p>\n\n<pre><code>#main > div#one{\n -webkit-box-ordinal-group: 2;\n -moz-box-ordinal-group: 2;\n -ms-flex-order: 2;\n -webkit-order: 2;\n order: 2;\n overflow:visible;\n}\n\n#main > div#two{\n -webkit-box-ordinal-group: 1;\n -moz-box-ordinal-group: 1;\n -ms-flex-order: 1;\n -webkit-order: 1;\n order: 1;\n}\n</code></pre>\n"
},
{
"answer_id": 33255407,
"author": "Arun Kumar M",
"author_id": 5173098,
"author_profile": "https://Stackoverflow.com/users/5173098",
"pm_score": 4,
"selected": false,
"text": "<p>With CSS3 flexbox layout module, you can order divs.</p>\n\n<pre><code>#wrapper {\n display: flex;\n flex-direction: column;\n}\n#firstDiv {\n order: 2;\n}\n\n<div id=\"wrapper\">\n <div id=\"firstDiv\">\n Content1\n </div>\n <div id=\"secondDiv\">\n Content2\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 39004402,
"author": "MUSTAPHA ABDULRASHEED",
"author_id": 6589406,
"author_profile": "https://Stackoverflow.com/users/6589406",
"pm_score": 0,
"selected": false,
"text": "<p>Just use flex for the parent div by specifying <code>display: flex</code> and <code>flex-direction : column</code>.\nThen use order to determine which of the child div comes first</p>\n"
},
{
"answer_id": 39628823,
"author": "Finesse",
"author_id": 1118709,
"author_profile": "https://Stackoverflow.com/users/1118709",
"pm_score": 2,
"selected": false,
"text": "<p>A solution with a bigger browser support then the flexbox (works in IE≥9):</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-css lang-css prettyprint-override\"><code>#wrapper {\r\n -webkit-transform: scaleY(-1);\r\n -ms-transform: scaleY(-1);\r\n transform: scaleY(-1);\r\n}\r\n#wrapper > * {\r\n -webkit-transform: scaleY(-1);\r\n -ms-transform: scaleY(-1);\r\n transform: scaleY(-1);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"wrapper\">\r\n <div id=\"firstDiv\">\r\n Content to be below in this situation\r\n </div>\r\n <div id=\"secondDiv\">\r\n Content to be above in this situation\r\n </div>\r\n</div>\r\nOther elements</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In contrast to the <code>display: table;</code> solution this solution works when <code>.wrapper</code> has any amount of children.</p>\n"
},
{
"answer_id": 42706942,
"author": "lsrom",
"author_id": 4751720,
"author_profile": "https://Stackoverflow.com/users/4751720",
"pm_score": -1,
"selected": false,
"text": "<p>Little late to the party, but you can also do this:</p>\n\n<pre><code><div style=\"height: 500px; width: 500px;\">\n\n<div class=\"bottom\" style=\"height: 250px; width: 500px; background: red; margin-top: 250px;\"></div>\n\n<div class=\"top\" style=\"height: 250px; width: 500px; background: blue; margin-top: -500px;\"></div>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 59388711,
"author": "al-bulat",
"author_id": 9056683,
"author_profile": "https://Stackoverflow.com/users/9056683",
"pm_score": 3,
"selected": false,
"text": "<p><strong>If you just use css, you can use flex.</strong></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-css lang-css prettyprint-override\"><code>.price {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n\r\n flex-direction: row-reverse; //revert horizontally\r\n //flex-direction: column-reverse; revert vertically\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"price\">\r\n <div>first block</div>\r\n <div>second block</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 65441414,
"author": "Alan",
"author_id": 5449450,
"author_profile": "https://Stackoverflow.com/users/5449450",
"pm_score": 3,
"selected": false,
"text": "<p>Ordering only for mobile and keep the native order for desktop:</p>\n<p>// html</p>\n<pre><code><div>\n <div class="gridInverseMobile1">First</div>\n <div class="gridInverseMobile1">Second</div>\n</div>\n</code></pre>\n<p>// css</p>\n<pre><code>@media only screen and (max-width: 960px) {\n .gridInverseMobile1 {\n order: 2;\n -webkit-order: 2;\n }\n .gridInverseMobile2 {\n order: 1;\n -webkit-order: 1;\n }\n}\n</code></pre>\n<p>Result:</p>\n<pre><code>Desktop: First | Second\nMobile: Second | First\n</code></pre>\n<p>source: <a href=\"https://www.w3schools.com/cssref/css3_pr_order.asp\" rel=\"noreferrer\">https://www.w3schools.com/cssref/css3_pr_order.asp</a></p>\n"
},
{
"answer_id": 69852350,
"author": "Aleandro Coppola",
"author_id": 4083794,
"author_profile": "https://Stackoverflow.com/users/4083794",
"pm_score": 3,
"selected": false,
"text": "<p>You can use Flex</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-css lang-css prettyprint-override\"><code>#wrapper {\n display: flex;\n flex-direction: column;\n}\n\n#firstDiv {\n order: 1;\n}\n\n#secondDiv {\n order: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"wrapper\">\n <div id=\"firstDiv\">\n Content to be below in this situation\n </div>\n <div id=\"secondDiv\">\n Content to be above in this situation\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69880977,
"author": "Chuong Tran",
"author_id": 8568835,
"author_profile": "https://Stackoverflow.com/users/8568835",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to reverse displaying order of children. I suggest you use this</p>\n<blockquote>\n<p><code>direction: rtl;</code> // Right to left</p>\n</blockquote>\n<p>Set this property in parent element</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12368/"
] |
Given a template where the HTML cannot be modified because of other requirements, how is it possible to display (rearrange) a `div` above another `div` when they are not in that order in the HTML? Both `div`s contain data that varies in height and width.
```
<div id="wrapper">
<div id="firstDiv">
Content to be below in this situation
</div>
<div id="secondDiv">
Content to be above in this situation
</div>
</div>
Other elements
```
Hopefully it is obvious that the desired result is:
```none
Content to be above in this situation
Content to be below in this situation
Other elements
```
When the dimensions are fixed it easy to position them where needed, but I need some ideas for when the content is variable. For the sake of this scenario, please just consider the width to be 100% on both.
I am specifically looking for a CSS-only solution (and it will probably have to be met with other solutions if that doesn't pan out).
There are other elements following this. A good suggestion was mentioned given the limited scenario I demonstrated—given that it might be the best answer, but I am looking to also make sure elements following this aren't impacted.
|
[This solution](http://tanalin.com/en/articles/css-block-order/) uses only CSS and works with variable content
```css
#wrapper { display: table; }
#firstDiv { display: table-footer-group; }
#secondDiv { display: table-header-group; }
```
|
220,323 |
<p>I have a class with the following member functions:</p>
<pre><code>
/// caller pid
virtual pid_t Pid() const = 0;
/// physical memory size in KB
virtual uint64_t Size() const = 0;
/// resident memory for this process
virtual uint64_t Rss() const = 0;
/// cpu used by this process
virtual double PercentCpu() const = 0;
/// memory used by this process
virtual double PercentMemory() const = 0;
/// number of threads in this process
virtual int32_t Lwps() const = 0;
</code>
</pre>
<p>This class' duty is to return process information about caller. Physical memory size can easily determined by a sysctl call, and pid is trivial, but the remaining calls have eluded me, aside from invoking a popen on ps or top and parsing the output - which isn't acceptable. Any help would be greatly appreciated.</p>
<p>Requirements:<br/>
Compiles on g++ 4.0<br/>
No obj-c<br/>
OSX 10.5<br/></p>
|
[
{
"answer_id": 220348,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>I think most of these values are available in the Mach API, but it's been a while since I've poked around in there. Alternatively, you could just look at the source code for the \"ps\" or \"top\" commands, and see how they do it.</p>\n"
},
{
"answer_id": 220352,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 0,
"selected": false,
"text": "<p>Most of this info can be gotten from <a href=\"http://developer.apple.com/documentation/Carbon/Reference/Process_Manager/Reference/reference.html#//apple_ref/doc/uid/TP30000208-CH1g-TPXREF103\" rel=\"nofollow noreferrer\">GetProcessInformation()</a>.</p>\n\n<p>By the way, why virtual methods for functions that return processwide info?</p>\n\n<p>This is <strong>CARBON</strong> only, and won't work with cocoa</p>\n"
},
{
"answer_id": 220546,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "<p>Since you say no Objective-C we'll rule out most of the MacOS frameworks.</p>\n\n<p>You can get CPU time using getrusage(), which gives the total amount of User and System CPU time charged to your process. To get a CPU percentage you'd need to snapshot the getrusage values once per second (or however granular you want to be).</p>\n\n<pre><code>#include <sys/resource.h>\n\nstruct rusage r_usage;\n\nif (getrusage(RUSAGE_SELF, &r_usage)) {\n /* ... error handling ... */\n}\n\nprintf(\"Total User CPU = %ld.%ld\\n\",\n r_usage.ru_utime.tv_sec,\n r_usage.ru_utime.tv_usec);\nprintf(\"Total System CPU = %ld.%ld\\n\",\n r_usage.ru_stime.tv_sec,\n r_usage.ru_stime.tv_usec);\n</code></pre>\n\n<p>There is an RSS field in the getrusage structure, but is appears to always be zero in MacOS X 10.5. <A HREF=\"http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html\" rel=\"noreferrer\">Michael Knight</A> wrote a blog post several years ago about how to determine the RSS.</p>\n"
},
{
"answer_id": 220908,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 5,
"selected": true,
"text": "<p>Process info comes from <code>pidinfo</code>:</p>\n\n<pre><code>cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h\n\nint proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize);\n</code></pre>\n\n<p>cpu load comes from <code>host_statistics</code>:</p>\n\n<pre><code>cristi:~ diciu$ grep -r host_statistics /usr/include/\n\n/usr/include/mach/host_info.h:/* host_statistics() */\n\n/usr/include/mach/mach_host.defs:routine host_statistics(\n\n/usr/include/mach/mach_host.h:/* Routine host_statistics */\n\n/usr/include/mach/mach_host.h:kern_return_t host_statistics\n</code></pre>\n\n<p>For more details, check out sources for <code>top</code> and <code>lsof</code>, they are open source (you need to register as an Apple developer but that's free of charge):</p>\n\n<p><a href=\"https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html\" rel=\"nofollow noreferrer\">https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html</a></p>\n\n<p><strong>Later edit:</strong> All these interfaces are version specific, so you need to take that into account when writing production code (libproc.h):</p>\n\n<pre><code>/*\n * This header file contains private interfaces to obtain process information.\n * These interfaces are subject to change in future releases.\n */\n</code></pre>\n"
},
{
"answer_id": 16522537,
"author": "hamed",
"author_id": 1859571,
"author_profile": "https://Stackoverflow.com/users/1859571",
"pm_score": 2,
"selected": false,
"text": "<p>You can use below code for process info in mac OS:</p>\n\n<pre><code>void IsInBSDProcessList(char *name) { \n assert( name != NULL); \n kinfo_proc *result; \n size_t count = 0; \n result = (kinfo_proc *)malloc(sizeof(kinfo_proc)); \n if(GetBSDProcessList(&result,&count) == 0) { \n for (int i = 0; i < count; i++) { \n kinfo_proc *proc = NULL; \n proc = &result[i]; \n }\n } \n free(result);\n}\n</code></pre>\n\n<p>kinfo_proc struct contains all the information about a process.such as Process identifier (pid),\n process group, process status and etc. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29810/"
] |
I have a class with the following member functions:
```
/// caller pid
virtual pid_t Pid() const = 0;
/// physical memory size in KB
virtual uint64_t Size() const = 0;
/// resident memory for this process
virtual uint64_t Rss() const = 0;
/// cpu used by this process
virtual double PercentCpu() const = 0;
/// memory used by this process
virtual double PercentMemory() const = 0;
/// number of threads in this process
virtual int32_t Lwps() const = 0;
```
This class' duty is to return process information about caller. Physical memory size can easily determined by a sysctl call, and pid is trivial, but the remaining calls have eluded me, aside from invoking a popen on ps or top and parsing the output - which isn't acceptable. Any help would be greatly appreciated.
Requirements:
Compiles on g++ 4.0
No obj-c
OSX 10.5
|
Process info comes from `pidinfo`:
```
cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h
int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize);
```
cpu load comes from `host_statistics`:
```
cristi:~ diciu$ grep -r host_statistics /usr/include/
/usr/include/mach/host_info.h:/* host_statistics() */
/usr/include/mach/mach_host.defs:routine host_statistics(
/usr/include/mach/mach_host.h:/* Routine host_statistics */
/usr/include/mach/mach_host.h:kern_return_t host_statistics
```
For more details, check out sources for `top` and `lsof`, they are open source (you need to register as an Apple developer but that's free of charge):
<https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html>
**Later edit:** All these interfaces are version specific, so you need to take that into account when writing production code (libproc.h):
```
/*
* This header file contains private interfaces to obtain process information.
* These interfaces are subject to change in future releases.
*/
```
|
220,340 |
<p>I want to be able to check the status of a publication and subscription in SQL Server 2008 T-SQL. I want to be able to determine if its okay, when was the last successful, sync, etc.. Is this possible?</p>
|
[
{
"answer_id": 4036445,
"author": "Denaem",
"author_id": 331461,
"author_profile": "https://Stackoverflow.com/users/331461",
"pm_score": 5,
"selected": false,
"text": "<p>I know this is a little late....</p>\n\n<pre><code>SELECT \n(CASE \n WHEN mdh.runstatus = '1' THEN 'Start - '+cast(mdh.runstatus as varchar)\n WHEN mdh.runstatus = '2' THEN 'Succeed - '+cast(mdh.runstatus as varchar)\n WHEN mdh.runstatus = '3' THEN 'InProgress - '+cast(mdh.runstatus as varchar)\n WHEN mdh.runstatus = '4' THEN 'Idle - '+cast(mdh.runstatus as varchar)\n WHEN mdh.runstatus = '5' THEN 'Retry - '+cast(mdh.runstatus as varchar)\n WHEN mdh.runstatus = '6' THEN 'Fail - '+cast(mdh.runstatus as varchar)\n ELSE CAST(mdh.runstatus AS VARCHAR)\nEND) [Run Status], \nmda.subscriber_db [Subscriber DB], \nmda.publication [PUB Name],\nright(left(mda.name,LEN(mda.name)-(len(mda.id)+1)), LEN(left(mda.name,LEN(mda.name)-(len(mda.id)+1)))-(10+len(mda.publisher_db)+(case when mda.publisher_db='ALL' then 1 else LEN(mda.publication)+2 end))) [SUBSCRIBER],\nCONVERT(VARCHAR(25),mdh.[time]) [LastSynchronized],\nund.UndelivCmdsInDistDB [UndistCom], \nmdh.comments [Comments], \n'select * from distribution.dbo.msrepl_errors (nolock) where id = ' + CAST(mdh.error_id AS VARCHAR(8)) [Query More Info],\nmdh.xact_seqno [SEQ_NO],\n(CASE \n WHEN mda.subscription_type = '0' THEN 'Push' \n WHEN mda.subscription_type = '1' THEN 'Pull' \n WHEN mda.subscription_type = '2' THEN 'Anonymous' \n ELSE CAST(mda.subscription_type AS VARCHAR)\nEND) [SUB Type],\n\nmda.publisher_db+' - '+CAST(mda.publisher_database_id as varchar) [Publisher DB],\nmda.name [Pub - DB - Publication - SUB - AgentID]\nFROM distribution.dbo.MSdistribution_agents mda \nLEFT JOIN distribution.dbo.MSdistribution_history mdh ON mdh.agent_id = mda.id \nJOIN \n (SELECT s.agent_id, MaxAgentValue.[time], SUM(CASE WHEN xact_seqno > MaxAgentValue.maxseq THEN 1 ELSE 0 END) AS UndelivCmdsInDistDB \n FROM distribution.dbo.MSrepl_commands t (NOLOCK) \n JOIN distribution.dbo.MSsubscriptions AS s (NOLOCK) ON (t.article_id = s.article_id AND t.publisher_database_id=s.publisher_database_id ) \n JOIN \n (SELECT hist.agent_id, MAX(hist.[time]) AS [time], h.maxseq \n FROM distribution.dbo.MSdistribution_history hist (NOLOCK) \n JOIN (SELECT agent_id,ISNULL(MAX(xact_seqno),0x0) AS maxseq \n FROM distribution.dbo.MSdistribution_history (NOLOCK) \n GROUP BY agent_id) AS h \n ON (hist.agent_id=h.agent_id AND h.maxseq=hist.xact_seqno) \n GROUP BY hist.agent_id, h.maxseq \n ) AS MaxAgentValue \n ON MaxAgentValue.agent_id = s.agent_id \n GROUP BY s.agent_id, MaxAgentValue.[time] \n ) und \nON mda.id = und.agent_id AND und.[time] = mdh.[time] \nwhere mda.subscriber_db<>'virtual' -- created when your publication has the immediate_sync property set to true. This property dictates whether snapshot is available all the time for new subscriptions to be initialized. This affects the cleanup behavior of transactional replication. If this property is set to true, the transactions will be retained for max retention period instead of it getting cleaned up as soon as all the subscriptions got the change.\n--and mdh.runstatus='6' --Fail\n--and mdh.runstatus<>'2' --Succeed\norder by mdh.[time]\n</code></pre>\n"
},
{
"answer_id": 28452406,
"author": "Jamie Pollard",
"author_id": 1498003,
"author_profile": "https://Stackoverflow.com/users/1498003",
"pm_score": 3,
"selected": false,
"text": "<p>Old post but adding for others - The following stored procedure will give you what you need: </p>\n\n<ul>\n<li>sp_replmonitorhelppublication (<a href=\"https://msdn.microsoft.com/en-us/library/ms186304.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms186304.aspx</a>)</li>\n</ul>\n\n<p>It allows you to view the status plus other information for all replication publications for a distributor (run it on the distribution database)</p>\n"
},
{
"answer_id": 70593923,
"author": "JM1",
"author_id": 3729714,
"author_profile": "https://Stackoverflow.com/users/3729714",
"pm_score": 0,
"selected": false,
"text": "<p>In case it's helpful, I've combined parts of the two answers given and taken sp_replmonitorhelppublication and sp_replmonitorhelpsubscription and placed them into Temp Tables so I can sort them and exclude columns as needed.</p>\n<p>Note, the subscriber script excludes some merge columns from sp_replmonitorhelpsubscription as I'm not looking for merge replication data.</p>\n<pre><code>-------------------------------------------------------------------------------------------------------------------------\n-- PUBLISHER SCRIPT\n-------------------------------------------------------------------------------------------------------------------------\n\nIF OBJECT_ID ('tempdb..#tmp_replicationPub_monitordata') IS NOT NULL DROP TABLE #tmp_replicationPub_monitordata;\n\nCREATE TABLE #tmp_replicationPub_monitordata (\n publisher_db sysname\n , publication sysname\n , publication_id INT\n , publication_type INT\n , status INT -- publication status defined as max(status) among all agents\n , warning INT -- publication warning defined as max(isnull(warning,0)) among all agents\n , worst_latency INT\n , best_latency INT\n , average_latency INT\n , last_distsync DATETIME -- last sync time\n , retention INT -- retention period \n , latencythreshold INT\n , expirationthreshold INT\n , agentnotrunningthreshold INT\n , subscriptioncount INT -- # of subscription\n , runningdistagentcount INT -- # of running agents\n , snapshot_agentname sysname NULL\n , logreader_agentname sysname NULL\n , qreader_agentname sysname NULL\n , worst_runspeedPerf INT\n , best_runspeedPerf INT\n , average_runspeedPerf INT\n , retention_period_unit TINYINT\n , publisher sysname NULL\n);\n\nINSERT INTO #tmp_replicationPub_monitordata\nEXEC sp_replmonitorhelppublication;\n\nSELECT (CASE WHEN status = '1' THEN 'Start - ' + CAST(status AS VARCHAR)\n WHEN status = '2' THEN 'Succeed - ' + CAST(status AS VARCHAR)\n WHEN status = '3' THEN 'InProgress - ' + CAST(status AS VARCHAR)\n WHEN status = '4' THEN 'Idle - ' + CAST(status AS VARCHAR)\n WHEN status = '5' THEN 'Retry - ' + CAST(status AS VARCHAR)\n WHEN status = '6' THEN 'Fail - ' + CAST(status AS VARCHAR)ELSE CAST(status AS VARCHAR)END) [Run Status]\n , publisher_db\n , publication\n , publication_id\n , (CASE WHEN publication_type = '0' THEN 'Transactional - ' + CAST(publication_type AS VARCHAR)\n WHEN publication_type = '1' THEN 'Snapshot - ' + CAST(publication_type AS VARCHAR)\n WHEN publication_type = '2' THEN 'Merge - ' + CAST(publication_type AS VARCHAR)ELSE '' END) AS [Publication Type]\n , (CASE WHEN warning = '1' THEN 'Expiration' + CAST(warning AS VARCHAR)\n WHEN warning = '2' THEN 'Latency' + CAST(warning AS VARCHAR)\n WHEN warning = '4' THEN 'Mergeexpiration' + CAST(warning AS VARCHAR)\n WHEN warning = '16' THEN 'Mergeslowrunduration' + CAST(warning AS VARCHAR)\n WHEN warning = '32' THEN 'Mergefastrunspeed' + CAST(warning AS VARCHAR)\n WHEN warning = '64' THEN 'Mergeslowrunspeed' + CAST(warning AS VARCHAR)END) warning\n , worst_latency\n , best_latency\n , average_latency\n , last_distsync\n , retention\n , latencythreshold\n , expirationthreshold\n , agentnotrunningthreshold\n , subscriptioncount\n , runningdistagentcount\n , snapshot_agentname\n , logreader_agentname\n , qreader_agentname\n , worst_runspeedPerf\n , best_runspeedPerf\n , average_runspeedPerf\n , retention_period_unit\n , publisher\nFROM #tmp_replicationPub_monitordata\nORDER BY publication;\n\n-------------------------------------------------------------------------------------------------------------------------\n-- SUBSCRIBER SCRIPT\n-------------------------------------------------------------------------------------------------------------------------\nIF OBJECT_ID ('tempdb..#tmp_rep_monitordata ') IS NOT NULL DROP TABLE #tmp_rep_monitordata;\n\nCREATE TABLE #tmp_rep_monitordata (\n status INT NULL\n , warning INT NULL\n , subscriber sysname NULL\n , subscriber_db sysname NULL\n , publisher_db sysname NULL\n , publication sysname NULL\n , publication_type INT NULL\n , subtype INT NULL\n , latency INT NULL\n , latencythreshold INT NULL\n , agentnotrunning INT NULL\n , agentnotrunningthreshold INT NULL\n , timetoexpiration INT NULL\n , expirationthreshold INT NULL\n , last_distsync DATETIME NULL\n , distribution_agentname sysname NULL\n , mergeagentname sysname NULL\n , mergesubscriptionfriendlyname sysname NULL\n , mergeagentlocation sysname NULL\n , mergeconnectiontype INT NULL\n , mergePerformance INT NULL\n , mergerunspeed FLOAT NULL\n , mergerunduration INT NULL\n , monitorranking INT NULL\n , distributionagentjobid BINARY(16) NULL\n , mergeagentjobid BINARY(16) NULL\n , distributionagentid INT NULL\n , distributionagentprofileid INT NULL\n , mergeagentid INT NULL\n , mergeagentprofileid INT NULL\n , logreaderagentname sysname NULL\n , publisher sysname NULL\n);\n\nINSERT INTO #tmp_rep_monitordata\nEXEC sp_replmonitorhelpsubscription @publication_type = 0;\n\nINSERT INTO #tmp_rep_monitordata\nEXEC sp_replmonitorhelpsubscription @publication_type = 1;\n\nSELECT (CASE WHEN status = '1' THEN 'Start - ' + CAST(status AS VARCHAR)\n WHEN status = '2' THEN 'Succeed - ' + CAST(status AS VARCHAR)\n WHEN status = '3' THEN 'InProgress - ' + CAST(status AS VARCHAR)\n WHEN status = '4' THEN 'Idle - ' + CAST(status AS VARCHAR)\n WHEN status = '5' THEN 'Retry - ' + CAST(status AS VARCHAR)\n WHEN status = '6' THEN 'Fail - ' + CAST(status AS VARCHAR)ELSE CAST(status AS VARCHAR)END) [Run Status]\n , publisher_db\n , publication\n , (CASE WHEN warning = '1' THEN 'Expiration' + CAST(warning AS VARCHAR)\n WHEN warning = '2' THEN 'Latency' + CAST(warning AS VARCHAR)\n WHEN warning = '4' THEN 'Mergeexpiration' + CAST(warning AS VARCHAR)\n WHEN warning = '16' THEN 'Mergeslowrunduration' + CAST(warning AS VARCHAR)\n WHEN warning = '32' THEN 'Mergefastrunspeed' + CAST(warning AS VARCHAR)\n WHEN warning = '64' THEN 'Mergeslowrunspeed' + CAST(warning AS VARCHAR)END) warning\n , subscriber\n , subscriber_db\n , (CASE WHEN publication_type = '0' THEN 'Transactional - ' + CAST(publication_type AS VARCHAR)\n WHEN publication_type = '1' THEN 'Snapshot - ' + CAST(publication_type AS VARCHAR)\n WHEN publication_type = '2' THEN 'Merge - ' + CAST(publication_type AS VARCHAR)ELSE '' END) AS [Publication Type]\n , (CASE WHEN subtype = '0' THEN 'Push - ' + CAST(subtype AS VARCHAR)\n WHEN subtype = '1' THEN 'Pull - ' + CAST(subtype AS VARCHAR)\n WHEN subtype = '2' THEN 'Anonymous - ' + CAST(subtype AS VARCHAR)ELSE '' END) AS SubscriptionType\n , latency\n , latencythreshold\n , agentnotrunning\n , agentnotrunningthreshold\n , last_distsync\n , timetoexpiration\n , expirationthreshold\n , distribution_agentname\n , monitorranking\n , distributionagentjobid\n , mergeagentjobid\n , distributionagentid\n , distributionagentprofileid\n , mergeagentid\n , mergeagentprofileid\n , logreaderagentname\n , publisher\nFROM #tmp_rep_monitordata\nORDER BY publication ASC;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17222/"
] |
I want to be able to check the status of a publication and subscription in SQL Server 2008 T-SQL. I want to be able to determine if its okay, when was the last successful, sync, etc.. Is this possible?
|
I know this is a little late....
```
SELECT
(CASE
WHEN mdh.runstatus = '1' THEN 'Start - '+cast(mdh.runstatus as varchar)
WHEN mdh.runstatus = '2' THEN 'Succeed - '+cast(mdh.runstatus as varchar)
WHEN mdh.runstatus = '3' THEN 'InProgress - '+cast(mdh.runstatus as varchar)
WHEN mdh.runstatus = '4' THEN 'Idle - '+cast(mdh.runstatus as varchar)
WHEN mdh.runstatus = '5' THEN 'Retry - '+cast(mdh.runstatus as varchar)
WHEN mdh.runstatus = '6' THEN 'Fail - '+cast(mdh.runstatus as varchar)
ELSE CAST(mdh.runstatus AS VARCHAR)
END) [Run Status],
mda.subscriber_db [Subscriber DB],
mda.publication [PUB Name],
right(left(mda.name,LEN(mda.name)-(len(mda.id)+1)), LEN(left(mda.name,LEN(mda.name)-(len(mda.id)+1)))-(10+len(mda.publisher_db)+(case when mda.publisher_db='ALL' then 1 else LEN(mda.publication)+2 end))) [SUBSCRIBER],
CONVERT(VARCHAR(25),mdh.[time]) [LastSynchronized],
und.UndelivCmdsInDistDB [UndistCom],
mdh.comments [Comments],
'select * from distribution.dbo.msrepl_errors (nolock) where id = ' + CAST(mdh.error_id AS VARCHAR(8)) [Query More Info],
mdh.xact_seqno [SEQ_NO],
(CASE
WHEN mda.subscription_type = '0' THEN 'Push'
WHEN mda.subscription_type = '1' THEN 'Pull'
WHEN mda.subscription_type = '2' THEN 'Anonymous'
ELSE CAST(mda.subscription_type AS VARCHAR)
END) [SUB Type],
mda.publisher_db+' - '+CAST(mda.publisher_database_id as varchar) [Publisher DB],
mda.name [Pub - DB - Publication - SUB - AgentID]
FROM distribution.dbo.MSdistribution_agents mda
LEFT JOIN distribution.dbo.MSdistribution_history mdh ON mdh.agent_id = mda.id
JOIN
(SELECT s.agent_id, MaxAgentValue.[time], SUM(CASE WHEN xact_seqno > MaxAgentValue.maxseq THEN 1 ELSE 0 END) AS UndelivCmdsInDistDB
FROM distribution.dbo.MSrepl_commands t (NOLOCK)
JOIN distribution.dbo.MSsubscriptions AS s (NOLOCK) ON (t.article_id = s.article_id AND t.publisher_database_id=s.publisher_database_id )
JOIN
(SELECT hist.agent_id, MAX(hist.[time]) AS [time], h.maxseq
FROM distribution.dbo.MSdistribution_history hist (NOLOCK)
JOIN (SELECT agent_id,ISNULL(MAX(xact_seqno),0x0) AS maxseq
FROM distribution.dbo.MSdistribution_history (NOLOCK)
GROUP BY agent_id) AS h
ON (hist.agent_id=h.agent_id AND h.maxseq=hist.xact_seqno)
GROUP BY hist.agent_id, h.maxseq
) AS MaxAgentValue
ON MaxAgentValue.agent_id = s.agent_id
GROUP BY s.agent_id, MaxAgentValue.[time]
) und
ON mda.id = und.agent_id AND und.[time] = mdh.[time]
where mda.subscriber_db<>'virtual' -- created when your publication has the immediate_sync property set to true. This property dictates whether snapshot is available all the time for new subscriptions to be initialized. This affects the cleanup behavior of transactional replication. If this property is set to true, the transactions will be retained for max retention period instead of it getting cleaned up as soon as all the subscriptions got the change.
--and mdh.runstatus='6' --Fail
--and mdh.runstatus<>'2' --Succeed
order by mdh.[time]
```
|
220,347 |
<p>I've got a somewhat primitive framework I've been using for most of my projects, but a general design issue came to mind that I haven't been able to work out yet. For a given application, should I separate the application-specific class structure from the framework's structure, or is building on top of the framework not such a bad thing?</p>
<p>For example, say I had a framework with a base Controller class and extended it for a given part of my application. Which arrangement makes the most sense, and why?</p>
<p><strong>Class Structure A:</strong></p>
<ul>
<li>Intuitive, easy to find source files when debugging.</li>
<li>File naming/directory structure mirrors class heirarchy.</li>
</ul>
<pre>
- Framework_Control "Framework\Control.php"
- Framework_Control_Index "Framework\Control\Index.php"
- Framework_Control_Home "Framework\Control\Home.php"
- Framework_Control_Contact "Framework\Control\Contact.php"
- Framework_Control_About "Framework\Control\About.php"
</pre>
<p><strong>Class Structure B:</strong></p>
<ul>
<li>Keeps framework modular and easily to replace/update.</li>
<li>Adds some complexity to directory structure, directory/file naming no longer follows class heirarchy all the time.</li>
</ul>
<pre>
- Framework_Control "Framework\Control.php"
- Application_Control_Index "Application\Control\Index.php"
- Application_Control_Home "Application\Control\Home.php"
- Application_Control_Contact "Application\Control\Contact.php"
- Application_Control_About "Application\Control\About.php"
</pre>
<p>I know overall it's going to come down to personal preference, but I want to make sure I weigh out all the pros and cons before I decide which way to go. It really comes down to class naming and directory structure as the actual hierarchy would remain the same in either case.</p>
|
[
{
"answer_id": 220359,
"author": "Rob Booth",
"author_id": 16445,
"author_profile": "https://Stackoverflow.com/users/16445",
"pm_score": 2,
"selected": true,
"text": "<p>What it really comes down to is what are you going to do when you update Framework\\Control.php in Application XYZ. Are you going to go back to Application ABC and make that same change? What if it's a critical bug?</p>\n\n<p>For maintainability of all of your projects I'd go with your second option.</p>\n"
},
{
"answer_id": 220516,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest that you view your source code in two different categories, external dependencies or code that is used across multiple sites and not native to any single one and native dependencies or the code that is native to the particular site that you're working on.</p>\n\n<p>It sounds like Framework/Control.php is part of a larger external dependency and should be managed as such, while the Application/Control files are all native the particular website.</p>\n\n<p>Using this differentiation in our code structure has made it much easier to reuse our in-house framework between multiple sites very easily.</p>\n\n<p>As a final thought, you might consider looking at what the major frameworks out there are doing such as Zend Framework, Symfony and others. Even though the entire framework might be more than you want the structure of the frameworks can provide a lot of insights into common, good practices that are being used by PHP developers everywhere.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
I've got a somewhat primitive framework I've been using for most of my projects, but a general design issue came to mind that I haven't been able to work out yet. For a given application, should I separate the application-specific class structure from the framework's structure, or is building on top of the framework not such a bad thing?
For example, say I had a framework with a base Controller class and extended it for a given part of my application. Which arrangement makes the most sense, and why?
**Class Structure A:**
* Intuitive, easy to find source files when debugging.
* File naming/directory structure mirrors class heirarchy.
```
- Framework_Control "Framework\Control.php"
- Framework_Control_Index "Framework\Control\Index.php"
- Framework_Control_Home "Framework\Control\Home.php"
- Framework_Control_Contact "Framework\Control\Contact.php"
- Framework_Control_About "Framework\Control\About.php"
```
**Class Structure B:**
* Keeps framework modular and easily to replace/update.
* Adds some complexity to directory structure, directory/file naming no longer follows class heirarchy all the time.
```
- Framework_Control "Framework\Control.php"
- Application_Control_Index "Application\Control\Index.php"
- Application_Control_Home "Application\Control\Home.php"
- Application_Control_Contact "Application\Control\Contact.php"
- Application_Control_About "Application\Control\About.php"
```
I know overall it's going to come down to personal preference, but I want to make sure I weigh out all the pros and cons before I decide which way to go. It really comes down to class naming and directory structure as the actual hierarchy would remain the same in either case.
|
What it really comes down to is what are you going to do when you update Framework\Control.php in Application XYZ. Are you going to go back to Application ABC and make that same change? What if it's a critical bug?
For maintainability of all of your projects I'd go with your second option.
|
220,392 |
<p>This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.</p>
<p>Here is what I'm doing:</p>
<pre><code>this.propertyTypeBindingSource.DataSource = typeof(System.Type);
/* snip */
this.nameTextBox1.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyTypeBindingSource,
"Name", true));
</code></pre>
<p>Is there some trick with binding to System.Type, is it not allowed or is there any workaround? Have no problems with binding to other types.</p>
|
[
{
"answer_id": 220425,
"author": "Evgeny",
"author_id": 26447,
"author_profile": "https://Stackoverflow.com/users/26447",
"pm_score": 3,
"selected": true,
"text": "<p>Found a workaround. Made a class </p>\n\n<pre><code>public class StubPropertyType\n{\n public StubPropertyType(Type type)\n {\n this.StubPropertyTypeName = type.Name;\n }\n\n public string StubPropertyTypeName = string.Empty;\n}\n</code></pre>\n\n<p>created a binding source</p>\n\n<pre><code>this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);\n</code></pre>\n\n<p>created an instance of the class and bound the textbox to it.</p>\n\n<pre><code>this.nameTextBox.DataBindings.Add(\n new System.Windows.Forms.Binding(\n \"Text\", \n this.propertyStubBindingSource, \n \"StubPropertyTypeName\", \n true));\n</code></pre>\n\n<p>works exactly as required.</p>\n"
},
{
"answer_id": 220901,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>Indeed, there is special treatment of Type... this approach is used in the IDE etc to configure meta-data ahead of time. If you look at IDE-generated bindings, they do things like:</p>\n\n<pre><code>bindingSource1.DataSource = typeof(MyObject);\n</code></pre>\n\n<p>saying \"when we get real data, we expect MyObject isntance(s)\"; i.e. when you ask for \"Name\", it is looking for the name property <em>on MyObject</em> - not the Name of the Type instance. This allows grids etc to obtain their metadata without having to wait for the real data; but as a consequence you can't bind to Type \"for real\".</p>\n\n<p>The System.ComponentModel code is identical between simple bindings and list bindings (give or take a currency manager), so simple bindings also inherit this behaviour. Equally, you can't bind to properties of a class that implements IList/IListSource, since this is interpreted in a special way. </p>\n\n<p>Your extra class seems a reasonable approach.</p>\n"
},
{
"answer_id": 4665356,
"author": "Siddhanath Lawand",
"author_id": 572198,
"author_profile": "https://Stackoverflow.com/users/572198",
"pm_score": 0,
"selected": false,
"text": "<p>One of the possible reason for this error is table/ Dataset do not have specified column.\nSpecially, in case of Typed DataSet make sure you have proper names in XSD matching with column names from table</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26447/"
] |
This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.
Here is what I'm doing:
```
this.propertyTypeBindingSource.DataSource = typeof(System.Type);
/* snip */
this.nameTextBox1.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyTypeBindingSource,
"Name", true));
```
Is there some trick with binding to System.Type, is it not allowed or is there any workaround? Have no problems with binding to other types.
|
Found a workaround. Made a class
```
public class StubPropertyType
{
public StubPropertyType(Type type)
{
this.StubPropertyTypeName = type.Name;
}
public string StubPropertyTypeName = string.Empty;
}
```
created a binding source
```
this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);
```
created an instance of the class and bound the textbox to it.
```
this.nameTextBox.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyStubBindingSource,
"StubPropertyTypeName",
true));
```
works exactly as required.
|
220,401 |
<p>I'm trying to create an in-process unit test for my service to client interactions using net.pipe binding. Like a good WCF service it uses FaultContractAttribute on service operations to expose possible faults <em>(wrapped exceptions)</em> to metadata. I would like to have the client and service endpoints configured thru XML <em>(App.config).</em> However, whenever a fault is thrown, it's just a CommunicationException "pipe has closed", and not the typed Fault I was expecting.</p>
<pre><code>System.ServiceModel.CommunicationException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d).
</code></pre>
<p>I tried Adding IMetadataExchange endpoint for net.pipe, but that didn't work. I also tried . Which being on Vista required me to netsh the ACL for the http endpoint. That too did not work.</p>
<p>The custom exception class:</p>
<pre><code>public class ValidationException : ApplicationException { }
</code></pre>
<p>This is the latest attempt at a config, but it pumps out <em>"The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service"</em></p>
<p>Any Links to examples or recommendations for how to get this done would be appreciated.</p>
<p></p>
<p></p>
<pre><code><system.serviceModel>
<client>
<endpoint name="Client"
contract="IService"
address="net.pipe://localhost/ServiceTest/"
binding="netNamedPipeBinding"
bindingConfiguration="netPipeBindingConfig" />
</client>
<services>
<service
name="Service"
behaviorConfiguration="ServiceFaults">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/ServiceTest/"/>
<add baseAddress="http://localhost/ServiceTest/"/>
</baseAddresses>
</host>
<endpoint
address=""
binding="netNamedPipeBinding"
bindingConfiguration="netPipeBindingConfig"
name="ServicePipe"
contract="IService" />
<endpoint
address="MEX"
binding="mexNamedPipeBinding"
bindingConfiguration="mexNetPipeBindingConfig"
name="MexUserServicePipe"
contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netNamedPipeBinding>
<binding name="netPipeBindingConfig"
closeTimeout="00:30:00"
sendTimeout="00:30:00" />
</netNamedPipeBinding>
<mexNamedPipeBinding>
<binding name="mexNetPipeBindingConfig"></binding>
</mexNamedPipeBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceFaults">
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
<behavior name="MEX">
<serviceMetadata
httpGetEnabled="true"
httpGetUrl="http://localhost/ServiceTest/MEX"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</code></pre>
<p>
</p>
|
[
{
"answer_id": 220472,
"author": "sebagomez",
"author_id": 23893,
"author_profile": "https://Stackoverflow.com/users/23893",
"pm_score": 0,
"selected": false,
"text": "<p>I got that same error a few days ago.<br>\nI solved creating my own class (MyFault) and throwing FaultException from the server and catching those in the client. MyFault has a string member wich is the Exception Message I want the client to see.</p>\n\n<p>I hope I made myself clear... I'll try to look for a nice sample and I'll post it here</p>\n"
},
{
"answer_id": 220533,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is most likely an error deserializing or serializing the request or response. Enable trace and view the log with svctraceviewer for the exact error.</p>\n\n<p>Also, make sure your fault exception is marked with [DataContract] and does not inherit and non [DataContract] classes.</p>\n"
},
{
"answer_id": 306804,
"author": "Wagner Silveira",
"author_id": 33352,
"author_profile": "https://Stackoverflow.com/users/33352",
"pm_score": 0,
"selected": false,
"text": "<p>One last thing to add. Do your operation contracts define the ServiceFault they are using?.</p>\n\n<p>My understanding is that you have to define which ServiceFaults your're using at the operation layer, and your business logic throw a FaulException where T is the ServiceFault you defined.</p>\n"
},
{
"answer_id": 368478,
"author": "Joseph DeCarlo",
"author_id": 46362,
"author_profile": "https://Stackoverflow.com/users/46362",
"pm_score": 3,
"selected": true,
"text": "<p>If the ValidationException class you describe above is the class you are using for faults, it may be the source of your problem. You should derive your fault exceptions from FaultException because it is Serializable. ApplicationException is not.</p>\n\n<p>Wagner is right, you need to decorate your operation definition with a FaultContract attribute giving it the type of your contract. You should also to decorate your FaultContract with DataContract and DataMember attributes as well.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14439/"
] |
I'm trying to create an in-process unit test for my service to client interactions using net.pipe binding. Like a good WCF service it uses FaultContractAttribute on service operations to expose possible faults *(wrapped exceptions)* to metadata. I would like to have the client and service endpoints configured thru XML *(App.config).* However, whenever a fault is thrown, it's just a CommunicationException "pipe has closed", and not the typed Fault I was expecting.
```
System.ServiceModel.CommunicationException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d).
```
I tried Adding IMetadataExchange endpoint for net.pipe, but that didn't work. I also tried . Which being on Vista required me to netsh the ACL for the http endpoint. That too did not work.
The custom exception class:
```
public class ValidationException : ApplicationException { }
```
This is the latest attempt at a config, but it pumps out *"The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service"*
Any Links to examples or recommendations for how to get this done would be appreciated.
```
<system.serviceModel>
<client>
<endpoint name="Client"
contract="IService"
address="net.pipe://localhost/ServiceTest/"
binding="netNamedPipeBinding"
bindingConfiguration="netPipeBindingConfig" />
</client>
<services>
<service
name="Service"
behaviorConfiguration="ServiceFaults">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/ServiceTest/"/>
<add baseAddress="http://localhost/ServiceTest/"/>
</baseAddresses>
</host>
<endpoint
address=""
binding="netNamedPipeBinding"
bindingConfiguration="netPipeBindingConfig"
name="ServicePipe"
contract="IService" />
<endpoint
address="MEX"
binding="mexNamedPipeBinding"
bindingConfiguration="mexNetPipeBindingConfig"
name="MexUserServicePipe"
contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netNamedPipeBinding>
<binding name="netPipeBindingConfig"
closeTimeout="00:30:00"
sendTimeout="00:30:00" />
</netNamedPipeBinding>
<mexNamedPipeBinding>
<binding name="mexNetPipeBindingConfig"></binding>
</mexNamedPipeBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceFaults">
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
<behavior name="MEX">
<serviceMetadata
httpGetEnabled="true"
httpGetUrl="http://localhost/ServiceTest/MEX"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
|
If the ValidationException class you describe above is the class you are using for faults, it may be the source of your problem. You should derive your fault exceptions from FaultException because it is Serializable. ApplicationException is not.
Wagner is right, you need to decorate your operation definition with a FaultContract attribute giving it the type of your contract. You should also to decorate your FaultContract with DataContract and DataMember attributes as well.
|
220,405 |
<p>I have a web application that I'm writing (C#, MSSQL) and I need to store the timestamp when a record is stored in the system. Normally, I would just do this with SQL and the DATETIME function. However, the server is located in a different time zone than our company is located... AND we may change to another server in completely different time zone. The hosting company will not change the server time to match our local time zone. (Not that I blame them, but it was one thing I tried.)</p>
<p>So, my question is, what is the best way to store the date/time of the record update and what is the best way to present that date/time back to the user in our local time zone?</p>
<p>I want the least messy way of doing this, so a combo of C# and SQL would be fine as long as the solution is easy to implement. (My normal style is to do more work in stored procedures and less in C#, if that matters.)</p>
<p>Can you show me some sample code? Thanks!</p>
|
[
{
"answer_id": 220407,
"author": "sebagomez",
"author_id": 23893,
"author_profile": "https://Stackoverflow.com/users/23893",
"pm_score": 3,
"selected": false,
"text": "<p>Save UTC times in your database and localize those times every time you wanna show them to a user</p>\n"
},
{
"answer_id": 220418,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Store it as UTC time and then preform the time zone calculation on the client end\nin C# use .ToUniversalTime() on the DateTime object to get the UTC time, store that on the server and then use .ToLocalTime() to convert it back.</p>\n"
},
{
"answer_id": 220706,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 5,
"selected": true,
"text": "<p><strong><em>always store DATETIME data in Universal Time Coordinated (UTC aka GMT)</em></strong></p>\n\n<ul>\n<li>this avoids all timezone issues</li>\n<li>this avoids daylight-savings-time issues</li>\n<li>this allows simple date math to always work</li>\n<li>this allows transactions in different time zones to stay in synch</li>\n<li>this allows you to move the data to a different server in a different time zone and not screw everything up</li>\n<li>etc. \"Universal\" time, make sense?</li>\n</ul>\n\n<p>C# DateTime provides DateTime.UtcNow and ToLocalTime(), SQL provides GETUTCDATE(). Here's a SQL function to convert UTC to local time -</p>\n\n<pre><code>-- convert UTC to local time\ncreate FUNCTION [dbo].[udfUtcToLocalTime]\n(\n @gmt datetime\n)\nRETURNS datetime\nAS\nBEGIN\n DECLARE @dt datetime\n SELECT \n @dt = dateadd(millisecond,datediff(millisecond,getutcdate(), getdate()),@gmt)\n RETURN @dt\nEND\n</code></pre>\n\n<p>example:</p>\n\n<pre><code>SELECT dbo.udfUtcToLocalTime(someDateTimeField)\nFROM someTable\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20848/"
] |
I have a web application that I'm writing (C#, MSSQL) and I need to store the timestamp when a record is stored in the system. Normally, I would just do this with SQL and the DATETIME function. However, the server is located in a different time zone than our company is located... AND we may change to another server in completely different time zone. The hosting company will not change the server time to match our local time zone. (Not that I blame them, but it was one thing I tried.)
So, my question is, what is the best way to store the date/time of the record update and what is the best way to present that date/time back to the user in our local time zone?
I want the least messy way of doing this, so a combo of C# and SQL would be fine as long as the solution is easy to implement. (My normal style is to do more work in stored procedures and less in C#, if that matters.)
Can you show me some sample code? Thanks!
|
***always store DATETIME data in Universal Time Coordinated (UTC aka GMT)***
* this avoids all timezone issues
* this avoids daylight-savings-time issues
* this allows simple date math to always work
* this allows transactions in different time zones to stay in synch
* this allows you to move the data to a different server in a different time zone and not screw everything up
* etc. "Universal" time, make sense?
C# DateTime provides DateTime.UtcNow and ToLocalTime(), SQL provides GETUTCDATE(). Here's a SQL function to convert UTC to local time -
```
-- convert UTC to local time
create FUNCTION [dbo].[udfUtcToLocalTime]
(
@gmt datetime
)
RETURNS datetime
AS
BEGIN
DECLARE @dt datetime
SELECT
@dt = dateadd(millisecond,datediff(millisecond,getutcdate(), getdate()),@gmt)
RETURN @dt
END
```
example:
```
SELECT dbo.udfUtcToLocalTime(someDateTimeField)
FROM someTable
```
|
220,432 |
<p>Say I have an array of strings in a php array called $foo with a few hundred entries, and I have a MySQL table 'people' that has a field named 'name' with a few thousand entries. What is an efficient way to find out which strings in $foo aren't a 'name' in an entry in 'people' without submitting a query for every string in $foo? </p>
<p>So I want to find out what strings in $foo have not already been entered in 'people.'</p>
<p>Note that it is clear that all of the data will have to be on one box at one point. The goal would be doing this at the same time minimizing the number of queries and the amount of php processing.</p>
|
[
{
"answer_id": 220441,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 1,
"selected": false,
"text": "<p>I'd put your $foo data in another table and do a LEFT OUTER JOIN with your names table. Otherwise, there aren't a lot of great ways to do this that don't involve iteration at some point.</p>\n"
},
{
"answer_id": 220457,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure there is a more efficient way to do this other than to submit all the strings to the database.</p>\n\n<p>Basically there are two options: get a list of all the strings in MySQL and pull them into PHP and do the comparisons, or send the list of all the strings to the MySQL server and let it do the comparisons. MySQL is going to do the comparisons much faster than PHP, unless the list in the database is a great deal smaller than the list in PHP.</p>\n\n<p>You can either create a temporary table, but either way your pushing all the data to the database.</p>\n"
},
{
"answer_id": 220476,
"author": "Andrew ",
"author_id": 22586,
"author_profile": "https://Stackoverflow.com/users/22586",
"pm_score": 0,
"selected": false,
"text": "<p>For a few hundred entries, just use array_diff() or array_diff_assoc()</p>\n"
},
{
"answer_id": 220497,
"author": "jakber",
"author_id": 29812,
"author_profile": "https://Stackoverflow.com/users/29812",
"pm_score": 1,
"selected": false,
"text": "<p>The best I can come up with without using a temporary table is:</p>\n\n<pre><code> $list = join(\",\", $foo);\n\n// fetch all rows of the result of \n// \"SELECT name FROM people WHERE name IN($list)\" \n// into an array $result\n\n$missing_names = array_diff($foo, $result);\n</code></pre>\n\n<p>Note that if $foo contains user input it would have to be escaped first.</p>\n"
},
{
"answer_id": 220509,
"author": "cole",
"author_id": 910,
"author_profile": "https://Stackoverflow.com/users/910",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$query = 'SELECT name FROM table WHERE name != '.implode(' OR name != '. $foo);\n</code></pre>\n\n<p>Yeash, that doesn't look like it would scale well at all.</p>\n"
},
{
"answer_id": 220599,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": true,
"text": "<pre><code>CREATE TEMPORARY TABLE PhpArray (name varchar(50));\n\n-- you can probably do this more efficiently\nINSERT INTO PhpArray VALUES ($foo[0]), ($foo[1]), ...;\n\nSELECT People.*\nFROM People\n LEFT OUTER JOIN PhpArray USING (name)\nWHERE PhpArray.name IS NULL;\n</code></pre>\n"
},
{
"answer_id": 221007,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>What about the following:</p>\n\n<ol>\n<li>Get the list of names that are already in the db, using something like: \n<code>SELECT name FROM people WHERE name IN (imploded list of names)</code></li>\n<li>Insert each item from the return of <code>array_diff()</code></li>\n</ol>\n\n<p>If you want to do it completely in SQL:</p>\n\n<ol>\n<li>Create a temp table with every name in the PHP array.</li>\n<li>Perform a query to populate a second temp table that will only include the new names.</li>\n<li>Do an <code>INSERT ... SELECT</code> from the second temp table into the people table.</li>\n</ol>\n\n<p>Neither will be terribly fast, although the second option might be slightly faster.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393/"
] |
Say I have an array of strings in a php array called $foo with a few hundred entries, and I have a MySQL table 'people' that has a field named 'name' with a few thousand entries. What is an efficient way to find out which strings in $foo aren't a 'name' in an entry in 'people' without submitting a query for every string in $foo?
So I want to find out what strings in $foo have not already been entered in 'people.'
Note that it is clear that all of the data will have to be on one box at one point. The goal would be doing this at the same time minimizing the number of queries and the amount of php processing.
|
```
CREATE TEMPORARY TABLE PhpArray (name varchar(50));
-- you can probably do this more efficiently
INSERT INTO PhpArray VALUES ($foo[0]), ($foo[1]), ...;
SELECT People.*
FROM People
LEFT OUTER JOIN PhpArray USING (name)
WHERE PhpArray.name IS NULL;
```
|
220,437 |
<p>According to the <a href="http://ca3.php.net/manual/en/function.get-magic-quotes-gpc.php" rel="noreferrer">PHP manual</a>, in order to make code more portable, they recommend using something like the following for escaping data:</p>
<pre><code>if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
</code></pre>
<p>I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().</p>
|
[
{
"answer_id": 220449,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 6,
"selected": true,
"text": "<p>Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.</p>\n\n<p>The PHP <a href=\"http://php.net/magic_quotes\" rel=\"nofollow noreferrer\">man page on magic quotes</a> agrees:</p>\n\n<blockquote>\n <p>\"This feature has been DEPRECATED as\n of PHP 5.3.0 and REMOVED as of PHP\n 5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a\n process that automagically escapes\n incoming data to the PHP script. It's\n preferred to code with magic quotes\n off and to instead escape the data at\n runtime, as needed.\"</p>\n</blockquote>\n"
},
{
"answer_id": 220455,
"author": "Devin Ceartas",
"author_id": 14897,
"author_profile": "https://Stackoverflow.com/users/14897",
"pm_score": 1,
"selected": false,
"text": "<p>Right, it's not the best way to do it and not the most secure. Escaping is best done in relation to what you are escaping for. If it is to store in a mysql database, use mysql_real_escape_string which takes into account other locales, character sets. For HTML, htmlentities. For use in code, escapeshellcmd, escapeshellarg. Yes, you probably need to stirpslashes first if magic quotes is on. But best not to count on it or use it. </p>\n"
},
{
"answer_id": 220490,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following code in the header file of my website to reverse the effects of magic_quotes:</p>\n\n<pre><code><?php\n\n// Strips slashes recursively only up to 3 levels to prevent attackers from\n// causing a stack overflow error.\nfunction stripslashes_array(&$array, $iterations=0) {\n if ($iterations < 3) {\n foreach ($array as $key => $value) {\n if (is_array($value)) {\n stripslashes_array($array[$key], $iterations + 1);\n } else {\n $array[$key] = stripslashes($array[$key]);\n }\n }\n }\n}\n\nif (get_magic_quotes_gpc()) {\n stripslashes_array($_GET);\n stripslashes_array($_POST);\n stripslashes_array($_COOKIE);\n}\n\n?>\n</code></pre>\n\n<p>Then I can write the rest of my code as if magic_quotes never existed.</p>\n"
},
{
"answer_id": 220993,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding using a database specific escaping function, you pretty much need to. I have found just using <code>addslashes()</code> to fail in rare cases with MySQL. You can write a function to escape which determines which DB you are using and then use the approriate escape function.</p>\n"
},
{
"answer_id": 221157,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 2,
"selected": false,
"text": "<p>\"I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string()\"</p>\n\n<p>Then use something like <a href=\"http://uk.php.net/pdo\" rel=\"nofollow noreferrer\">PDO</a>. But you have to reverse the damage done by magic quotes anyway.</p>\n"
},
{
"answer_id": 221180,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 4,
"selected": false,
"text": "<p>Magic quotes were a design error. Their use is incompatible with retainnig your sanity.</p>\n\n<p>I prefer:</p>\n\n<pre><code>if (get_magic_quotes_gpc()) {\n throw new Exception(\"Turn magic quotes off now!\");\n}\n</code></pre>\n\n<p>Don't write code for compatibility with inherently broken setups. Instead defend aginst their use by having your code <a href=\"http://en.wikipedia.org/wiki/Fail-fast\" rel=\"noreferrer\">FAIL FAST</a>.</p>\n"
},
{
"answer_id": 325534,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may try this: </p>\n\n<pre><code>if (get_magic_quotes_gpc()) { \n $_REQUEST = array_map('stripslashes', $_REQUEST); \n $_GET = array_map('stripslashes', $_GET);\n $_POST = array_map('stripslashes', $_POST);\n $_GET = array_map('stripslashes', $_COOKIES);\n\n }\n</code></pre>\n"
},
{
"answer_id": 441737,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>\"I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string()\"</p>\n\n<p>Also addslashes can be tricked as well check out this post:</p>\n\n<p><a href=\"http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string\" rel=\"nofollow noreferrer\">http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string</a></p>\n"
},
{
"answer_id": 441790,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Put a requirement of PHP 5.2 or higher on your code and use the <a href=\"http://php.net/filter\" rel=\"nofollow noreferrer\">filter API</a>. The <code>filter_*</code> functions access the raw input data directly (they don't ever touch <code>$_POST</code> etc.) so they're completely unaffected by <code>magic_quotes_gpc</code>.</p>\n\n<p>Then this example:</p>\n\n<pre><code>if (!get_magic_quotes_gpc()) {\n $lastname = addslashes($_POST['lastname']);\n} else {\n $lastname = $_POST['lastname'];\n}\n</code></pre>\n\n<p>Can become this:</p>\n\n<pre><code>$lastname = filter_input(INPUT_POST, 'lastname');\n</code></pre>\n"
},
{
"answer_id": 441832,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 0,
"selected": false,
"text": "<p>Your sample code is backwards, you should be doing the following:</p>\n\n<pre><code>if (get_magic_quotes_gpc()) {\n $lastname = stripslashes($_POST['lastname']);\n} else {\n $lastname = $_POST['lastname'];\n}\n</code></pre>\n\n<p>Note that this leaves your input data in a 'raw' state exactly as the user typed it - no extra backslashes and potentially loaded with SQL Injection and XSRF attacks - and that's exactly what you want. Then, you make sure you <strong>always</strong> use one of the following:</p>\n\n<ul>\n<li>When <code>echo</code>ing the variable into HTML, wrap it in <code>htmlentities()</code></li>\n<li>When putting it into mysql, use prepared statements or else <code>mysql_real_escape_string()</code> as a minimum.</li>\n<li>When <code>echo</code>ing the variable into Javascritpt code, use <code>json_encode()</code></li>\n</ul>\n\n<p>Joel Spolsky has some good starting advice in <a href=\"http://joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Making Wrong Code Look Wrong</a></p>\n"
},
{
"answer_id": 2688559,
"author": "gnarf",
"author_id": 91914,
"author_profile": "https://Stackoverflow.com/users/91914",
"pm_score": 0,
"selected": false,
"text": "<p>Just found this over on the <a href=\"http://us2.php.net/manual/en/function.get-magic-quotes-gpc.php#95697\" rel=\"nofollow noreferrer\">PHP manual pages</a>, looks like a pretty clever way to strip em (deals with keys and values...):</p>\n\n<pre><code>if (get_magic_quotes_gpc())\n{\n $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);\n $_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);\n $_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);\n $_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);\n ini_set('magic_quotes_gpc', 0);\n}\n</code></pre>\n"
},
{
"answer_id": 44902042,
"author": "Nick Tsai",
"author_id": 4767939,
"author_profile": "https://Stackoverflow.com/users/4767939",
"pm_score": 0,
"selected": false,
"text": "<p>Prepared statements of <a href=\"http://php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow noreferrer\">PDO</a> and <a href=\"http://php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow noreferrer\">Mysqli</a> are the better way to prevent SQL injection.</p>\n\n<p>But if you are migrating a legacy code which is base on Magic Quotes for every SQL queries, you can refer <a href=\"https://github.com/yidas/php-magic-quotes\" rel=\"nofollow noreferrer\">yidas/php-magic-quotes</a> for implementing Magic Quotes on the environment with PHP 5.4 above version.</p>\n\n<blockquote>\n <p><a href=\"https://github.com/yidas/php-magic-quotes\" rel=\"nofollow noreferrer\">https://github.com/yidas/php-magic-quotes</a></p>\n</blockquote>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
According to the [PHP manual](http://ca3.php.net/manual/en/function.get-magic-quotes-gpc.php), in order to make code more portable, they recommend using something like the following for escaping data:
```
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
```
I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql\_real\_escape\_string().
|
Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $\_GET/$\_POST/$\_COOKIES/$\_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.
The PHP [man page on magic quotes](http://php.net/magic_quotes) agrees:
>
> "This feature has been DEPRECATED as
> of PHP 5.3.0 and REMOVED as of PHP
> 5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a
> process that automagically escapes
> incoming data to the PHP script. It's
> preferred to code with magic quotes
> off and to instead escape the data at
> runtime, as needed."
>
>
>
|
220,445 |
<p>How would I be able to programmatically search and replace some text in a large number of PDF files? I would like to remove a URL that has been added to a set of files. I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains. I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.</p>
|
[
{
"answer_id": 220791,
"author": "Chris Dolan",
"author_id": 14783,
"author_profile": "https://Stackoverflow.com/users/14783",
"pm_score": 5,
"selected": true,
"text": "<p>Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file. That said, <a href=\"http://search.cpan.org/dist/CAM-PDF\" rel=\"nofollow noreferrer\">CAM::PDF</a> has some search-replace capabilities and heuristics. Give <a href=\"http://search.cpan.org/dist/CAM-PDF/bin/changepagestring.pl\" rel=\"nofollow noreferrer\">changepagestring.pl</a> a try and see if it works on your PDFs.</p>\n<p>To install:</p>\n<pre><code> $ cpan install CAM::PDF\n # start a new terminal if this is your first cpan module\n $ changepagestring.pl input.pdf oldtext newtext output.pdf\n</code></pre>\n"
},
{
"answer_id": 920471,
"author": "Larry",
"author_id": 113697,
"author_profile": "https://Stackoverflow.com/users/113697",
"pm_score": 3,
"selected": false,
"text": "<p>I have also become desperate. After 10 PDF Editor installations which all cost money, and no success:</p>\n<p>pdftk + editor suffice:</p>\n<p><strong>Replace Text in PDF Files</strong></p>\n<ul>\n<li><p>Use pdftk to uncompress PDF page streams</p>\n<p>pdftk original.pdf output original.uncompressed.pdf uncompress</p>\n</li>\n<li><p>Replace the text (sometimes this\nworks, sometimes it doesn't) within original.uncompressed.pdf</p>\n</li>\n<li><p>Repair the modified (and now broken)\nPDF</p>\n<p>pdftk original.uncompressed.pdf output original.uncompressed.fixed.pdf</p>\n</li>\n</ul>\n<blockquote>\n<p>(from Joel Dare)</p>\n</blockquote>\n"
},
{
"answer_id": 3355762,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the 'redaction' feature in Adobe Acrobat Pro to find & replace all references in a single document in one step...not sure if it can be automated to multiple steps.</p>\n\n<p><a href=\"http://help.adobe.com/en_US/Acrobat/9.0/Professional/WS5E28D332-9FF7-4569-AFAD-79AD60092D4D.w.html\" rel=\"nofollow noreferrer\">http://help.adobe.com/en_US/Acrobat/9.0/Professional/WS5E28D332-9FF7-4569-AFAD-79AD60092D4D.w.html</a></p>\n"
},
{
"answer_id": 4622448,
"author": "stirhale",
"author_id": 566409,
"author_profile": "https://Stackoverflow.com/users/566409",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure I would want to do all the work to write the code to modify your 1300 files when there is a program that can do it for you. The other day, I used the Professional version of Infix to batch modify almost 100 files using its \"Find and Replace in Files\" feature. It works great. I have evaluated other programs in hopes finding an find and replace functionality similar to Microsoft Word. Infix was the only one I found that can do it. Check out: <a href=\"http://www.iceni.com/infix-pro.htm\" rel=\"nofollow\">http://www.iceni.com/infix-pro.htm</a></p>\n"
},
{
"answer_id": 8104870,
"author": "sobusola",
"author_id": 1043183,
"author_profile": "https://Stackoverflow.com/users/1043183",
"pm_score": 1,
"selected": false,
"text": "<p>I just finished trying out infix for a text that is comprised of text ladened with diacritics with the hope of generating another text where characters with double and composed diacritics are replaced by alternate with single diacritics. Infix is such definitely a good solution for someone who does not care for the trouble of understanding the working of programmatic solutions. All the request changes were effected. Still need to understand how to effect reflow of words that change the layout of text.</p>\n"
},
{
"answer_id": 13934716,
"author": "d-b",
"author_id": 1802826,
"author_profile": "https://Stackoverflow.com/users/1802826",
"pm_score": 1,
"selected": false,
"text": "<p>This is just half a solution but I used Touch up combined with AppleScript's support for sending keystrokes to replace a string in thousands of table cells. Depending on how your pages are layout it could work for you. In my case I had to manually insert the cursor in the beginning of every table (tens of tables - quite manageable for a manual process) but after that i replaced thousands of cells automatically.</p>\n"
},
{
"answer_id": 27953608,
"author": "Dimitar",
"author_id": 75715,
"author_profile": "https://Stackoverflow.com/users/75715",
"pm_score": 1,
"selected": false,
"text": "<p>The question is for a programmatic solution, but I will still share this free online tool which helped me mass replace text in some PDF files:</p>\n\n<p><a href=\"http://www.pdfdu.com/pdf-replace-text.aspx\" rel=\"nofollow\">http://www.pdfdu.com/pdf-replace-text.aspx</a></p>\n\n<p>I did not notice any ads or other modifications in the resulting PDF files after replacing the text.</p>\n\n<p>I was not able to make the changes locally with the software I tried. I think the main problem was that I was missing the font used in the PDF and it did not work properly, even with Acrobat Pro. The online tool did not complain and produced a great result.</p>\n"
},
{
"answer_id": 45092840,
"author": "smith",
"author_id": 8304987,
"author_profile": "https://Stackoverflow.com/users/8304987",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest you may use VeryPDF PDF Text Replacer Command Line software to batch replace text in PDF pages, you can run pdftr.exe to replace text in PDF pages easily, for example,</p>\n\n<p>pdftr.exe -contentreplace \"My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -searchandoverlaytext \"My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -searchandoverlaytext \"My Name=>D:\\temp\\myname.png*20*20\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -pagerange 1-3 -contentreplace \"Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -searchtext \"string\" C:\\in.pdf</p>\n\n<p>pdftr.exe -pagerange 1 -searchtext \"string\" C:\\in.pdf</p>\n\n<p>pdftr.exe -pagerange 1 -searchandoverlaytext \"Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -overlaytextfontname \"Arial\" -overlaytextcolor FF0000 -overlaybgcolor 00FF00 -searchandoverlaytext \"Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -opw 123 -upw 456 -contentreplace \"Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name\" D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -searchandoverlaytext \"PDFcamp Printer=>VeryPDF Printer\" -overlaytextfontsize 8 D:\\in.pdf D:\\out.pdf</p>\n\n<p>pdftr.exe -searchandoverlaytext \"PDFcamp Printer=>VeryPDF Printer\" -overlaytextfontsize 80% D:\\in.pdf D:\\out.pdf</p>\n"
},
{
"answer_id": 67439448,
"author": "Tilal Ahmad",
"author_id": 1368028,
"author_profile": "https://Stackoverflow.com/users/1368028",
"pm_score": -1,
"selected": false,
"text": "<p>Although it is quite an old thread. Just wanted to share a Node.js package option to search and replace text in PDF: <a href=\"https://products.aspose.cloud/pdf/nodejs\" rel=\"nofollow noreferrer\">Aspose.PDF Cloud SDK for Node.js</a>. It is paid product but it provides 150 free monthly API calls.</p>\n<pre><code>\nconst { PdfApi } = require("asposepdfcloud");\nconst { TextReplaceListRequest }= require("asposepdfcloud/src/models/textReplaceListRequest");\nconst { TextReplace }= require("asposepdfcloud/src/models/textReplace");\n\n// Get Client ID and Client Secret from https://dashboard.aspose.cloud/\npdfApi = new PdfApi("xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxx");\nvar fs = require('fs');\n\nconst name = "02_pages.pdf";\nconst remoteTempFolder = "Temp";\n//const localTestDataFolder = "C:\\\\Temp";\n//const path = remoteTempFolder + "\\\\" + name;\n//const outputFile= "Replace_output.pdf";\n\n\n// Upload File\n//pdfApi.uploadFile(path, fs.readFileSync(localTestDataFolder + "\\\\" + name)).then((result) => { \n// console.log("Uploaded File"); \n// }).catch(function(err) {\n // Deal with an error\n// console.log(err);\n//});\n \nconst textReplace= new TextReplace();\n textReplace.oldValue= "origami"; \n textReplace.newValue= "aspose";\n textReplace.regex= false;\n\nconst textReplace1= new TextReplace();\n textReplace1.oldValue= "candy"; \n textReplace1.newValue= "biscuit";\n textReplace1.regex= false;\n \nconst trr = new TextReplaceListRequest();\n trr.textReplaces = [textReplace,textReplace1];\n\n\n// Replace text\npdfApi.postDocumentTextReplace(name, trr, null, remoteTempFolder).then((result) => { \n console.log(result.body.code); \n}).catch(function(err) {\n // Deal with an error\n console.log(err);\n});\n\n//Download file\n//const outputPath = "C:/Temp/" + outputFile;\n\n//pdfApi.downloadFile(path).then((result) => { \n// fs.writeFileSync(outputPath, result.body);\n// console.log("File Downloaded"); \n//}).catch(function(err) {\n // Deal with an error\n// console.log(err);\n//});\n</code></pre>\n"
},
{
"answer_id": 67932076,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 0,
"selected": false,
"text": "<p>It appears that even with uncompressed pdf's, text is sometimes formatted funky. This makes "normal" text replacement, a la <code>sed</code>, not work or not be trivial.</p>\n<p>I couldn't find anything that seemed to work with <a href=\"https://stackoverflow.com/a/66282749/32453\">glyph spacing offsets</a>, i.e. text that looks like this (which seems very common in pdf's), in this example, the word "Other information" is stored like this:</p>\n<pre><code> [(O)-16(ther i)-20(nformati)-11(on )]TJ\n</code></pre>\n<p>I have attempted to write a tool that satisfies this myself. It works OK for common use cases. Check it out <a href=\"https://github.com/rdp/replace-text-pdf\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>First uncompress your pdf, then cd to the checked out git code and:</p>\n<p>Syntax</p>\n<pre><code> $ crystal replaceinpdf.cr input_filename.pdf "something you want replaced" "what you want it replaced with" output.pdf\n</code></pre>\n<p>Enjoy!</p>\n"
},
{
"answer_id": 71492892,
"author": "Ahmet Firat Keler",
"author_id": 14999599,
"author_profile": "https://Stackoverflow.com/users/14999599",
"pm_score": 0,
"selected": false,
"text": "<p>This library has an extensive support. Check it out.</p>\n<p><a href=\"https://pdf-lib.js.org/\" rel=\"nofollow noreferrer\">PDF-LIB</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363015/"
] |
How would I be able to programmatically search and replace some text in a large number of PDF files? I would like to remove a URL that has been added to a set of files. I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains. I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.
|
Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file. That said, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF) has some search-replace capabilities and heuristics. Give [changepagestring.pl](http://search.cpan.org/dist/CAM-PDF/bin/changepagestring.pl) a try and see if it works on your PDFs.
To install:
```
$ cpan install CAM::PDF
# start a new terminal if this is your first cpan module
$ changepagestring.pl input.pdf oldtext newtext output.pdf
```
|
220,465 |
<p>I have an application which I have made a 256 x 256 Windows Vista icon for.</p>
<p>I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form.</p>
<p>I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection.</p>
<p>I am not sure if this is even possible in Windows XP and may need Windows Vista APIs</p>
|
[
{
"answer_id": 220474,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 2,
"selected": false,
"text": "<p>Found info <a href=\"http://www.geekpedia.com/tutorial219_Extracting-Icons-from-Files.html\" rel=\"nofollow noreferrer\">here</a>. To get the large Vista icon, you need to use Shell32's SHGetFileInfo method. I've copied the relevant text below, of course you'll want to replace the filename variable with \"Assembly.GetExecutingAssembly().Location\".</p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>A bunch of constants we will use in the call to SHGetFileInfo() to specify the size of the icon we wish to retrieve:</p>\n\n<pre><code>// Constants that we need in the function call\nprivate const int SHGFI_ICON = 0x100;\nprivate const int SHGFI_SMALLICON = 0x1;\nprivate const int SHGFI_LARGEICON = 0x0;\n</code></pre>\n\n<p>The SHFILEINFO structure is very important as it will be our handle to various file information, among which is the graphic icon. </p>\n\n<pre><code>// This structure will contain information about the file\npublic struct SHFILEINFO\n{\n // Handle to the icon representing the file\n public IntPtr hIcon;\n // Index of the icon within the image list\n public int iIcon;\n // Various attributes of the file\n public uint dwAttributes;\n // Path to the file\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]\n public string szDisplayName;\n // File type\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]\n public string szTypeName;\n};\n</code></pre>\n\n<p>The final preparation for the unmanaged code is to define the signature of SHGetFileInfo, which is located inside the popular Shell32.dll: </p>\n\n<pre><code>// The signature of SHGetFileInfo (located in Shell32.dll)\n[DllImport(\"Shell32.dll\")]\npublic static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);\n</code></pre>\n\n<p>Now that we have everything prepared, it's time to make the call to the function and display the icon that we retrieved. The object that will be retrieved is an Icon type (System.Drawing.Icon) but we want to display it in a PictureBox so we'll convert the Icon to a Bitmap using the ToBitmap() method. </p>\n\n<p>But first of all there are 3 controls you need to add to the form, a Button btnExtract that has \"Extract Icon\" for its Text property, picIconSmall which is a PictureBox and a picIconLarge which is also a PictureBox. That's because we will get two icons sizes. Now double click btnExtract in Visual Studio's Design view and you'll get to its Click event. Inside it is the rest of the code:</p>\n\n<pre><code>private void btnExtract_Click(object sender, EventArgs e)\n{\n // Will store a handle to the small icon\n IntPtr hImgSmall;\n // Will store a handle to the large icon\n IntPtr hImgLarge;\n\n SHFILEINFO shinfo = new SHFILEINFO();\n\n // Open the file that we wish to extract the icon from\n if(openFile.ShowDialog() == DialogResult.OK)\n {\n // Store the file name\n string FileName = openFile.FileName;\n // Sore the icon in this myIcon object\n System.Drawing.Icon myIcon;\n\n // Get a handle to the small icon\n hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);\n // Get the small icon from the handle\n myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);\n // Display the small icon\n picIconSmall.Image = myIcon.ToBitmap();\n\n // Get a handle to the large icon\n hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);\n // Get the large icon from the handle\n myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);\n // Display the large icon\n picIconLarge.Image = myIcon.ToBitmap();\n\n }\n}\n</code></pre>\n\n<p>UPDATE: found even more info <a href=\"http://support.microsoft.com/kb/319350\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 220558,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at the Windows <a href=\"http://msdn.microsoft.com/en-us/library/ms674654(VS.85).aspx\" rel=\"nofollow noreferrer\">icon functions</a> that are available. There's also an <a href=\"http://msdn.microsoft.com/en-us/library/ms648050(VS.85).aspx\" rel=\"nofollow noreferrer\">overview</a> that mentions querying for different icon sizes. There's a <a href=\"http://www.dreamincode.net/forums/showtopic60140.htm\" rel=\"nofollow noreferrer\">Dream.In.Code</a> forum thread for using the APIs in C# as well as a <a href=\"http://www.pinvoke.net/default.aspx/shell32.ExtractIconEx\" rel=\"nofollow noreferrer\">Pinvoke.net reference</a>. </p>\n"
},
{
"answer_id": 220688,
"author": "Damien",
"author_id": 29823,
"author_profile": "https://Stackoverflow.com/users/29823",
"pm_score": 2,
"selected": false,
"text": "<p>None of the above answers handle Vista Icons - only small (32x32) and large (48x48) </p>\n\n<p>There is a library that handles Vista Icons <a href=\"http://www.codeproject.com/KB/cs/IconLib.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>...it looks quite complicated due to the dual-png alpha channel format.</p>\n\n<p>I will try to make a concise answer in vb .net but it may take some time.</p>\n"
},
{
"answer_id": 1945764,
"author": "SLA80",
"author_id": 228365,
"author_profile": "https://Stackoverflow.com/users/228365",
"pm_score": 4,
"selected": true,
"text": "<p>Today, I made a very nice function for <strong>extracting the 256x256 Bitmaps from Vista icons</strong>. </p>\n\n<p>Like you, Nathan W, I use it to display the large icon as a Bitmap in \"About\" box. For example, this code gets Vista icon as PNG image, and displays it in a 256x256 PictureBox:</p>\n\n<pre><code>picboxAppLogo.Image = ExtractVistaIcon(myIcon);\n</code></pre>\n\n<p>This function takes Icon object as a parameter. So, you can use it with any icons - <strong>from resources</strong>, from files, from streams, and so on. (Read below about extracting EXE icon).</p>\n\n<p>It runs on <strong>any OS</strong>, because it does <strong>not</strong> use any Win32 API, it is <strong>100% managed code</strong> :-)</p>\n\n<pre><code>// Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx\n// And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx\n\nBitmap ExtractVistaIcon(Icon icoIcon)\n{\n Bitmap bmpPngExtracted = null;\n try\n {\n byte[] srcBuf = null;\n using (System.IO.MemoryStream stream = new System.IO.MemoryStream())\n { icoIcon.Save(stream); srcBuf = stream.ToArray(); }\n const int SizeICONDIR = 6;\n const int SizeICONDIRENTRY = 16;\n int iCount = BitConverter.ToInt16(srcBuf, 4);\n for (int iIndex=0; iIndex<iCount; iIndex++)\n {\n int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex];\n int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1];\n int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6);\n if (iWidth == 0 && iHeight == 0 && iBitCount == 32)\n {\n int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8);\n int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12);\n System.IO.MemoryStream destStream = new System.IO.MemoryStream();\n System.IO.BinaryWriter writer = new System.IO.BinaryWriter(destStream);\n writer.Write(srcBuf, iImageOffset, iImageSize);\n destStream.Seek(0, System.IO.SeekOrigin.Begin);\n bmpPngExtracted = new Bitmap(destStream); // This is PNG! :)\n break;\n }\n }\n }\n catch { return null; }\n return bmpPngExtracted;\n}\n</code></pre>\n\n<p><strong>IMPORTANT!</strong> If you want to load this icon directly from EXE file, then you <strong>CAN'T</strong> use <em>Icon.ExtractAssociatedIcon(Application.ExecutablePath)</em> as a parameter, because .NET function ExtractAssociatedIcon() is so stupid, it extracts ONLY 32x32 icon!</p>\n\n<p>Instead, you better use the whole <strong>IconExtractor</strong> class, created by Tsuda Kageyu (<a href=\"http://www.codeproject.com/KB/cs/IconExtractor.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/IconExtractor.aspx</a>). You can slightly simplify this class, to make it smaller. Use <strong>IconExtractor</strong> this way:</p>\n\n<pre><code>// Getting FILL icon set from EXE, and extracting 256x256 version for logo...\nusing (TKageyu.Utils.IconExtractor IconEx = new TKageyu.Utils.IconExtractor(Application.ExecutablePath))\n{\n Icon icoAppIcon = IconEx.GetIcon(0); // Because standard System.Drawing.Icon.ExtractAssociatedIcon() returns ONLY 32x32.\n picboxAppLogo.Image = ExtractVistaIcon(icoAppIcon);\n}\n</code></pre>\n\n<p>Note: I'm still using my ExtractVistaIcon() function here, because I don't like how <strong>IconExtractor</strong> handles this job - first, it extracts all icon formats by using IconExtractor.SplitIcon(icoAppIcon), and then you have to know the exact 256x256 icon index to get the desired vista-icon. So, using my ExtractVistaIcon() here is much faster and simplier way :)</p>\n"
},
{
"answer_id": 9098914,
"author": "Jean-Philippe",
"author_id": 1183099,
"author_profile": "https://Stackoverflow.com/users/1183099",
"pm_score": 2,
"selected": false,
"text": "<p>Having the same problem of displaying the 256*256*32 image from an ICO file in a picture box, I found the solution from SAL80 the most efficient one (and almost working). However, the original code doesn't support images stored as BMP (the large icon is usually PNG, but not always...). </p>\n\n<p>Here is my version for future references. The code to create the bitmap is also slightly simpler :</p>\n\n<pre><code> /// <summary>\n /// Extracts the large Vista icon from a ICO file \n /// </summary>\n /// <param name=\"srcBuf\">Bytes of the ICO file</param>\n /// <returns>The large icon or null if not found</returns>\n private static Bitmap ExtractVistaIcon(byte[] srcBuf)\n {\n const int SizeIcondir = 6;\n const int SizeIcondirentry = 16;\n\n // Read image count from ICO header\n int iCount = BitConverter.ToInt16(srcBuf, 4);\n\n // Search for a large icon\n for (int iIndex = 0; iIndex < iCount; iIndex++)\n {\n // Read image information from image directory entry\n int iWidth = srcBuf[SizeIcondir + SizeIcondirentry * iIndex];\n int iHeight = srcBuf[SizeIcondir + SizeIcondirentry * iIndex + 1];\n int iBitCount = BitConverter.ToInt16(srcBuf, SizeIcondir + SizeIcondirentry * iIndex + 6);\n\n // If Vista icon\n if (iWidth == 0 && iHeight == 0 && iBitCount == 32)\n {\n // Get image data position and length from directory\n int iImageSize = BitConverter.ToInt32(srcBuf, SizeIcondir + SizeIcondirentry * iIndex + 8);\n int iImageOffset = BitConverter.ToInt32(srcBuf, SizeIcondir + SizeIcondirentry * iIndex + 12);\n\n // Check if the image has a PNG signature\n if (srcBuf[iImageOffset] == 0x89 && srcBuf[iImageOffset+1] == 0x50 && srcBuf[iImageOffset+2] == 0x4E && srcBuf[iImageOffset+3] == 0x47)\n {\n // the PNG data is stored directly in the file\n var x = new MemoryStream(srcBuf, iImageOffset, iImageSize, false, false);\n return new Bitmap(x); \n }\n\n // Else it's bitmap data with a partial bitmap header\n // Read size from partial header\n int w = BitConverter.ToInt32(srcBuf, iImageOffset + 4);\n // Create a full header\n var b = new Bitmap(w, w, PixelFormat.Format32bppArgb);\n // Copy bits into bitmap\n BitmapData bmpData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, b.PixelFormat);\n Marshal.Copy(srcBuf, iImageOffset + Marshal.SizeOf(typeof(Bitmapinfoheader)), bmpData.Scan0, b.Width*b.Height*4);\n b.UnlockBits(bmpData);\n return b;\n }\n }\n\n return null;\n }\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
I have an application which I have made a 256 x 256 Windows Vista icon for.
I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form.
I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection.
I am not sure if this is even possible in Windows XP and may need Windows Vista APIs
|
Today, I made a very nice function for **extracting the 256x256 Bitmaps from Vista icons**.
Like you, Nathan W, I use it to display the large icon as a Bitmap in "About" box. For example, this code gets Vista icon as PNG image, and displays it in a 256x256 PictureBox:
```
picboxAppLogo.Image = ExtractVistaIcon(myIcon);
```
This function takes Icon object as a parameter. So, you can use it with any icons - **from resources**, from files, from streams, and so on. (Read below about extracting EXE icon).
It runs on **any OS**, because it does **not** use any Win32 API, it is **100% managed code** :-)
```
// Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx
// And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx
Bitmap ExtractVistaIcon(Icon icoIcon)
{
Bitmap bmpPngExtracted = null;
try
{
byte[] srcBuf = null;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{ icoIcon.Save(stream); srcBuf = stream.ToArray(); }
const int SizeICONDIR = 6;
const int SizeICONDIRENTRY = 16;
int iCount = BitConverter.ToInt16(srcBuf, 4);
for (int iIndex=0; iIndex<iCount; iIndex++)
{
int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex];
int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1];
int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6);
if (iWidth == 0 && iHeight == 0 && iBitCount == 32)
{
int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8);
int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12);
System.IO.MemoryStream destStream = new System.IO.MemoryStream();
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(destStream);
writer.Write(srcBuf, iImageOffset, iImageSize);
destStream.Seek(0, System.IO.SeekOrigin.Begin);
bmpPngExtracted = new Bitmap(destStream); // This is PNG! :)
break;
}
}
}
catch { return null; }
return bmpPngExtracted;
}
```
**IMPORTANT!** If you want to load this icon directly from EXE file, then you **CAN'T** use *Icon.ExtractAssociatedIcon(Application.ExecutablePath)* as a parameter, because .NET function ExtractAssociatedIcon() is so stupid, it extracts ONLY 32x32 icon!
Instead, you better use the whole **IconExtractor** class, created by Tsuda Kageyu (<http://www.codeproject.com/KB/cs/IconExtractor.aspx>). You can slightly simplify this class, to make it smaller. Use **IconExtractor** this way:
```
// Getting FILL icon set from EXE, and extracting 256x256 version for logo...
using (TKageyu.Utils.IconExtractor IconEx = new TKageyu.Utils.IconExtractor(Application.ExecutablePath))
{
Icon icoAppIcon = IconEx.GetIcon(0); // Because standard System.Drawing.Icon.ExtractAssociatedIcon() returns ONLY 32x32.
picboxAppLogo.Image = ExtractVistaIcon(icoAppIcon);
}
```
Note: I'm still using my ExtractVistaIcon() function here, because I don't like how **IconExtractor** handles this job - first, it extracts all icon formats by using IconExtractor.SplitIcon(icoAppIcon), and then you have to know the exact 256x256 icon index to get the desired vista-icon. So, using my ExtractVistaIcon() here is much faster and simplier way :)
|
220,470 |
<p>This works, but is it the proper way to do it???</p>
<p>I have a custom server control that has an [input] box on it. I want it to kinda mimic the ASP.NET TextBox, but not completely. When the textbox is rendered i have a javascript that allows users to select values that are then placed in that input box.</p>
<p>I have a public text property on the control. In the get/set i get/set the viewstate for the control - that part is easy, but when the control is populated via the javascript, the Text get is not actually called, what is the proper way to set this exposed property using JavaScript (or even if the user just types in the box) ?</p>
<p>Edit:
In the OnInit i ensure the state is maintained by reaching into the form values.</p>
<pre><code> protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (HttpContext.Current.Request.Form["MyInputBoxValue"] != "")
{
ViewState["MyInputBoxValue"]
= HttpContext.Current.Request.Form["MyInputBoxValue"];
}
}
</code></pre>
<p>Then to get the value actually back in place in the HtmlTextWrite, i do this:</p>
<pre><code>protected override void RenderContents(HtmlTextWriter output)
{
// There is an input control here and i set its value property
// like this using the Text internal defined.
output.Write("<input value=" + Text + ">.....
}
</code></pre>
<p>thanks</p>
|
[
{
"answer_id": 220480,
"author": "balaweblog",
"author_id": 22162,
"author_profile": "https://Stackoverflow.com/users/22162",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to maintain state on postback, you must provide your own methods\nof recording what the user has done with your control on the client side\n and either update the server control later on the server with\nthe changes, or redo the changes on the client side when the page refreshes. </p>\n"
},
{
"answer_id": 220586,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 2,
"selected": true,
"text": "<p>I find using IStateManager works the best. </p>\n\n<p>For example:</p>\n\n<pre><code>partial class MyControl : System.Web.UI.UserControl, IStateManager\n{\n [Serializable()]\n protected struct MyControlState\n {\n public bool someValue;\n public string name;\n }\n\n protected MyControlState state;\n\n public bool someValue {\n get { return state.someValue; }\n set { state.someValue = value; }\n }\n\n public bool IsTrackingViewState {\n get { return true; }\n }\n\n protected override void LoadViewState(object state)\n {\n if ((state != null) && state is MyControlState) {\n this.state = state;\n }\n }\n\n protected override object SaveViewState()\n {\n return state;\n }\n\n protected override void TrackViewState()\n {\n base.TrackViewState();\n }\n}\n</code></pre>\n\n<p>getDefaultState() would just load some sane defaults into a new state struct. state gets tracked in the viewstate of the page, and ASP will take care of bring it in/out for you.</p>\n\n<p>(above code ported from VB and not checked, hopefully I didn't make any errors but it should get the point across anyways)</p>\n"
},
{
"answer_id": 616260,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm I wonder if we can use the existing ASP.NET persistence... try inheriting from the most basic post-back state persisting control (I'm thinking asp:hidden). Then just override the render and add all the jazz you want.</p>\n\n<p>Let me know if it works, then I won't have to test :)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
This works, but is it the proper way to do it???
I have a custom server control that has an [input] box on it. I want it to kinda mimic the ASP.NET TextBox, but not completely. When the textbox is rendered i have a javascript that allows users to select values that are then placed in that input box.
I have a public text property on the control. In the get/set i get/set the viewstate for the control - that part is easy, but when the control is populated via the javascript, the Text get is not actually called, what is the proper way to set this exposed property using JavaScript (or even if the user just types in the box) ?
Edit:
In the OnInit i ensure the state is maintained by reaching into the form values.
```
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (HttpContext.Current.Request.Form["MyInputBoxValue"] != "")
{
ViewState["MyInputBoxValue"]
= HttpContext.Current.Request.Form["MyInputBoxValue"];
}
}
```
Then to get the value actually back in place in the HtmlTextWrite, i do this:
```
protected override void RenderContents(HtmlTextWriter output)
{
// There is an input control here and i set its value property
// like this using the Text internal defined.
output.Write("<input value=" + Text + ">.....
}
```
thanks
|
I find using IStateManager works the best.
For example:
```
partial class MyControl : System.Web.UI.UserControl, IStateManager
{
[Serializable()]
protected struct MyControlState
{
public bool someValue;
public string name;
}
protected MyControlState state;
public bool someValue {
get { return state.someValue; }
set { state.someValue = value; }
}
public bool IsTrackingViewState {
get { return true; }
}
protected override void LoadViewState(object state)
{
if ((state != null) && state is MyControlState) {
this.state = state;
}
}
protected override object SaveViewState()
{
return state;
}
protected override void TrackViewState()
{
base.TrackViewState();
}
}
```
getDefaultState() would just load some sane defaults into a new state struct. state gets tracked in the viewstate of the page, and ASP will take care of bring it in/out for you.
(above code ported from VB and not checked, hopefully I didn't make any errors but it should get the point across anyways)
|
220,488 |
<p>I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to write code that simulates a click on the "background" of the page?</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("input").focus();
document.getElementById("main").focus();
});
</script>
</head>
<body>
<div id="main">
<form action="/">
<p>
<input type="text" id="input"/>
</p>
</form>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 220491,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 5,
"selected": true,
"text": "<p>I would imagine using <code>blur()</code> would do the trick:</p>\n\n<pre><code><script type=\"text/javascript\">\n YAHOO.util.Event.onDOMReady(function() {\n document.getElementById(\"input\").focus(); \n document.getElementById(\"input\").blur(); \n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 220494,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the <code>blur</code> event. If you're using jQuery there is a method you can call on the DOM object to raise this event. The <code>blur()</code> method should also work without jQuery.</p>\n\n<p><a href=\"http://docs.jquery.com/Events/blur\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/blur</a></p>\n"
},
{
"answer_id": 64925509,
"author": "Regis Emiel",
"author_id": 9096719,
"author_profile": "https://Stackoverflow.com/users/9096719",
"pm_score": 0,
"selected": false,
"text": "<p>Your idea is right, but there is a little problem.</p>\n<pre><code>document.getElementById("main").focus();\n\n<div id="main">\n</code></pre>\n<p>as shown in your code, actually the div HTMLElement doesn't have a focus method.</p>\n<p>so you can call other elements that have a focus method or call <code>blur()</code> on the input element</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to write code that simulates a click on the "background" of the page?
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("input").focus();
document.getElementById("main").focus();
});
</script>
</head>
<body>
<div id="main">
<form action="/">
<p>
<input type="text" id="input"/>
</p>
</form>
</div>
</body>
</html>
```
|
I would imagine using `blur()` would do the trick:
```
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("input").focus();
document.getElementById("input").blur();
});
</script>
```
|
220,507 |
<p>I write a large static method that takes a generic as a parameter argument. I call this method, and the framework throws a System.InvalidProgramException. This exception is thrown even before the first line of the method is executed.</p>
<p>I can create a static class which takes the generic argument, and then make this a method of the static class, and everything works fine.</p>
<p>Is this a .NET defect, or is there some obscure generic rule I'm breaking here?</p>
<p>For the sake of completeness, I've included the method which fails, and the method which passes. Note that this uses a number of other classes from my own library (eg GridUtils), and these classes are not explained here. I don't think the actual meaning matters: the question is why the runtime crashes before the method even starts.</p>
<p>(I'm programming with Visual Studio 2005, so maybe this has gone away in Visual Studio 2008.)</p>
<p><b>This throws an exception before the first line is invoked:</b></p>
<pre><code> private delegate void PROG_Delegate<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
</code></pre>
<p><b>This works fine:</b></p>
<pre><code> public static class Populator<TGridLine>
{
private delegate void PROG_Delegate(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate(PopulateReadOnlyGrid),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}
</code></pre>
|
[
{
"answer_id": 220491,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 5,
"selected": true,
"text": "<p>I would imagine using <code>blur()</code> would do the trick:</p>\n\n<pre><code><script type=\"text/javascript\">\n YAHOO.util.Event.onDOMReady(function() {\n document.getElementById(\"input\").focus(); \n document.getElementById(\"input\").blur(); \n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 220494,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the <code>blur</code> event. If you're using jQuery there is a method you can call on the DOM object to raise this event. The <code>blur()</code> method should also work without jQuery.</p>\n\n<p><a href=\"http://docs.jquery.com/Events/blur\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/blur</a></p>\n"
},
{
"answer_id": 64925509,
"author": "Regis Emiel",
"author_id": 9096719,
"author_profile": "https://Stackoverflow.com/users/9096719",
"pm_score": 0,
"selected": false,
"text": "<p>Your idea is right, but there is a little problem.</p>\n<pre><code>document.getElementById("main").focus();\n\n<div id="main">\n</code></pre>\n<p>as shown in your code, actually the div HTMLElement doesn't have a focus method.</p>\n<p>so you can call other elements that have a focus method or call <code>blur()</code> on the input element</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28506/"
] |
I write a large static method that takes a generic as a parameter argument. I call this method, and the framework throws a System.InvalidProgramException. This exception is thrown even before the first line of the method is executed.
I can create a static class which takes the generic argument, and then make this a method of the static class, and everything works fine.
Is this a .NET defect, or is there some obscure generic rule I'm breaking here?
For the sake of completeness, I've included the method which fails, and the method which passes. Note that this uses a number of other classes from my own library (eg GridUtils), and these classes are not explained here. I don't think the actual meaning matters: the question is why the runtime crashes before the method even starts.
(I'm programming with Visual Studio 2005, so maybe this has gone away in Visual Studio 2008.)
**This throws an exception before the first line is invoked:**
```
private delegate void PROG_Delegate<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
```
**This works fine:**
```
public static class Populator<TGridLine>
{
private delegate void PROG_Delegate(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate(PopulateReadOnlyGrid),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}
```
|
I would imagine using `blur()` would do the trick:
```
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("input").focus();
document.getElementById("input").blur();
});
</script>
```
|
220,547 |
<p>Does anyone knows how to detect printable characters in java?</p>
<p>After a while ( trial/error ) I get to this method:</p>
<pre><code> public boolean isPrintableChar( char c ) {
Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
return (!Character.isISOControl(c)) &&
c != KeyEvent.CHAR_UNDEFINED &&
block != null &&
block != Character.UnicodeBlock.SPECIALS;
}
</code></pre>
<p>I'm getting the input via KeyListener and come Ctr-'key' printed an square. With this function seems fairly enough. </p>
<p>Am I missing some char here?</p>
|
[
{
"answer_id": 221115,
"author": "jb.",
"author_id": 7918,
"author_profile": "https://Stackoverflow.com/users/7918",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not perfectly sure whether I understand your problem. But if you want detect if character can be drawn to Graphics object, and if not print some placeholder char you might find usefull:</p>\n\n<pre><code>Font.canDisplay(int)\n</code></pre>\n\n<p>It will check whether font can display specific codepoint (it is more that check whether font is displayable at all -- since there are chars that are displayable - like ą - but some fonts cant display them.</p>\n"
},
{
"answer_id": 418560,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 7,
"selected": true,
"text": "<p>It seems this was the \"Font\" independent way.</p>\n\n<pre><code>public boolean isPrintableChar( char c ) {\n Character.UnicodeBlock block = Character.UnicodeBlock.of( c );\n return (!Character.isISOControl(c)) &&\n c != KeyEvent.CHAR_UNDEFINED &&\n block != null &&\n block != Character.UnicodeBlock.SPECIALS;\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
Does anyone knows how to detect printable characters in java?
After a while ( trial/error ) I get to this method:
```
public boolean isPrintableChar( char c ) {
Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
return (!Character.isISOControl(c)) &&
c != KeyEvent.CHAR_UNDEFINED &&
block != null &&
block != Character.UnicodeBlock.SPECIALS;
}
```
I'm getting the input via KeyListener and come Ctr-'key' printed an square. With this function seems fairly enough.
Am I missing some char here?
|
It seems this was the "Font" independent way.
```
public boolean isPrintableChar( char c ) {
Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
return (!Character.isISOControl(c)) &&
c != KeyEvent.CHAR_UNDEFINED &&
block != null &&
block != Character.UnicodeBlock.SPECIALS;
}
```
|
220,560 |
<p>I am changing document template macros. The one thing I can't find out how to do is to customize error messages. For example an error message in a document is</p>
<p>"Error! No table of figures entries found"</p>
<p>I would like to change this to display something else. Is it possible to do this with Word VBA or VBScript?</p>
|
[
{
"answer_id": 220573,
"author": "CtrlDot",
"author_id": 19487,
"author_profile": "https://Stackoverflow.com/users/19487",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to trap a specific error type in VBA, one method is to use On Error Resume Next then test for an error message on the line following the action to trap, e.g.:</p>\n\n<pre><code>On Error Resume Next\n' try action\nIf Err.Number <> 0 Then\n ' handle w/ custom message\n Err.Clear\nEnd If\n</code></pre>\n\n<p>If you know the exact error number (<code>If Err.Number = N Then</code>), that would be better of course.</p>\n"
},
{
"answer_id": 220579,
"author": "Michael Galos",
"author_id": 29820,
"author_profile": "https://Stackoverflow.com/users/29820",
"pm_score": 0,
"selected": false,
"text": "<p>Well if you are talking about having a custom message box - that's easy.\nLook up 'msgbox' in VBA help for better info.</p>\n\n<pre><code>Msgbox(\"Error! No table of figures entries found\",16,\"Error\")\n</code></pre>\n\n<p>The 16 makes it a 'criticial' message.</p>\n\n<p>If you're talking about error trapping then you'll need code like this:</p>\n\n<pre><code>On Error Resume Next\nn = 1 / 0 ' this causes an error\nIf Err.Number <> 0 Then \n n = 1\n if Err.Number = 1 Then MsgBox Err.Description\nEnd If\n</code></pre>\n\n<p>When an error is thrown, a number and description are given to the Err object.</p>\n"
},
{
"answer_id": 221239,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to put this in some\n kind of global error handler? – Craig</p>\n</blockquote>\n\n<p>It is possible. Here is a very rough example.</p>\n\n<p>In a standard module:</p>\n\n<pre><code>Sub HandleErr(ErrNo As Long)\n Select Case ErrNo\n Case vbObjectError + 1024\n MsgBox \"No table of figures entries found.\", vbOKOnly + vbCritical\n\n Case vbObjectError + 1034 To vbObjectError + 4999\n MsgBox \"Still no table of figures entries found.\", vbOKOnly + vbCritical\n\n Case Else\n MsgBox \"I give up.\", vbOKOnly + vbCritical, _\n \"Application Error\"\n End Select\nEnd Sub\n</code></pre>\n\n<p>Some code:</p>\n\n<pre><code>Sub ShowError()\nDim i As Integer\n\nOn Error GoTo Proc_Err\n\n 'VBA Error\n i = \"a\"\n\n 'Custom error\n If Dir(\"C:\\Docs\\TableFigs.txt\") = \"\" Then\n Err.Raise vbObjectError + 1024\n End If\n\nExit_Here:\n Exit Sub\n\nProc_Err:\n If Err.Number > vbObjectError And Err.Number < vbObjectError + 9999 Then\n HandleErr Err.Number\n Else\n MsgBox Err.Description\n End If\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
I am changing document template macros. The one thing I can't find out how to do is to customize error messages. For example an error message in a document is
"Error! No table of figures entries found"
I would like to change this to display something else. Is it possible to do this with Word VBA or VBScript?
|
>
> Is it possible to put this in some
> kind of global error handler? – Craig
>
>
>
It is possible. Here is a very rough example.
In a standard module:
```
Sub HandleErr(ErrNo As Long)
Select Case ErrNo
Case vbObjectError + 1024
MsgBox "No table of figures entries found.", vbOKOnly + vbCritical
Case vbObjectError + 1034 To vbObjectError + 4999
MsgBox "Still no table of figures entries found.", vbOKOnly + vbCritical
Case Else
MsgBox "I give up.", vbOKOnly + vbCritical, _
"Application Error"
End Select
End Sub
```
Some code:
```
Sub ShowError()
Dim i As Integer
On Error GoTo Proc_Err
'VBA Error
i = "a"
'Custom error
If Dir("C:\Docs\TableFigs.txt") = "" Then
Err.Raise vbObjectError + 1024
End If
Exit_Here:
Exit Sub
Proc_Err:
If Err.Number > vbObjectError And Err.Number < vbObjectError + 9999 Then
HandleErr Err.Number
Else
MsgBox Err.Description
End If
End Sub
```
|
220,603 |
<p>I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.</p>
<p>If I wanted to generate the following HTML for each object:</p>
<pre><code><div><img src="the url" />the name</div>
</code></pre>
<p>Is there a best practice for this? I can see a few ways of doing it:</p>
<ol>
<li>Concatenate strings</li>
<li>Create elements</li>
<li>Use a templating plugin</li>
<li>Generate the html on the server, then serve up via JSON.</li>
</ol>
|
[
{
"answer_id": 220619,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 3,
"selected": false,
"text": "<p>Either of the first two options is both common and acceptable.</p>\n\n<p>I'll give examples of each one in <a href=\"http://prototypejs.org/\" rel=\"noreferrer\">Prototype</a>.</p>\n\n<pre><code>// assuming JSON looks like this:\n// { 'src': 'foo/bar.jpg', 'name': 'Lorem ipsum' }\n</code></pre>\n\n<p>Approach #1:</p>\n\n<pre><code>var html = \"<div><img src='#{src}' /> #{name}</div>\".interpolate(json);\n$('container').insert(html); // inserts at bottom\n</code></pre>\n\n<p>Approach #2:</p>\n\n<pre><code>var div = new Element('div');\ndiv.insert( new Element('img', { src: json.src }) );\ndiv.insert(\" \" + json.name);\n$('container').insert(div); // inserts at bottom\n</code></pre>\n"
},
{
"answer_id": 220632,
"author": "Jim Fiorato",
"author_id": 650,
"author_profile": "https://Stackoverflow.com/users/650",
"pm_score": 7,
"selected": true,
"text": "<p>Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects.</p>\n\n<p>Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frameworks.</p>\n\n<p>Here's an example in <a href=\"http://api.jquery.com/jQuery.template/\" rel=\"noreferrer\">JQuery Template Plugin</a> that will save you the performance hit, and is really, really straightforward:</p>\n\n<pre><code>var t = $.template('<div><img src=\"${url}\" />${name}</div>');\n\n$(selector).append( t , {\n url: jsonObj.url,\n name: jsonObj.name\n});\n</code></pre>\n\n<p>I say go the cool route (and better performing, more maintainable), and use templating.</p>\n"
},
{
"answer_id": 220696,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an example, using my <strong><a href=\"http://code.google.com/p/jquery-simple-templates/\" rel=\"noreferrer\">Simple Templates</a></strong> plug-in for jQuery:</p>\n\n<pre><code>var tmpl = '<div class=\"#{classname}\">#{content}</div>';\nvar vals = {\n classname : 'my-class',\n content : 'This is my content.'\n};\nvar html = $.tmpl(tmpl, vals);\n</code></pre>\n"
},
{
"answer_id": 223790,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 3,
"selected": false,
"text": "<p>You could add the template HTML to your page in a hidden div and then use cloneNode and your favorite library's querying facilities to populate it</p>\n\n<pre><code>/* CSS */\n.template {display:none;}\n\n<!--HTML-->\n<div class=\"template\">\n <div class=\"container\">\n <h1></h1>\n <img src=\"\" alt=\"\" />\n </div>\n</div>\n\n/*Javascript (using Prototype)*/\nvar copy = $$(\".template .container\")[0].cloneNode(true);\nmyElement.appendChild(copy);\n$(copy).select(\"h1\").each(function(e) {/*do stuff to h1*/})\n$(copy).select(\"img\").each(function(e) {/*do stuff to img*/})\n</code></pre>\n"
},
{
"answer_id": 304798,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 4,
"selected": false,
"text": "<p>If you absolutely have to concatenate strings, instead of the normal :</p>\n\n<pre><code>var s=\"\";\nfor (var i=0; i < 200; ++i) {s += \"testing\"; }\n</code></pre>\n\n<p>use a temporary array:</p>\n\n<pre><code>var s=[];\nfor (var i=0; i < 200; ++i) { s.push(\"testing\"); }\ns = s.join(\"\");\n</code></pre>\n\n<p>Using arrays is much faster, especially in IE. I did some testing with strings a while ago with IE7, Opera and FF. Opera took only 0.4s to perform the test, but IE7 hadn't finished after 20 MINUTES !!!! ( No, I am not kidding. ) With array IE was very fast. </p>\n"
},
{
"answer_id": 23670731,
"author": "Tzach",
"author_id": 1795244,
"author_profile": "https://Stackoverflow.com/users/1795244",
"pm_score": 3,
"selected": false,
"text": "<p>Perhaps a more modern approach is to use a templating language such as <a href=\"https://github.com/janl/mustache.js\" rel=\"nofollow\">Mustache</a>, which has implementations in many languages, including javascript. For example:</p>\n\n<pre><code>var view = {\n url: \"/hello\",\n name: function () {\n return 'Jo' + 'hn';\n }\n};\n\nvar output = Mustache.render('<div><img src=\"{{url}}\" />{{name}}</div>', view);\n</code></pre>\n\n<p>You even get an added benefit - you can reuse the same templates in other places, such as the server side.</p>\n\n<p>If you need more complicated templates (if statements, loops, etc.), you can use <a href=\"http://handlebarsjs.com/\" rel=\"nofollow\">Handlebars</a> which has more features, and is compatible with Mustache.</p>\n"
},
{
"answer_id": 23671367,
"author": "Paolo",
"author_id": 1579327,
"author_profile": "https://Stackoverflow.com/users/1579327",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is there a best practice for this? I can see a few ways of doing it:</p>\n \n <ol>\n <li>Concatenate strings </li>\n <li>Create elements </li>\n <li>Use a templating plugin </li>\n <li>Generate the html on the server, then serve up via JSON.</li>\n </ol>\n</blockquote>\n\n<p><strong>1)</strong> This is an option. Build up the html with JavaScript on the client side and then inject it in the DOM as a whole.</p>\n\n<p>Note that there is a paradigm behind this approach: the server outputs just data and (in case of interaction) receives data from the client asyncronoulsy with AJAX requests. The client side code operete as a stand-alone JavaScript web application.</p>\n\n<p>The web application may operate, render the interface, even without the server being up (of course it won't display any data or offer any kind of interaction).</p>\n\n<p>This paradigm is getting adopted often lately, and entire frameworks are build around this approach (see backbone.js for example).</p>\n\n<p><strong>2)</strong> For performance reasons, when possible, is better to build the html in a string and then inject it as a whole into the page.</p>\n\n<p><strong>3)</strong> This is another option, as well as adopting a Web Application framework. Other users have posted various templating engines available. I have the impression that you have the skills to evaluate them and decide whether to follow this path or not.</p>\n\n<p><strong>4)</strong> Another option. But serve it up as a plain text/html; why JSON? I don't like this approach because mixes PHP (your server language) with Html. But I adopt it often as a reasonable compromise between option <strong>1</strong> and <strong>4</strong>.</p>\n\n<hr>\n\n<p>My answer: you are already looking in the right direction.</p>\n\n<p>I suggest to adopt an approach between <strong>1</strong> and <strong>4</strong> like I do. Otherwise adopt a web framework or templating engine.</p>\n\n<p>Just my opinion based on my experience... </p>\n"
},
{
"answer_id": 29434325,
"author": "Automatico",
"author_id": 741850,
"author_profile": "https://Stackoverflow.com/users/741850",
"pm_score": 2,
"selected": false,
"text": "<p>Disclosure: I am the maintainer of BOB.</p>\n<h3>There is a javascript library that makes this process a lot easier called <a href=\"https://github.com/stephan-nordnes-eriksen/BOB\" rel=\"nofollow noreferrer\">BOB</a>.</h3>\n<p>For your specific example:</p>\n<pre><code><div><img src="the url" />the name</div>\n</code></pre>\n<p>This can be generated with BOB by the following code.</p>\n<pre><code>new BOB("div").insert("img",{"src":"the url"}).up().content("the name").toString()\n//=> "<div><img src="the url" />the name</div>"\n</code></pre>\n<p>Or with the shorter syntax</p>\n<pre><code>new BOB("div").i("img",{"src":"the url"}).up().co("the name").s()\n//=> "<div><img src="the url" />the name</div>"\n</code></pre>\n<p>This library is quite powerful and can be used to create very complex structures with data insertion (similar to d3), eg.:</p>\n<pre><code>data = [1,2,3,4,5,6,7]\nnew BOB("div").i("ul#count").do(data).i("li.number").co(BOB.d).up().up().a("a",{"href": "www.google.com"}).s()\n//=> "<div><ul id="count"><li class="number">1</li><li class="number">2</li><li class="number">3</li><li class="number">4</li><li class="number">5</li><li class="number">6</li><li class="number">7</li></ul></div><a href="www.google.com"></a>"\n</code></pre>\n<p>BOB does currently not support injecting the data into the DOM. This is on the todolist. For now you can simply use the output together with normal JS, or jQuery, and put it wherever you want.</p>\n<pre><code>document.getElementById("parent").innerHTML = new BOB("div").insert("img",{"src":"the url"}).up().content("the name").s();\n//Or jquery:\n$("#parent").append(new BOB("div").insert("img",{"src":"the url"}).up().content("the name").s());\n</code></pre>\n<hr />\n<p>I made this library because I was not pleased with any of the alternatives like jquery and d3. The code very complicated and hard to read. Working with BOB is in my opinion, which is obviously biased, a lot more pleasant.</p>\n<p>BOB is available on <strong>Bower</strong>, so you can get it by running <code>bower install BOB</code>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67719/"
] |
I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.
If I wanted to generate the following HTML for each object:
```
<div><img src="the url" />the name</div>
```
Is there a best practice for this? I can see a few ways of doing it:
1. Concatenate strings
2. Create elements
3. Use a templating plugin
4. Generate the html on the server, then serve up via JSON.
|
Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects.
Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frameworks.
Here's an example in [JQuery Template Plugin](http://api.jquery.com/jQuery.template/) that will save you the performance hit, and is really, really straightforward:
```
var t = $.template('<div><img src="${url}" />${name}</div>');
$(selector).append( t , {
url: jsonObj.url,
name: jsonObj.name
});
```
I say go the cool route (and better performing, more maintainable), and use templating.
|
220,624 |
<p>How do I write the getDB() function and use it properly?</p>
<p>Here is a code snippet of my App Object:</p>
<pre><code>public class MyApp extends UiApplication {
private static PersistentObject m_oStore;
private static MyBigObjectOfStorage m_oDB;
static {
store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
}
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new MyMainScreen());
}
// Is this correct? Will it return a copy of m_oDB or a reference of m_oDB?
public MyBigObjectOfStorage getDB() {
return m_oDB; // returns a reference
}
}
</code></pre>
|
[
{
"answer_id": 220724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public MyBigObjectOfStorage getDB() {\n Object o = store.getContents();\n if ( o instanceof MyBigObjectOfStorage ) {\n return (MyBigObjectOfStorage) o;\n } else {\n return null;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 220726,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 2,
"selected": true,
"text": "<pre><code>public MyBigObjectOfStorage getDB() {\n return m_oDB;\n}\n</code></pre>\n\n<p>As you put it is correct. It will return a <em>copy of the reference</em>, which is kind of in between a copy and a reference.</p>\n\n<p>The actual object instance returned by getDB() is the same object referenced by m_oDB. However, you can't change the reference returned by getDB() to point at a different object and have it actually cause the local private m_oDB to point at the new object. m_oDB will still point at the object it was already.</p>\n\n<p>See <a href=\"http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html\" rel=\"nofollow noreferrer\">http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html</a> for more detail.</p>\n\n<p>Although looking through your code there, you never set m_oDB at all, so getDB() will always return null.</p>\n"
},
{
"answer_id": 221861,
"author": "Guðmundur Bjarni",
"author_id": 27349,
"author_profile": "https://Stackoverflow.com/users/27349",
"pm_score": 0,
"selected": false,
"text": "<p>I am one of those folks that are very much against using singletons and/or statics as it tends to make unit testing impossible. As this is posted under best practices, I suggest that you take a look at using a dependency injection framework. Personally I am using and prefer <a href=\"http://code.google.com/p/google-guice/\" rel=\"nofollow noreferrer\">Google Guice</a>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22917/"
] |
How do I write the getDB() function and use it properly?
Here is a code snippet of my App Object:
```
public class MyApp extends UiApplication {
private static PersistentObject m_oStore;
private static MyBigObjectOfStorage m_oDB;
static {
store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
}
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new MyMainScreen());
}
// Is this correct? Will it return a copy of m_oDB or a reference of m_oDB?
public MyBigObjectOfStorage getDB() {
return m_oDB; // returns a reference
}
}
```
|
```
public MyBigObjectOfStorage getDB() {
return m_oDB;
}
```
As you put it is correct. It will return a *copy of the reference*, which is kind of in between a copy and a reference.
The actual object instance returned by getDB() is the same object referenced by m\_oDB. However, you can't change the reference returned by getDB() to point at a different object and have it actually cause the local private m\_oDB to point at the new object. m\_oDB will still point at the object it was already.
See <http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html> for more detail.
Although looking through your code there, you never set m\_oDB at all, so getDB() will always return null.
|
220,638 |
<p>How can I best set up my PHP (LAMP) development environment so that I have development, staging and production servers. One-"click" deployment to any of those, as well as one-click rollback to any revision. Rollback should also rollback the database schema and data to how it was when that source code was current.</p>
<p>Right now I've done all of this (except the DB rollback ability) for one application using shell scripts. I'm curious to know how others' environments are setup, and also if there are any generic tools or best-practices out there to follow as far as layout is concerned.</p>
<p>So, how do you do this? What existing tools do you make use of?</p>
<p>Thanks!</p>
<p>UPDATE: Just to clarify as there is some confusion about what I'm interested in.</p>
<p>I really want people to chime in with how their environment is set up.</p>
<p>If you run a PHP project and you have your DB schema in version control, how do you do it? What tools do you use? Are they in-house or can we all find them on the web somewhere?</p>
<p>If you run a PHP project and you do automated testing on commit (and/or nightly), how do you do it? What source versioning system do you use? Do you use SVN and run your tests in post-commit hooks?</p>
<p>If you run a PHP project with multiple dev servers, a staging server and production server(s), how do you organize them and how do you deploy?</p>
<p>What I hope to get out of this is a good idea of how others glue everything together.</p>
|
[
{
"answer_id": 221958,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 1,
"selected": false,
"text": "<p>I noticed this wasn't getting much exposure. It's also something I'm interested in. Are you aware of <a href=\"http://phing.info/trac/\" rel=\"nofollow noreferrer\">Phing</a>? Have you tried it?</p>\n\n<p>Andrew</p>\n"
},
{
"answer_id": 222130,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/\" rel=\"nofollow noreferrer\">Here's a good guide on automating deployment of PHP applications with Capistrano.</a></p>\n"
},
{
"answer_id": 225524,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 5,
"selected": true,
"text": "<p>Our production environment includes the following:</p>\n\n<ul>\n<li>3 frontends who serve our website</li>\n<li>2 database backends (Master-Slave, replication)</li>\n<li>1 mixed which runs httpd and database for adserving</li>\n</ul>\n\n<p>Our development environment is a single server running both database and httpd, configuration-wise we have different workspaces for everyone setup and our VC is subversion. Staging is rather simple too - it runs on one of the frontends.</p>\n\n<p><strong>Database changes</strong></p>\n\n<p>Initially we spent a lot of time on the database design and it seems to have really paid off. We haven't changed anything major in five months now. Most of the changes we deploy are on the frontend. Now, so far we run all the changes to the database manually and I always wrote a small script to revert.</p>\n\n<p>If I had more of those, I'd use <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a> and <a href=\"http://www.doctrine-project.org/projects/migrations.html\" rel=\"nofollow noreferrer\">Migrations</a> here. I've never actually had the chance to use them in production but I've played with those extensively already and they seem very powerful.</p>\n\n<p><strong>Deployment</strong></p>\n\n<p>So whenever we deploy a new version we create a tag of the code which we check out on staging, then go through a couple lists of checks etc. and then we deploy the code on the production frontends. For doing all of the deployment, I have a couple tasks setup in <a href=\"http://capistranorb.com/\" rel=\"nofollow noreferrer\">Capistrano</a>.</p>\n\n<p>Check out this sample <code>capfile</code>:</p>\n\n<pre><code>role :www, \"web01\", \"web02\", \"web03\"\nrole :web, \"web01\", \"web02\", \"web03\", \"web04\"\nrole :db, \"db01\", \"db02\"\n\ndesc \"Deploy sites\"\ntask :deploy, :roles => :www do\n run \"cd /usr/www/website && sudo svn --username=deploy --password=foo update\"\nend\n</code></pre>\n\n<p>Capistrano also allows you to run any other command without defining a task:</p>\n\n<pre><code>cap invoke COMMAND=\"uptime\" ROLES=web\n</code></pre>\n\n<p>(Requires the <em>role</em> \"web\" to be setup. See example above.)</p>\n\n<p><strong>Coding style and documentation</strong></p>\n\n<p>We pretty much adhere to the <a href=\"http://pear.php.net/manual/en/standards.php\" rel=\"nofollow noreferrer\">PEAR Coding standard</a>, which we check using <a href=\"http://pear.php.net/package/PHP_CodeSniffer\" rel=\"nofollow noreferrer\">PHP_CodeSniffer</a> (phpcs). When I say pretty much, I mean that I forked the sniffs provided and added a few exceptions of my own gusto.</p>\n\n<p>On top of coding style, phpcs checks on inline documentation as well. This documentation is created by <a href=\"http://phpdoc.org/\" rel=\"nofollow noreferrer\">phpDocumentor</a> in the end.</p>\n\n<p><strong>CI</strong></p>\n\n<p>I have both of those tools setup in our CI-server (<strong>continuos-integration</strong>), which is <a href=\"http://phpundercontrol.org\" rel=\"nofollow noreferrer\">phpUnderControl</a> using the above and CruiseControl, <a href=\"http://phpunit.de\" rel=\"nofollow noreferrer\">phpUnit</a>, <a href=\"http://xdebug.org\" rel=\"nofollow noreferrer\">Xdebug</a> (a couple code metrics...), etc..</p>\n\n<p>unit-testing is something we currently lack. But what we do right now is that with each bug we find in our parsing engine (we parse text into certain formats), we write a test to make sure it doesn't come back. I've also written some basic tests to check the URL-routing and the internal XMLRPC API but this is really subject to improvement. We employ both phpUnit-style tests and <a href=\"http://qa.php.net/write-test.php\" rel=\"nofollow noreferrer\">phpt</a> as well.</p>\n\n<p>The CI-server <em>builds</em> a new version a couple times per day, generates graphs, docs and all kinds of reports.</p>\n\n<p>On top of all of the tools mentioned, we also use Google Apps (primarily for email) and keep a Google Sites wiki with all other documentation. For example, deployment procedure, QA test lists, etc..</p>\n"
},
{
"answer_id": 241483,
"author": "Bertrand Gorge",
"author_id": 30955,
"author_profile": "https://Stackoverflow.com/users/30955",
"pm_score": 0,
"selected": false,
"text": "<p>@andrew : I've tried Phing and ended up with phpUnderControl. The problem with Phing is that to manage code coverage, it has to actually include all the files in you project, which for our project just does not do it. The approach of CruiseControl worked better for us. Give them a try, they are both easy to setup - the hard work is to build the tests....</p>\n"
},
{
"answer_id": 1171129,
"author": "K. Norbert",
"author_id": 80761,
"author_profile": "https://Stackoverflow.com/users/80761",
"pm_score": 1,
"selected": false,
"text": "<p>For database changes, we have a directory in the VCS:</p>\n\n<pre><code>+ dbchanges\n|_ 01_database\n|_ 02_table\n|_ 03_data\n|_ 04_constraints\n|_ 05_functions\n|_ 06_triggers\n|_ 07_indexes\n</code></pre>\n\n<p>When you make a change to the database you put the .sql file into the correct directory, and run the integration script that goes through these directories in order, and import every change into the db.</p>\n\n<p>The sql files have to have to start with a comment, which is displayed to the user when the integration scripts imports the change, describing what it does. It logs every imported sql file's name to a file, so when you run the script next time, it won't apply the same change again.</p>\n\n<p>This way, all the developers can simply run the script to get the db up to date.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29838/"
] |
How can I best set up my PHP (LAMP) development environment so that I have development, staging and production servers. One-"click" deployment to any of those, as well as one-click rollback to any revision. Rollback should also rollback the database schema and data to how it was when that source code was current.
Right now I've done all of this (except the DB rollback ability) for one application using shell scripts. I'm curious to know how others' environments are setup, and also if there are any generic tools or best-practices out there to follow as far as layout is concerned.
So, how do you do this? What existing tools do you make use of?
Thanks!
UPDATE: Just to clarify as there is some confusion about what I'm interested in.
I really want people to chime in with how their environment is set up.
If you run a PHP project and you have your DB schema in version control, how do you do it? What tools do you use? Are they in-house or can we all find them on the web somewhere?
If you run a PHP project and you do automated testing on commit (and/or nightly), how do you do it? What source versioning system do you use? Do you use SVN and run your tests in post-commit hooks?
If you run a PHP project with multiple dev servers, a staging server and production server(s), how do you organize them and how do you deploy?
What I hope to get out of this is a good idea of how others glue everything together.
|
Our production environment includes the following:
* 3 frontends who serve our website
* 2 database backends (Master-Slave, replication)
* 1 mixed which runs httpd and database for adserving
Our development environment is a single server running both database and httpd, configuration-wise we have different workspaces for everyone setup and our VC is subversion. Staging is rather simple too - it runs on one of the frontends.
**Database changes**
Initially we spent a lot of time on the database design and it seems to have really paid off. We haven't changed anything major in five months now. Most of the changes we deploy are on the frontend. Now, so far we run all the changes to the database manually and I always wrote a small script to revert.
If I had more of those, I'd use [Doctrine](http://www.doctrine-project.org/) and [Migrations](http://www.doctrine-project.org/projects/migrations.html) here. I've never actually had the chance to use them in production but I've played with those extensively already and they seem very powerful.
**Deployment**
So whenever we deploy a new version we create a tag of the code which we check out on staging, then go through a couple lists of checks etc. and then we deploy the code on the production frontends. For doing all of the deployment, I have a couple tasks setup in [Capistrano](http://capistranorb.com/).
Check out this sample `capfile`:
```
role :www, "web01", "web02", "web03"
role :web, "web01", "web02", "web03", "web04"
role :db, "db01", "db02"
desc "Deploy sites"
task :deploy, :roles => :www do
run "cd /usr/www/website && sudo svn --username=deploy --password=foo update"
end
```
Capistrano also allows you to run any other command without defining a task:
```
cap invoke COMMAND="uptime" ROLES=web
```
(Requires the *role* "web" to be setup. See example above.)
**Coding style and documentation**
We pretty much adhere to the [PEAR Coding standard](http://pear.php.net/manual/en/standards.php), which we check using [PHP\_CodeSniffer](http://pear.php.net/package/PHP_CodeSniffer) (phpcs). When I say pretty much, I mean that I forked the sniffs provided and added a few exceptions of my own gusto.
On top of coding style, phpcs checks on inline documentation as well. This documentation is created by [phpDocumentor](http://phpdoc.org/) in the end.
**CI**
I have both of those tools setup in our CI-server (**continuos-integration**), which is [phpUnderControl](http://phpundercontrol.org) using the above and CruiseControl, [phpUnit](http://phpunit.de), [Xdebug](http://xdebug.org) (a couple code metrics...), etc..
unit-testing is something we currently lack. But what we do right now is that with each bug we find in our parsing engine (we parse text into certain formats), we write a test to make sure it doesn't come back. I've also written some basic tests to check the URL-routing and the internal XMLRPC API but this is really subject to improvement. We employ both phpUnit-style tests and [phpt](http://qa.php.net/write-test.php) as well.
The CI-server *builds* a new version a couple times per day, generates graphs, docs and all kinds of reports.
On top of all of the tools mentioned, we also use Google Apps (primarily for email) and keep a Google Sites wiki with all other documentation. For example, deployment procedure, QA test lists, etc..
|
220,643 |
<p>In my app I've got a thread which displays for some time "please wait" dialog window, sometimes it is a very tiny amout of time and there is some glitch while drawing UI (I guess).</p>
<p>I get the exception "Thread was being aborted" and completly have no idea how get rid of it. I mean Catch that exception in some way, or in some other way hide it from user. This exception has got nothing to do with rest of my app and that error in any way doesn't affect it. Appears randomly and it is hard to recreate on a call.</p>
<p>I tried in various ways to catch that exception by side of code which starts and stops thread with dialog window but it seems that error apparently is by side some other thread which dispalys window in my newly created thread.</p>
<p>Here is a code sample, part of static class with useful stuff, of course I don't say that is good way to solve this kind of "busy" situation but I want to solve this problem. Thread.Sleep(500); or other try/catch improvments doesn't help me to avoid that thread exception.</p>
<pre><code> public static bool alreadyBusy = false;
public static BusyIndicator bi = new BusyIndicator("");
public static Thread backgroundOpertionThread;
public static void showBusy(bool isBusy, System.Windows.Forms.Form hostform, string message)
{
Common.busyMessage = message;
if (isBusy)
{
Common.alreadyBusy = true;
backgroundOpertionThread = new Thread(new ThreadStart(showBusy));
Thread.Sleep(500);
if (hostform != null)
{
hostform.Enabled = false;
hostform.SuspendLayout();
}
backgroundOpertionThread.Start();
}
else
{
backgroundOpertionThread.Abort();
Thread.Sleep(500);
Common.alreadyBusy = false;
if (hostform != null)
{
hostform.Enabled = true;
hostform.ResumeLayout();
}
}
}
public static void showBusy()
{
BusyIndicator bir = new BusyIndicator(Common.busyMessage);
bir.ShowDialog();
}
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 220729,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>use <a href=\"http://www.codeproject.com/KB/threads/SafeThread.aspx\" rel=\"nofollow noreferrer\">SafeThread</a> and set ShouldReportThreadAbort to false to make the problem go away...</p>\n\n<p>a better solution would be to run this in the debugger with Debug >> Exceptions >> Thrown checked for all exception types, and figure out what is happening to abort your thread</p>\n\n<p>EDIT: thanks for posting the code sample, that makes the problem much easier to see. <strong>DO NOT CALL THREAD.ABORT</strong></p>\n"
},
{
"answer_id": 220811,
"author": "joshua.ewer",
"author_id": 28664,
"author_profile": "https://Stackoverflow.com/users/28664",
"pm_score": 0,
"selected": false,
"text": "<p>Agreed with Steven's idea about turning on all exceptions when thrown. Then you'll be able to immediately see the problem. </p>\n\n<p>One thing that's important to remember, you won't have the debug menu option if your visual studio settings are on general, as opposed to the \"Visual C# Developer\" setting. Still catches me if I'm on a new machine or using a new profile...</p>\n"
},
{
"answer_id": 220917,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": true,
"text": "<p>Do <strong>not</strong> use Thread.Abort. This method is reserved for when the .NET runtime needs to forcibly kill threads in order to unload your program.</p>\n\n<p>You can only \"safely\" use this if you're about to unload an AppDomain and want to get rid of threads running in it first.</p>\n\n<p>To get rid of a thread, write it in cooperative mode. This means that the thread should periodically check some kind of flag, and if the flag is set, exit normally out of the thread method. To \"kill\" the thread, simply set the flag and wait for the thread to exit.</p>\n\n<p>You can use an Event-object or a simple boolean variable for this flag.</p>\n\n<p>But <strong>do not use Thread.Abort</strong>.</p>\n"
},
{
"answer_id": 220948,
"author": "Veldmuis",
"author_id": 18826,
"author_profile": "https://Stackoverflow.com/users/18826",
"pm_score": -1,
"selected": false,
"text": "<p>You can try calling</p>\n\n<pre><code>Thread.Sleep(500);\n</code></pre>\n\n<p>after</p>\n\n<pre><code>backgroundOpertionThread.Start();\n</code></pre>\n\n<p>This would give the background thread 500 ms to do what it needs to do before the main thread gets an opportunity to call</p>\n\n<pre><code>backgroundOpertionThread.Abort();\n</code></pre>\n\n<p>Edit: But I agree that the best solution would be not to use Thread.Abort() at all</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24824/"
] |
In my app I've got a thread which displays for some time "please wait" dialog window, sometimes it is a very tiny amout of time and there is some glitch while drawing UI (I guess).
I get the exception "Thread was being aborted" and completly have no idea how get rid of it. I mean Catch that exception in some way, or in some other way hide it from user. This exception has got nothing to do with rest of my app and that error in any way doesn't affect it. Appears randomly and it is hard to recreate on a call.
I tried in various ways to catch that exception by side of code which starts and stops thread with dialog window but it seems that error apparently is by side some other thread which dispalys window in my newly created thread.
Here is a code sample, part of static class with useful stuff, of course I don't say that is good way to solve this kind of "busy" situation but I want to solve this problem. Thread.Sleep(500); or other try/catch improvments doesn't help me to avoid that thread exception.
```
public static bool alreadyBusy = false;
public static BusyIndicator bi = new BusyIndicator("");
public static Thread backgroundOpertionThread;
public static void showBusy(bool isBusy, System.Windows.Forms.Form hostform, string message)
{
Common.busyMessage = message;
if (isBusy)
{
Common.alreadyBusy = true;
backgroundOpertionThread = new Thread(new ThreadStart(showBusy));
Thread.Sleep(500);
if (hostform != null)
{
hostform.Enabled = false;
hostform.SuspendLayout();
}
backgroundOpertionThread.Start();
}
else
{
backgroundOpertionThread.Abort();
Thread.Sleep(500);
Common.alreadyBusy = false;
if (hostform != null)
{
hostform.Enabled = true;
hostform.ResumeLayout();
}
}
}
public static void showBusy()
{
BusyIndicator bir = new BusyIndicator(Common.busyMessage);
bir.ShowDialog();
}
```
Any ideas?
|
Do **not** use Thread.Abort. This method is reserved for when the .NET runtime needs to forcibly kill threads in order to unload your program.
You can only "safely" use this if you're about to unload an AppDomain and want to get rid of threads running in it first.
To get rid of a thread, write it in cooperative mode. This means that the thread should periodically check some kind of flag, and if the flag is set, exit normally out of the thread method. To "kill" the thread, simply set the flag and wait for the thread to exit.
You can use an Event-object or a simple boolean variable for this flag.
But **do not use Thread.Abort**.
|
220,658 |
<p>Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused. </p>
<p>And now that we're here, how do they differ from a regular function?</p>
|
[
{
"answer_id": 220691,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 6,
"selected": false,
"text": "<p>Not all closures are lambdas and not all lambdas are closures. Both are functions, but not necessarily in the manner we're used to knowing.</p>\n\n<p>A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.</p>\n\n<p>A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.</p>\n\n<p>In an object-oriented language, closures are normally provided through objects. However, some OO languages (e.g. C#) implement special functionality that is closer to the definition of closures provided by purely <a href=\"http://en.wikipedia.org/wiki/Category:Functional_languages\" rel=\"noreferrer\">functional languages</a> (such as lisp) that do not have objects to enclose state.</p>\n\n<p>What's interesting is that the introduction of Lambdas and Closures in C# brings functional programming closer to mainstream usage.</p>\n"
},
{
"answer_id": 220715,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 8,
"selected": false,
"text": "<p>When most people think of <em>functions</em>, they think of <strong>named functions</strong>:</p>\n\n<pre><code>function foo() { return \"This string is returned from the 'foo' function\"; }\n</code></pre>\n\n<p>These are called by name, of course:</p>\n\n<pre><code>foo(); //returns the string above\n</code></pre>\n\n<p>With <em>lambda expressions</em>, you can have <strong>anonymous functions</strong>:</p>\n\n<pre><code> @foo = lambda() {return \"This is returned from a function without a name\";}\n</code></pre>\n\n<p>With the above example, you can call the lambda through the variable it was assigned to:</p>\n\n<pre><code>foo();\n</code></pre>\n\n<p>More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:</p>\n\n<pre><code>function filter(list, predicate) \n { @filteredList = [];\n for-each (@x in list) if (predicate(x)) filteredList.add(x);\n return filteredList;\n }\n\n//filter for even numbers\nfilter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); \n</code></pre>\n\n<p>A <em>closure</em> may be a named or anonymous function, but is known as such when it \"closes over\" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:</p>\n\n<pre><code>@x = 0;\n\nfunction incrementX() { x = x + 1;}\n\nincrementX(); // x now equals 1\n</code></pre>\n\n<p>That doesn't seem like much but what if this was all in another function and you passed <code>incrementX</code> to an external function?</p>\n\n<pre><code>function foo()\n { @x = 0;\n\n function incrementX() \n { x = x + 1;\n return x;\n }\n\n return incrementX;\n }\n\n@y = foo(); // y = closure of incrementX over foo.x\ny(); //returns 1 (y.x == 0 + 1)\ny(); //returns 2 (y.x == 1 + 1)\n</code></pre>\n\n<p>This is how you get stateful objects in functional programming. Since naming \"incrementX\" isn't needed, you can use a lambda in this case:</p>\n\n<pre><code>function foo()\n { @x = 0;\n\n return lambda() \n { x = x + 1;\n return x;\n };\n }\n</code></pre>\n"
},
{
"answer_id": 220728,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 11,
"selected": true,
"text": "<p>A <b>lambda</b> is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.</p>\n\n<p>A <b>closure</b> is any function which <b>closes over</b> the <b>environment</b> in which it was defined. This means that it can access variables not in its parameter list. Examples:</p>\n\n<pre><code>def func(): return h\ndef anotherfunc(h):\n return func()\n</code></pre>\n\n<p>This will cause an error, because <code>func</code> does not <b>close over</b> the environment in <code>anotherfunc</code> - <code>h</code> is undefined. <code>func</code> only closes over the global environment. This will work:</p>\n\n<pre><code>def anotherfunc(h):\n def func(): return h\n return func()\n</code></pre>\n\n<p>Because here, <code>func</code> is defined in <code>anotherfunc</code>, and in python 2.3 and greater (or some number like this) when they <i>almost</i> got closures correct (mutation still doesn't work), this means that it <b>closes over</b> <code>anotherfunc</code>'s environment and can access variables inside of it. In Python 3.1+, mutation works too when using <a href=\"http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal\" rel=\"noreferrer\">the <code>nonlocal</code> keyword</a>.</p>\n\n<p>Another important point - <code>func</code> will continue to close over <code>anotherfunc</code>'s environment even when it's no longer being evaluated in <code>anotherfunc</code>. This code will also work:</p>\n\n<pre><code>def anotherfunc(h):\n def func(): return h\n return func\n\nprint anotherfunc(10)()\n</code></pre>\n\n<p>This will print 10.</p>\n\n<p>This, as you notice, has nothing to do with <b>lambda</b>s - they are two different (although related) concepts.</p>\n"
},
{
"answer_id": 22493714,
"author": "Wei Qiu",
"author_id": 1854834,
"author_profile": "https://Stackoverflow.com/users/1854834",
"pm_score": 4,
"selected": false,
"text": "<p>From the view of programming languages, they are completely two different things.</p>\n\n<p>Basically for a Turing complete language we only needs very limited elements, e.g. abstraction, application and reduction. Abstraction and application provides the way you can build up lamdba expression, and reduction dertermines the meaning of the lambda expression.</p>\n\n<p>Lambda provides a way you can abstract the computation process out. \nfor example, to compute the sum of two numbers, a process which takes two parameters x, y and returns x+y can be abstracted out. In scheme, you can write it as</p>\n\n<pre><code>(lambda (x y) (+ x y))\n</code></pre>\n\n<p>You can rename the parameters, but the task that it completes doesn't change. \nIn almost all of programming languages, you can give the lambda expression a name, which are named functions. But there is no much difference, they can be conceptually considered as just syntax sugar.</p>\n\n<p>OK, now imagine how this can be implemented. Whenever we apply the lambda expression to some expressions, e.g.</p>\n\n<pre><code>((lambda (x y) (+ x y)) 2 3)\n</code></pre>\n\n<p>We can simply substitute the parameters with the expression to be evaluated. This model is already very powerful.\nBut this model doesn't enable us to change the values of symbols, e.g. We can't mimic the change of status. Thus we need a more complex model. \nTo make it short, whenever we want to calculate the meaning of the lambda expression, we put the pair of symbol and the corresponding value into an environment(or table). Then the rest (+ x y) is evaluated by looking up the corresponding symbols in the table.\nNow if we provide some primitives to operate on the environment directly, we can model the changes of status!</p>\n\n<p>With this background, check this function:</p>\n\n<pre><code>(lambda (x y) (+ x y z))\n</code></pre>\n\n<p>We know that when we evaluate the lambda expression, x y will be bound in a new table. But how and where can we look z up? Actually z is called a free variable. There must be an outer \nan environment which contains z. Otherwise the meaning of the expression can't be determined by only binding x and y. To make this clear, you can write something as follows in scheme:</p>\n\n<pre><code>((lambda (z) (lambda (x y) (+ x y z))) 1)\n</code></pre>\n\n<p>So z would be bound to 1 in an outer table. We still get a function which accepts two parameters but the real meaning of it also depends on the outer environment.\nIn other words the outer environment closes on the free variables. With the help of set!, we can make the function stateful, i.e, it's not a function in the sense of maths. What it returns not only depends on the input, but z as well.</p>\n\n<p>This is something you already know very well, a method of objects almost always relies on the state of objects. That's why some people say \"closures are poor man's objects. \" But we could also consider objects as poor man's closures since we really like first class functions.</p>\n\n<p>I use scheme to illustrate the ideas due to that scheme is one of the earliest language which has real closures. All of the materials here are much better presented in SICP chapter 3.</p>\n\n<p>To sum up, lambda and closure are really different concepts. A lambda is a function. A closure is a pair of lambda and the corresponding environment which closes the lambda.</p>\n"
},
{
"answer_id": 22500157,
"author": "Andreas Rossberg",
"author_id": 1097780,
"author_profile": "https://Stackoverflow.com/users/1097780",
"pm_score": 4,
"selected": false,
"text": "<p>It's as simple as this: lambda is a language construct, i.e. simply syntax for anonymous functions; a closure is a technique to implement it -- or any first-class functions, for that matter, named or anonymous.</p>\n\n<p>More precisely, a closure is how a <a href=\"http://en.wikipedia.org/wiki/First-class_function\" rel=\"noreferrer\">first-class function</a> is represented at runtime, as a pair of its \"code\" and an environment \"closing\" over all the non-local variables used in that code. This way, those variables are still accessible even when the outer scopes where they originate have already been exited.</p>\n\n<p>Unfortunately, there are many languages out there that do not support functions as first-class values, or only support them in crippled form. So people often use the term \"closure\" to distinguish \"the real thing\".</p>\n"
},
{
"answer_id": 25053337,
"author": "Developer",
"author_id": 376702,
"author_profile": "https://Stackoverflow.com/users/376702",
"pm_score": 4,
"selected": false,
"text": "<p>Concept is same as described above, but if you are from PHP background, this further explain using PHP code. </p>\n\n<pre><code>$input = array(1, 2, 3, 4, 5);\n$output = array_filter($input, function ($v) { return $v > 2; });\n</code></pre>\n\n<p>function ($v) { return $v > 2; } is the lambda function definition. We can even store it in a variable, so it can be reusable:</p>\n\n<pre><code>$max = function ($v) { return $v > 2; };\n\n$input = array(1, 2, 3, 4, 5);\n$output = array_filter($input, $max);\n</code></pre>\n\n<p>Now, what if you want to change the maximum number allowed in the filtered array? You would have to write another lambda function or create a closure (PHP 5.3):</p>\n\n<pre><code>$max_comp = function ($max) {\n return function ($v) use ($max) { return $v > $max; };\n};\n\n$input = array(1, 2, 3, 4, 5);\n$output = array_filter($input, $max_comp(2));\n</code></pre>\n\n<p>A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called. They come from the functional programming world, where there are a number of concepts in play. Closures are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined.</p>\n\n<p>Here is a simpler example of PHP closure:</p>\n\n<pre><code>$string = \"Hello World!\";\n$closure = function() use ($string) { echo $string; };\n\n$closure();\n</code></pre>\n\n<p><a href=\"http://www.codeforest.net/anonymous-or-lambda-functions-in-php\" rel=\"noreferrer\">Nicely explained in this article.</a> </p>\n"
},
{
"answer_id": 26831209,
"author": "philippe lhardy",
"author_id": 1521926,
"author_profile": "https://Stackoverflow.com/users/1521926",
"pm_score": 3,
"selected": false,
"text": "<p>This question is old and got many answers.<br>\nNow with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.</p>\n\n<p>The answer in Java context (via <a href=\"http://www.lambdafaq.org/lambdas-and-closures-whats-the-difference/\" rel=\"nofollow noreferrer\">Lambdas and closures — what’s the difference?</a>):</p>\n\n<blockquote>\n <p>\"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community.\"</p>\n</blockquote>\n"
},
{
"answer_id": 30272814,
"author": "feilengcui008",
"author_id": 4322680,
"author_profile": "https://Stackoverflow.com/users/4322680",
"pm_score": 3,
"selected": false,
"text": "<p>Simply speaking, closure is a trick about scope, lambda is an anonymous function. We can realize closure with lambda more elegantly and lambda is often used as a parameter passed to a higher function</p>\n"
},
{
"answer_id": 36878651,
"author": "SasQ",
"author_id": 434562,
"author_profile": "https://Stackoverflow.com/users/434562",
"pm_score": 9,
"selected": false,
"text": "<p>There is a lot of confusion around lambdas and closures, even in the answers to this StackOverflow question here. Instead of asking random programmers who learned about closures from practice with certain programming languages or other clueless programmers, take a journey to the <em>source</em> (where it all began). And since lambdas and closures come from <strong>Lambda Calculus</strong> invented by Alonzo Church back in the '30s before first electronic computers even existed, this is the <em>source</em> I'm talking about.</p>\n\n<p>Lambda Calculus is the simplest programming language in the world. The only things you can do in it:►</p>\n\n<ul>\n<li>APPLICATION: Applying one expression to another, denoted <code>f x</code>.<br/>(Think of it as a <em>function call</em>, where <code>f</code> is the function and <code>x</code> is its only parameter)</li>\n<li>ABSTRACTION: Binds a symbol occurring in an expression to mark that this symbol is just a \"slot\", a blank box waiting to be filled with value, a \"variable\" as it were. It is done by prepending a Greek letter <code>λ</code> (lambda), then the symbolic name (e.g. <code>x</code>), then a dot <code>.</code> before the expression. This then converts the expression into a <em>function</em> expecting one <em>parameter</em>.<br/>For example: <code>λx.x+2</code> takes the expression <code>x+2</code> and tells that the symbol <code>x</code> in this expression is a <em>bound variable</em> – it can be substituted with a value you supply as a parameter.<br/>\nNote that the function defined this way is <em>anonymous</em> – it doesn't have a name, so you can't refer to it yet, but you can <em>immediately call</em> it (remember application?) by supplying it the parameter it is waiting for, like this: <code>(λx.x+2) 7</code>. Then the expression (in this case a literal value) <code>7</code> is substituted as <code>x</code> in the subexpression <code>x+2</code> of the applied lambda, so you get <code>7+2</code>, which then reduces to <code>9</code> by common arithmetics rules.</li>\n</ul>\n\n<p>So we've solved one of the mysteries:<br/>\n<strong>lambda</strong> is the <em>anonymous function</em> from the example above, <code>λx.x+2</code>.\n<hr/>\nIn different programming languages, the syntax for functional abstraction (lambda) may differ. For example, in JavaScript it looks like this:</p>\n\n<pre><code>function(x) { return x+2; }\n</code></pre>\n\n<p>and you can immediately apply it to some parameter like this:</p>\n\n<pre><code>(function(x) { return x+2; })(7)\n</code></pre>\n\n<p>or you can store this anonymous function (lambda) into some variable:</p>\n\n<pre><code>var f = function(x) { return x+2; }\n</code></pre>\n\n<p>which effectively gives it a name <code>f</code>, allowing you to refer to it and call it multiple times later, e.g.:</p>\n\n<pre><code>alert( f(7) + f(10) ); // should print 21 in the message box\n</code></pre>\n\n<p>But you didn't have to name it. You could call it immediately:</p>\n\n<pre><code>alert( function(x) { return x+2; } (7) ); // should print 9 in the message box\n</code></pre>\n\n<p>In LISP, lambdas are made like this:</p>\n\n<pre><code>(lambda (x) (+ x 2))\n</code></pre>\n\n<p>and you can call such a lambda by applying it immediately to a parameter:</p>\n\n<pre><code>( (lambda (x) (+ x 2)) 7 )\n</code></pre>\n\n<p><hr/>\nOK, now it's time to solve the other mystery: what is a <em>closure</em>.\nIn order to do that, let's talk about <em>symbols</em> (<em>variables</em>) in lambda expressions.</p>\n\n<p>As I said, what the lambda abstraction does is <em>binding</em> a symbol in its subexpression, so that it becomes a substitutible <em>parameter</em>. Such a symbol is called <em>bound</em>. But what if there are other symbols in the expression? For example: <code>λx.x/y+2</code>. In this expression, the symbol <code>x</code> is bound by the lambda abstraction <code>λx.</code> preceding it. But the other symbol, <code>y</code>, is not bound – it is <em>free</em>. We don't know what it is and where it comes from, so we don't know what it <em>means</em> and what <em>value</em> it represents, and therefore we cannot evaluate that expression until we figure out what <code>y</code> means.</p>\n\n<p>In fact, the same goes with the other two symbols, <code>2</code> and <code>+</code>. It's just that we are so familiar with these two symbols that we usually forget that the computer doesn't know them and we need to tell it what they mean by defining them somewhere, e.g. in a library or the language itself.</p>\n\n<p>You can think of the <em>free</em> symbols as defined somewhere else, outside the expression, in its \"surrounding context\", which is called its <strong>environment</strong>. The environment might be a bigger expression that this expression is a part of (as Qui-Gon Jinn said: \"There's always a bigger fish\" ;) ), or in some library, or in the language itself (as a <em>primitive</em>).</p>\n\n<p>This lets us divide lambda expressions into two categories:</p>\n\n<ul>\n<li>CLOSED expressions: every symbol that occurs in these expressions is <em>bound</em> by some lambda abstraction. In other words, they are <em>self-contained</em>; they don't require any surrounding context to be evaluated. They are also called <em>combinators</em>.</li>\n<li>OPEN expressions: some symbols in these expressions are not <em>bound</em> – that is, some of the symbols occurring in them are <em>free</em> and they require some external information, and thus they cannot be evaluated until you supply the definitions of these symbols.</li>\n</ul>\n\n<p>You can CLOSE an <em>open</em> lambda expression by supplying the <strong>environment</strong>, which defines all these free symbols by binding them to some values (which may be numbers, strings, anonymous functions aka lambdas, whatever…).</p>\n\n<p>And here comes the <em>closure</em> part:<br/>\nThe <strong>closure</strong> of a <em>lambda expression</em> is this particular set of symbols defined in the outer context (environment) that give values to the <em>free symbols</em> in this expression, making them non-free anymore. It turns an <em>open</em> lambda expression, which still contains some \"undefined\" free symbols, into a <em>closed</em> one, which doesn't have any free symbols anymore.</p>\n\n<p>For example, if you have the following lambda expression: <code>λx.x/y+2</code>, the symbol <code>x</code> is bound, while the symbol <code>y</code> is free, therefore the expression is <code>open</code> and cannot be evaluated unless you say what <code>y</code> means (and the same with <code>+</code> and <code>2</code>, which are also free). But suppose that you also have an <em>environment</em> like this:</p>\n\n<pre><code>{ y: 3,\n+: [built-in addition],\n2: [built-in number],\nq: 42,\nw: 5 }\n</code></pre>\n\n<p>This <em>environment</em> supplies definitions for all the \"undefined\" (free) symbols from our lambda expression (<code>y</code>, <code>+</code>, <code>2</code>), and several extra symbols (<code>q</code>, <code>w</code>). The symbols that we need to be defined are this subset of the environment:</p>\n\n<pre><code>{ y: 3,\n+: [built-in addition],\n2: [built-in number] }\n</code></pre>\n\n<p>and this is precisely the <em>closure</em> of our lambda expression :></p>\n\n<p>In other words, it <em>closes</em> an open lambda expression. This is where the name <em>closure</em> came from in the first place, and this is why so many people's answers in this thread are not quite correct :P\n<hr/>\nSo why are they mistaken? Why do so many of them say that closures are some data structures in memory, or some features of the languages they use, or why do they confuse closures with lambdas? :P</p>\n\n<p>Well, the corporate marketoids of Sun/Oracle, Microsoft, Google etc. are to blame, because that's what they called these constructs in their languages (Java, C#, Go etc.). They often call \"closures\" what are supposed to be just lambdas. Or they call \"closures\" a particular technique they used to implement lexical scoping, that is, the fact that a function can access the variables that were defined in its outer scope at the time of its definition. They often say that the function \"encloses\" these variables, that is, captures them into some data structure to save them from being destroyed after the outer function finishes executing. But this is just made-up <em>post factum</em> \"folklore etymology\" and marketing, which only makes things more confusing, because every language vendor uses its own terminology.</p>\n\n<p>And it's even worse because of the fact that there's always a bit of truth in what they say, which does not allow you to easily dismiss it as false :P Let me explain:</p>\n\n<p>If you want to implement a language that uses lambdas as first-class citizens, you need to allow them to use symbols defined in their surrounding context (that is, to use free variables in your lambdas). And these symbols must be there even when the surrounding function returns. The problem is that these symbols are bound to some local storage of the function (usually on the call stack), which won't be there anymore when the function returns. Therefore, in order for a lambda to work the way you expect, you need to somehow \"capture\" all these free variables from its outer context and save them for later, even when the outer context will be gone. That is, you need to find the <em>closure</em> of your lambda (all these external variables it uses) and store it somewhere else (either by making a copy, or by preparing space for them upfront, somewhere else than on the stack). The actual method you use to achieve this goal is an \"implementation detail\" of your language. What's important here is the <em>closure</em>, which is the set of <em>free variables</em> from the <em>environment</em> of your lambda that need to be saved somewhere.</p>\n\n<p>It didn't took too long for people to start calling the actual data structure they use in their language's implementations to implement closure as the \"closure\" itself. The structure usually looks something like this:</p>\n\n<pre><code>Closure {\n [pointer to the lambda function's machine code],\n [pointer to the lambda function's environment]\n}\n</code></pre>\n\n<p>and these data structures are being passed around as parameters to other functions, returned from functions, and stored in variables, to represent lambdas, and allowing them to access their enclosing environment as well as the machine code to run in that context. But it's just a way (one of many) to <em>implement</em> closure, not <em>the</em> closure itself.</p>\n\n<p>As I explained above, the closure of a lambda expression is the subset of definitions in its environment that give values to the free variables contained in that lambda expression, effectively <em>closing</em> the expression (turning an <em>open</em> lambda expression, which cannot be evaluated yet, into a <em>closed</em> lambda expression, which can then be evaluated, since all the symbols contained in it are now defined).</p>\n\n<p>Anything else is just a \"cargo cult\" and \"voo-doo magic\" of programmers and language vendors unaware of the real roots of these notions.</p>\n\n<p>I hope that answers your questions. But if you had any follow-up questions, feel free to ask them in the comments, and I'll try to explain it better.</p>\n"
},
{
"answer_id": 52476401,
"author": "DIPANSHU GOYAL",
"author_id": 4853061,
"author_profile": "https://Stackoverflow.com/users/4853061",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on whether a function uses external variable or not to perform operation. </p>\n\n<p><strong>External variables</strong> - variables defined outside the scope of a function.</p>\n\n<ul>\n<li><p>Lambda expressions are <strong>stateless</strong> because It depends on parameters, internal variables or constants to perform operations.</p>\n\n<pre><code>Function<Integer,Integer> lambda = t -> {\n int n = 2\n return t * n \n}\n</code></pre></li>\n<li><p>Closures <strong>hold state</strong> because it uses external variables (i.e. variable defined outside the scope of the function body) along with parameters and constants to perform operations.</p>\n\n<pre><code>int n = 2\n\nFunction<Integer,Integer> closure = t -> {\n return t * n \n}\n</code></pre></li>\n</ul>\n\n<p>When Java creates closure, it keeps the variable n with the function so it can be referenced when passed to other functions or used anywhere.</p>\n"
},
{
"answer_id": 55680389,
"author": "j2emanue",
"author_id": 835883,
"author_profile": "https://Stackoverflow.com/users/835883",
"pm_score": 3,
"selected": false,
"text": "<p>A Lambda expression is just an anonymous function. in plain java, for example, you can write it like this:</p>\n\n<pre><code>Function<Person, Job> mapPersonToJob = new Function<Person, Job>() {\n public Job apply(Person person) {\n Job job = new Job(person.getPersonId(), person.getJobDescription());\n return job;\n }\n};\n</code></pre>\n\n<p>where the class Function is just built in java code. Now you can call <code>mapPersonToJob.apply(person)</code> somewhere to use it. thats just one example. Thats a lambda before there was syntax for it. Lambdas a short cut for this. </p>\n\n<p>Closure:</p>\n\n<p>a Lambda becomes a closure when it can access the variables outside of this scope. i guess you can say its magic, it magically can wrap around the environment it was created in and use the variables outside of its scope(outer scope. so to be clear, a closure means a lambda can access its OUTER SCOPE. </p>\n\n<p>in Kotlin, a lambda can always access its closure (the variables that are in its outer scope)</p>\n"
},
{
"answer_id": 66426148,
"author": "ap-osd",
"author_id": 3209308,
"author_profile": "https://Stackoverflow.com/users/3209308",
"pm_score": 0,
"selected": false,
"text": "<p>Lambda is an anonymous function <em>definition</em> that is not (necessarily) bound to an identifier.</p>\n<blockquote>\n<p>"Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus, in which all functions are anonymous" - <a href=\"https://en.wikipedia.org/wiki/Anonymous_function\" rel=\"nofollow noreferrer\">Wikipedia</a></p>\n</blockquote>\n<p>Closure is the lambda function implementation.</p>\n<blockquote>\n<p>"Peter J. Landin defined the term closure in 1964 as having an environment part and a control part as used by his SECD machine for evaluating expressions" - <a href=\"https://en.wikipedia.org/wiki/Closure_(computer_programming)#History_and_etymology\" rel=\"nofollow noreferrer\">Wikipedia</a></p>\n</blockquote>\n<p>The generic explanation of Lambda and Closure is covered in the other responses.</p>\n<p>For those from a C++ background, Lambda expressions were introduced in C++11. Think of Lambdas as a convenient way to create anonymous functions and function objects.</p>\n<blockquote>\n<p>"The distinction between a lambda and the corresponding closure is precisely equivalent to the distinction between a class and an instance of the class. A class exists only in source code; it doesn’t exist at runtime. What exists at runtime are objects of the class type. Closures are to lambdas as objects are to classes. This should not be a surprise, because each lambda expression causes a unique class to be generated (during compilation) and also causes an object of that class type, a closure to be created (at runtime)." - <a href=\"http://scottmeyers.blogspot.com/2013/05/lambdas-vs-closures.html\" rel=\"nofollow noreferrer\">Scott Myers</a></p>\n</blockquote>\n<p>C++ allows us to examine the nuances of Lambda and Closure as you have to explicitly specify the free variables to be captured.</p>\n<p>In the sample below, the Lambda expression has no free variables, an empty capture list (<code>[]</code>). It’s essentially an ordinary function and no closure is required in the strictest sense. So it can even be passed as a function pointer argument.</p>\n<pre><code>void register_func(void(*f)(int val)) // Works only with an EMPTY capture list\n{\n int val = 3;\n f(val);\n}\n \nint main() \n{\n int env = 5;\n register_func( [](int val){ /* lambda body can access only val variable*/ } );\n}\n</code></pre>\n<p>As soon as a free variable from the surrounding environment is introduced in the capture list (<code>[env]</code>), a Closure has to be generated.</p>\n<pre><code> register_func( [env](int val){ /* lambda body can access val and env variables*/ } );\n</code></pre>\n<p>Since this is no longer an ordinary function, but a closure instead, it produces a compilation error.<br />\n<code>no suitable conversion function from "lambda []void (int val)->void" to "void (*)(int val)" exists</code></p>\n<p>The error can be fixed with a function wrapper <code>std::function</code> which accepts any callable target including a generated closure.</p>\n<pre><code>void register_func(std::function<void(int val)> f)\n</code></pre>\n<p>See <a href=\"https://cognitivewaves.wordpress.com/lambda-and-closure/\" rel=\"nofollow noreferrer\">Lambda and Closure</a> for a detailed explanation with a C++ example.</p>\n"
},
{
"answer_id": 66663532,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Lambda vs Closure</strong></p>\n<p><code>Lambda</code> is <strong>anonymous</strong> function(method)</p>\n<p><code>Closure</code> is function which <strong>closes over</strong>(capture) variables from its enclosing scope(e.g. non-local variables)</p>\n<p>Java</p>\n<pre><code>interface Runnable {\n void run();\n}\n\nclass MyClass {\n void foo(Runnable r) {\n\n }\n\n //Lambda\n void lambdaExample() {\n foo(() -> {});\n }\n\n //Closure\n String s = "hello";\n void closureExample() {\n foo(() -> { s = "world";});\n }\n}\n</code></pre>\n<p>Swift<a href=\"https://stackoverflow.com/questions/24133879/what-are-the-differences-between-functions-and-methods-in-swift/60988242#60988242\"><sup>[Closure]</sup></a></p>\n<pre><code>class MyClass {\n func foo(r:() -> Void) {}\n \n func lambdaExample() {\n foo(r: {})\n }\n \n var s = "hello"\n func closureExample() {\n foo(r: {s = "world"})\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68880250,
"author": "mtmrv",
"author_id": 9310187,
"author_profile": "https://Stackoverflow.com/users/9310187",
"pm_score": 2,
"selected": false,
"text": "<p>The question is 12 years old and we still get it as the first link in Google for “closures vs lambda”.\nSo I have to say it as no one did explicitly.</p>\n<p>Lambda expression is an anonymous function (declaration).</p>\n<p>And a closure, quoting <strong>Scott's Programming Language Pragmatics</strong> is explained as:</p>\n<blockquote>\n<p>… creating an explicit representation of a referencing environment (generally the one in which the subroutine would execute if called at the present time) and bundling it together with a reference to the subroutine … is referred to as a <strong>closure</strong>.</p>\n</blockquote>\n<p>That is, it is just as we call <em>the bundle</em> of “function + surrendering context”.</p>\n"
},
{
"answer_id": 70879701,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 2,
"selected": false,
"text": "<p>There are many noises of technically vague or "not even wrong" artificial pearls in various existing answers to this question, so I'd finally add a new one...</p>\n<h1>Clarification on the terminology</h1>\n<p>It is better to know, the terms "closure" and "lambda" can both denote different things, contextually dependently.</p>\n<p>This is a formal issue because the specification of the PL (programming language) being discussed may define such terms explicitly.</p>\n<p>For example, by ISO C++ (since C++11):</p>\n<blockquote>\n<p>The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.</p>\n</blockquote>\n<p>As users of C-like languages are daily confusing with "pointers" (types) to "pointer values" or "pointer objects" (inhabitants of types), there are risks to getting confused here, too: most C++ users are actually talking about "closure objects" by using the term "closure". Be cautious to the ambiguity.</p>\n<p><strong>NOTE</strong> To make things generally clearer and more precise, I'd seldom deliberately use some language-neutral terms (usually specific to the <a href=\"https://en.wikipedia.org/wiki/Programming_language_theory\" rel=\"nofollow noreferrer\">PL theory</a> instead of the language-defined terminology. For instance, <a href=\"https://en.wikipedia.org/wiki/Type_inhabitation\" rel=\"nofollow noreferrer\">type inhabitant</a> used above covers the language-specific "(r)values" and "lvalues" in a broader sense. (Since the syntactic essence of C++'s <em>value category</em> definition is irrelevant, avoiding "(l/r)values" may reduce confusion). (Disclaimer: lvalues and rvalues are <a href=\"https://en.wikipedia.org/wiki/Value_%28computer_science%29#lrvalue\" rel=\"nofollow noreferrer\">common</a> enough in many other contexts.) Terms not defined formally among different PLs may be in quotes. Verbatim copy from referenced materials may be also in quotes, with typos unchanged.</p>\n<p>This is even more relevant to "lambda". The (small case) letter lambda (λ) is an element of the Greek alphabet. By compared with "lambda" and "closure", one is certainly not talking about the letter itself, but something behind the syntax using "lambda"-derived concepts.</p>\n<p>The relevant constructs in modern PLs are usually named as "lambda expressions". And it is derived from the "lambda abstractions", discussed below.</p>\n<p>Before the detailed discussions, I recommend reading some comments of the question itself. I feel they safer and more helpful than most answers of the question here, in the sense of less risks of getting confused. (Sadly, this is the most significant reason I decide to provide an answer here...)</p>\n<h1>Lambdas: a brief history</h1>\n<p>The constructs named of "lambda" in PLs, whatever "lambda expression" or something others, are <em>syntactic</em>. In other words, users of the languages can find such <em>source language constructs</em> which are used to build something others. Roughly, the "others" are just "anonymous functions" in practice.</p>\n<p>Such constructs are originated from <em>lambda abstractions</em>, one of the three syntax categories ("kinds of expressions") of the <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"nofollow noreferrer\">(untyped) lambda calculus</a> developed by A. Church.</p>\n<p>Lambda calculus is a deducing system (more precisely, a <a href=\"https://en.wikipedia.org/wiki/Rewriting#Term_rewriting_systems\" rel=\"nofollow noreferrer\">TRS (term rewrite system)</a>) to model computation universally. To reduce a of lambda term is just like to evaluate an expression in normal PLs. With the built-in reduction rules, it is sufficient to define the various ways to compute. (As you may know, <a href=\"https://en.wikipedia.org/wiki/Church%E2%80%93Turing_thesis\" rel=\"nofollow noreferrer\">it is Turing-complete</a>.) Hence, it can be used as a PL.</p>\n<p><strong>NOTE</strong> Evaluating an expression in a PL is not interchangable to reducing a term in a TRS in general. However, lambda calculus is a language with all reduction results expressible within the source language (i.e. as lambda terms), so they have same meaning coincidentally. Almost all PLs in practice do not have this property; the calculus to describe their semantics may contain terms not being the source lanugage expressions, and reductions may have more detailed effects than evaluations.</p>\n<p>Every terms ("expressions") in the lambda calculus (lambda terms) are either variable, abstraction or application. "Variable" here is the syntax (just the variable's name) of symbol, which can refer to an existing "variable" (semantically, an entity which may reduce to some other lambda term) introduced previously. The ability to introduce a variable is provided by the abstraction syntax, which has a leading letter λ, followed by a <em>bound variable</em>, a dot and a lambda term. The bound variable is similar to the formal parameter name both in the syntax and semantic among many languages, and the followed lambda term inside the lambda abstraction is just like the function body. The application syntax combines a lambda term ("actual argument") to some abstraction, like the function call expression in many PLs.</p>\n<p><strong>NOTE</strong> A lambda abstraction can introduce only one parameter. To overcome the limitation inside the calculus, see <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"nofollow noreferrer\">Currying</a>.</p>\n<p>The ability of introducing variables makes lambda calculus a typical high-level language (albeit simple). On the other hand, <a href=\"https://en.wikipedia.org/wiki/Combinatory_logic\" rel=\"nofollow noreferrer\">combinatory logics</a> can be treated as PLs by remove away the variable and abstraction features from the lambda calculus. Combinatory logics are low-level exactly in this sense: they are like plain-old assembly languages which do not allow to introduce variables named by the user (despite macros, which requires additional preprocessing). (... If not more low-level... typically assembly languages can at least introduce user-named labels.)</p>\n<p>Noticing the lambda abstraction can be built in-place inside any other lambda terms, without the need to specify a name to denote the abstraction. So, the lambda abstraction in a whole forms the anonymous function (probably nested). This is a quite high-level feature (compared to, e.g. ISO C, which does not allow anonymous or nested functions).</p>\n<p>The successor of the untyped lambda calculus include various typed lambda calculi (like the <a href=\"https://en.wikipedia.org/wiki/Lambda_cube\" rel=\"nofollow noreferrer\">lambda cube</a>). These are more like statically typed languages which requires type annotations on the formal parameters of functions. Nevertheless, the lambda abstractions still have the same roles here.</p>\n<p>Although lambda calculi are not intended to be directly used as PLs implemented in computers, they do have affected PLs in practice. Notably, J. McCarthy introduced the <code>LAMBDA</code> operator in LISP to provide functions exactly following the idea of Church's untyped lambda calculus. Apparently, the name <code>LAMBDA</code> comes from the letter λ. LISP (later) has a different syntax (<a href=\"https://en.wikipedia.org/wiki/S-expression\" rel=\"nofollow noreferrer\">S-expression</a>), but all programmable elements in the <code>LAMBDA</code> expressions can be directly mapped to the lambda abstractions in the untyped lambda calculus by trivial syntactic conversions.</p>\n<p>On the other hand, many other PLs express similar functionalities by other means. A slightly different way to introduce reusable computations are named functions (or more exactly, named subroutines), which are supported by earlier PLs like FORTRAN, and languages derived from ALGOL. They are introduced by syntaxes specifying a named entity being a function at the same time. This is simpler in some sense compared to LISP dialects (esp. in the aspect of implementation), and it seems more popular than LISP dialects for decades. Named functions may also allow extensions not shared by anonymous functions like function overloading.</p>\n<p>Nevertheless, more and more industrial programmers finally find the usefulness of <a href=\"https://en.wikipedia.org/wiki/First-class_function\" rel=\"nofollow noreferrer\">first-class functions</a>, and demands of the ability to introduce function definitions in-place (in the expressions in the arbitrary contexts, say, as an argument of some other function) are increasing. It is natural and legitimate to avoid naming a thing not required to be, and any named functions fail here by definition. (You may know, <a href=\"https://skeptics.stackexchange.com/questions/19836\">naming things correctly is one of the well-known hard problems in the computer science</a>.) To address the problem, anonymous functions are introduced to languages traditionally only providing named functions (or function-like constructs like "methods", whatsoever), like C++ and Java. Many of them name the feature as "lambda expressions" or similar lambda things, because they are basically reflecting the essentially same idea in lambda calculi. <em>Renaissance.</em></p>\n<p>A bit disambiguity: in the lambda calculus, all terms (variables, abstractions and applications) are effectively expressions in a PL; they are all "lambda expressions" in this sense. However, PLs adding lambda abstraction to enrich their features may speficially name the syntax of the abstraction as the "lambda expression", to distinguish with existing other kinds of expressions.</p>\n<h1>Closures: the history</h1>\n<p><a href=\"https://en.wikipedia.org/wiki/Closure_%28mathematics%29\" rel=\"nofollow noreferrer\">Closures in mathematics</a> is not the same to <a href=\"https://en.wikipedia.org/wiki/Closure_%28computer_programming%29\" rel=\"nofollow noreferrer\">it in PLs</a>.</p>\n<p>In the latter context, the term <a href=\"https://www.cs.kent.ac.uk/people/staff/dat/tfp12/tfp12.pdf\" rel=\"nofollow noreferrer\">is coined by P. J. Landin in 1964</a>, to providing the support of the first-class functions in the implementation of evaluating the PLs "modelled in Church's λ-notation".</p>\n<p>Specific to the model proposed by Landin (the <a href=\"https://en.wikipedia.org/wiki/SECD_machine\" rel=\"nofollow noreferrer\">SECD machine</a>), <a href=\"https://www.cs.cmu.edu/%7Ecrary/819-f09/Landin64.pdf\" rel=\"nofollow noreferrer\">a closure is comprising the λ-expression and the environment relative to which it was evaluated</a>, or more precisely:</p>\n<blockquote>\n<p>an environment part which is a list whose two items are (1) an environment (2) an identifier of list of identifiers</p>\n</blockquote>\n<blockquote>\n<p>and a control part which consists of a list whose sole item is an AE</p>\n</blockquote>\n<p><strong>NOTE</strong> <em>AE</em> is abbreviated for <em>applicative expression</em> in the paper. This is the syntax exposing more or less the same functionality of application in the lambda calculus. There are also some additional pieces of details like <a href=\"https://en.wikipedia.org/wiki/Evaluation_strategy#Strict_evaluation\" rel=\"nofollow noreferrer\">"applicative"</a> not that interesting in the lambda calculus (because it is purely functional), though. SECD is not consistent with the original lambda calculus for these minor differences. For example, SECD halts on arbitrary single lambda abstraction whether the subterm ("body") has a normal form, because it will not reduce the subterm ("evaluate the body") without the abstraction has been applied ("called"). However, such behavior may be more like the PLs today than the lambda calculus. SECD is also not the only abstract machine can evaluate lambda terms; although most other abstract machines for the similar purpose may also have environments. Contrast to the lambda calculus (which is pure), these abstract machines can support mutation in some degrees.</p>\n<p>So, in this specific context, a closure is an internal data structure to implement specific evaluations of PLs with AEs.</p>\n<p>The discipline of accessing the variables in closures reflects <a href=\"https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scope\" rel=\"nofollow noreferrer\">lexical scoping</a>, first used in early 1960s by the imperative language ALGOL 60. ALGOL 60 does support nested procedures and passing procedures to parameters, but not returning procedures as results. For languages has full support of first-class functions which can be returned by functions, the static chain in ALGOL 60-style implementations does not work because free variables used by the function being returned may be no longer present on the call stack. This is the <a href=\"https://en.wikipedia.org/wiki/Funarg_problem#Upwards_funarg_problem\" rel=\"nofollow noreferrer\">upwards funarg problem</a>. Closures resolve the problem by capturing the free variable in the environment parts and avoiding allocating them on the stack.</p>\n<p>On the other hand, early LISP implementations all use dynamic scope. This makes the variable bindings referenced all reachable in the global store, and name hiding (if any) is implemented as per-variable basis: once a variable is created with an existing name, the old one is backed by a LIFO structure; in other words, each variable's name can access a corresponding global stack. This effectively cancels the need of the per-function environments because no free variables are ever captured in the function (they are already "captured" by the stacks).</p>\n<p>Despite imitating the lambda notation at the first, LISP is very different to the lambda calculus here. The lambda calculus is <em>statically scoped</em>. That is, each variable denotes to the instance bounded by the nearest same named-formal parameter of a lambda abstraction which contains the variable before its reduction. In the semantics of lambda calculus, reducing an application substitute the term ("argument") to the bound variable ("formal parameter") in the abstraction. Since all values can be represented as lambda terms in the lambda calculus, this can be done by direct rewriting by replacing specific subterms in each step of the reducing.</p>\n<p><strong>NOTE</strong> So, environments are not essential to reduce the lambda terms. However, a calculus extending the lambda calculus can introduce the environments explicitly in the grammar, even when it only models pure computations (without mutation). By adding environments explicitly, there can be dedicated rules of constraints on the environments to enforce environment normalizations which strengthens the equational theory of the calculus. (See <a href=\"https://web.wpi.edu/Pubs/ETD/Available/etd-090110-124904/unrestricted/jshutt.pdf\" rel=\"nofollow noreferrer\">[Shu10]</a> §9.1.)</p>\n<p>LISP is quite different, because its underlying semantic rules are based on neither lambda calculus nor term rewriting. Therefore, LISP needs some different mechanism to maintaining the scoping discipline. It adopted the mechanism based on the environment data structures saving the variable to value mappings (i.e. variable bindings). There may be more sophisticated structure in an environment in new variants of LISP (e.g. lexically scoped Lisp allows mutations), but the simplest structure conceptually equivalent to the environment defined by the Landin's paper, discussed below.</p>\n<p>LISP implementations do support first-class functions at the very early era, but with pure dynamic scoping, there is no real funargs problem: they can just avoid the allocations on the stack and letting a global owner (the GC, garbage collector) to manage the resources in the environments (and activation records) referencing the variables. Closures are not needed then. And this is the early implementations prior to the invention of closures do.</p>\n<p><em>Deep binding</em> which approximates static (lexical) binding was introduced around 1962 in LISP 1.5, via the <code>FUNARG</code> device. This finally made the problem well-known under the name "funarg problem".</p>\n<p><strong>NOTE</strong> <a href=\"https://dspace.mit.edu/bitstream/handle/1721.1/5854/AIM-199.pdf\" rel=\"nofollow noreferrer\">AIM-199</a> points out that this is essentially about the environments.</p>\n<p>Scheme is <a href=\"https://en.wikipedia.org/wiki/History_of_the_Scheme_programming_language#Influence\" rel=\"nofollow noreferrer\">the first</a> Lisp dialect <a href=\"https://en.wikipedia.org/wiki/Scheme_%28programming_language%29#Lexical_scope\" rel=\"nofollow noreferrer\">supporting lexical scoping</a> by default (dynamic scope can be simulated by <code>make-parameter</code>/<code>parameterize</code> forms in modern versions of Scheme). There were some debates in a later decade, but finally most Lisp dialects adopt the idea to default to lexical scoping, as many other languages do. Since then, closure, as an implementation technique, are more widely spread and more popular among PLs of different flavors.</p>\n<h2>Closures: the evolution</h2>\n<p>The original paper of Landin first defines an environment being a mathematical function mapping the name ("constant") to the named object ("primitive"). Then, it specifies the environment as "a list-structure made up of name/value pairs". The latter is also implemented in early Lisp implementation as <em>alist</em>s (associative lists), but modern language implementations do not necessarily follow such detail. In particular, environments can be <em>linked</em> to support nested closures, which is unlikely directly supported by abstract machines like SECD.</p>\n<p>Besides the environment, the other component of the "environment part" in Landin's paper is used to keep the names of bound variable(s) of the lambda abstractions (the formal parameter(s) of the functions). This is also optional (and likely missing) for modern implementations where the names of the parameters can be statically optimized away (spiritually granted by the alpha-renaming rules of lambda calculi), when there is no need to reflect the source information.</p>\n<p>Similarly, modern implementations may not save the syntactic constructs (AEs or lambda terms) directly as the control part. Instead, they may use some internal IR (intermediate representation) or the "compiled" form (e.g. FASL used by some implementations of Lisp dialects). Such IR is even not guaranteed to be generated from <code>lambda</code> forms (e.g. it can come from the body of some named functions).</p>\n<p>Moreover, the the environment part can save other information not for the evaluation for the lambda calculi. For example, <a href=\"https://web.wpi.edu/Pubs/ETD/Available/etd-090110-124904/unrestricted/jshutt.pdf\" rel=\"nofollow noreferrer\">it can keep an extra identifier to provide additional binding naming the environment at the call site</a>. This can implement languages based on extensions of lambda calculi.</p>\n<h2>Revisit of PL-specific terminology</h2>\n<p>Further, some languages may define "closure"-related terms in their specification to name entities may be implemented by closures. This is unfortunate because it leads to many misconceptions like "a closure is a function". But fortunately enough, most languages seem to avoid to name it directly as a syntactic construct in the language.</p>\n<p>Nevertheless, this is still better than the overloading more well-established common concepts arbitrary by language specifications. To name a few:</p>\n<ul>\n<li><p>"objects" are redirected to "instance of classes" (in <a href=\"https://docs.oracle.com/javase/specs/jls/se17/html/index.html\" rel=\"nofollow noreferrer\">Java</a>/CLR/"OOP" languages) instead of <a href=\"https://www.ics.uci.edu/%7Ejajones/INF102-S18/readings/05_stratchey_1967.pdf\" rel=\"nofollow noreferrer\">traditional</a> "typed storage" (in C and <a href=\"http://www.eel.is/c++draft/\" rel=\"nofollow noreferrer\">C++</a>) or just "values" (in many Lisps);</p>\n</li>\n<li><p>"variables" are redirected to something traditional called "objects" (in <a href=\"https://go.dev/ref/spec\" rel=\"nofollow noreferrer\">Golang</a>) as well as mutable states (in many new languages), so it is no longer compatible to mathematics and pure functional languages;</p>\n</li>\n<li><p>"polymorphism" is restricted to <a href=\"https://en.wikipedia.org/wiki/Inclusion_polymorphism\" rel=\"nofollow noreferrer\">inclusion polymorphism</a> (in C++/"OOP" languages) even these languages do have other kinds of polymorphism (parametric polymorphism and ad-hoc polymorphism).</p>\n</li>\n</ul>\n<h2>About the resource mangagement</h2>\n<p>Despite the components being ommited in modern implementations, the definitions in Landin's paper are fairly flexible. It does not limits how to store the components like the environments out of the contexts of SECD machine.</p>\n<p>In practice, various strategies are used. The most common and traditional way is making all resources owned by a global owner which can collect the resources not any longer in use, i.e. the (global) GC, first used in the LISP.</p>\n<p>Other ways may not need a global owner and have better locality to the closures, for example:</p>\n<ul>\n<li><p>In C++, resources of entities captured in closures are allowed being managed explicitly by users, by specifying how to capture each variable in the lambda-expression's capture list (by value copy, by reference, or even by an explicit initializer) and the exact type of each variable (smart pointers or other types). This can be unsafe, but it gains more flexibility when used correctly.</p>\n</li>\n<li><p>In Rust, resources are captured with different capture modes (by immutable borrow, by borrow, by move) tried in turn (by the implementation), and users can specify explicit <code>move</code>. This is more conservative than C++, but safer in some sense (since borrows are statically checked, compared to unchecked by-reference captures in C++).</p>\n</li>\n</ul>\n<p>All the strategies above can support closures (C++ and Rust do have the language-specific definitions of the concept "closure type"). The disciplines to manage the resources used by the closures have nothing to do of the qualification of the closures.</p>\n<p>So, (although not seen here,) <a href=\"http://lambda-the-ultimate.org/node/5007#comment-81721\" rel=\"nofollow noreferrer\">the claim of the necessity of graph tracing for closures by Thomas Lord at LtU</a> is also technically incorrect. Closures can solve the funarg problem because it allows preventing invalid accesses to the activation record (the stack), but the fact does not magically assert every operations on the resources comprising the closure <em>will</em> be valid. Such mechanism depend on the external execution environment. It should be clear, even in traditional implementations, the implicit owner (GC) is not a component <em>in</em> the closures, and the existence of the owner is the implementation detail of SECD machine (so it is one of the "high-order" details to the users). Whether such detail supports graph tracing or not has no effects on the qualification of closures. Besides, AFAIK, <a href=\"https://www.cs.kent.ac.uk/people/staff/dat/tfp12/tfp12.pdf\" rel=\"nofollow noreferrer\">the language constructs <code>let</code> combined with <code>rec</code> is first introduced (again by P. Landin) in ISWIM in 1966</a>, which could not have effects to enforce the original meaning of the closures invented earlier than itself.</p>\n<h1>The relationships</h1>\n<p>So, to sum them up, a closure can be (informally) defined as:</p>\n<p>(1) a PL implementation-specific data structure comprising as an environment part and a control part for a function-like entity, where:</p>\n<p>(1.1) the control part is derived from some source language constructs specifying the evaluation construct of the function-like entity;</p>\n<p>(1.2) the environment part is comprised by an environment and optionally other implementation-defined data;</p>\n<p>(1.3) the environment in (1.2) is determined by the potentially context-dependent source language constructs of the function-like entity, used to hold the captured free variables occurs in the evaluation construct of the source language constructs creating the function-like entity.</p>\n<p>(2) alternatively, the umbrella term of an implementation technique to utilize the entities named "closures" in (1).</p>\n<p>Lambda expressions (abstractions) are just <em>one of</em> the syntactic constructs in the source language to introduce (to create) unnamed function-like entities. A PL may provide it as the only way introduce the function-like entity.</p>\n<p>In general, there are no definite correspondence between lambda expressions in the source program and the existence of the closures in the execution of the program. As implementation details having no effects on the observable behavior of the program, a PL implementation is usually allowed to merge resources allocated for closures when possible, or totally omitting creating them when it does not matter on the program semantics:</p>\n<ul>\n<li><p>The implementation can check the set of the free variables to be captured in the lambda expression, and when the set is empty, it can avoid introducing the environment part, so the function-like entity will not require a closure to be maintained. Such strategy is usually mandated in the rules of static languages.</p>\n</li>\n<li><p>Otherwise, the implementation may or may not always create a closure for a function-like entity resulted by evaluating the lambda expression whether there are variables to be captured.</p>\n</li>\n</ul>\n<p>Lambda expressions may be evaluates to the function-like entity. Users of some PLs may call such a function-like entity a "closure". "Anonymous function" should be a more neutral name of such "closure" in this context.</p>\n<h1>Appendix: functions: the messy history</h1>\n<p>This is not directly tied to the problem, but it may also worth noting "functions" can name different entities in different contexts.</p>\n<p>It is already <a href=\"https://en.wikipedia.org/wiki/History_of_the_function_concept\" rel=\"nofollow noreferrer\">a mess in mathematics</a>.</p>\n<p>Currently I am too lazy to sum them up in the contexts of PLs, but as a caveat: keep an eye on the context to make sure the various definitions of "function" in different PLs not making your reasoning biased from the topic.</p>\n<p>As of the use "anonymous functions" in general (shared by PLs in practice), I believe it will not introduce significant confusions and misconceptions on this topic, though.</p>\n<p>Named functions may have a slightly more problems. Functions may denote the entity of the name themselves (the "symbols"), as well as the evaluated values of these names. Given that the fact that most PLs don't have unevaluated context to differentiate a function with some other entities carrying interesting meaning (e.g. <code>sizeof(a_plain_cxx_function)</code> in C++ just ill-formed), users may not observe the differences of the misinterpretation between unevaluated operand and evaluated values. That will be problematic with some Lisp dialects having <code>QUOTE</code>. <a href=\"https://eighty-twenty.org/2011/09/29/fexprs-remain-inscrutable#comment-418744898\" rel=\"nofollow noreferrer\">Even experienced PL specialists can easily miss something important</a>; this is also why I emphasize to distinguish syntactic constructs with other entities.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9776/"
] |
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.
And now that we're here, how do they differ from a regular function?
|
A **lambda** is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.
A **closure** is any function which **closes over** the **environment** in which it was defined. This means that it can access variables not in its parameter list. Examples:
```
def func(): return h
def anotherfunc(h):
return func()
```
This will cause an error, because `func` does not **close over** the environment in `anotherfunc` - `h` is undefined. `func` only closes over the global environment. This will work:
```
def anotherfunc(h):
def func(): return h
return func()
```
Because here, `func` is defined in `anotherfunc`, and in python 2.3 and greater (or some number like this) when they *almost* got closures correct (mutation still doesn't work), this means that it **closes over** `anotherfunc`'s environment and can access variables inside of it. In Python 3.1+, mutation works too when using [the `nonlocal` keyword](http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal).
Another important point - `func` will continue to close over `anotherfunc`'s environment even when it's no longer being evaluated in `anotherfunc`. This code will also work:
```
def anotherfunc(h):
def func(): return h
return func
print anotherfunc(10)()
```
This will print 10.
This, as you notice, has nothing to do with **lambda**s - they are two different (although related) concepts.
|
220,718 |
<p>I am trying to use <code>set.insert (key)</code> as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:</p>
<pre><code>if (set.insert( key )) {
// some kind of code
}
</code></pre>
<p>Is this allowed? Because the compiler is throwing this error: </p>
<pre><code>conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
</code></pre>
|
[
{
"answer_id": 220721,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 2,
"selected": false,
"text": "<p>set::insert returns a pair, try this:</p>\n\n<pre><code>if( set.insert( key ).second ) {\n // some kind of code\n}\n</code></pre>\n"
},
{
"answer_id": 220722,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": true,
"text": "<p>The version of insert that takes a single key value should return a <code>std::pair<iterator,bool></code>, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this:</p>\n\n<pre><code>if( set.insert( key ).second ) {\n // code\n}\n</code></pre>\n"
},
{
"answer_id": 222894,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 1,
"selected": false,
"text": "<p>Other answers have suggested just using '.second', and this will work - but if the processing that you need to perform uses the existing entry in the set, then you can store the full result of the insert:</p>\n\n<pre><code>std::pair<std::set<key>::iterator, bool> iResult = set.insert (key);\nif (iResult.second) {\n // some kind of code - insert took place\n}\nelse {\n // some kind of code using iResult.first, which\n // is an iterator to the previous entry in the set.\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29326/"
] |
I am trying to use `set.insert (key)` as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:
```
if (set.insert( key )) {
// some kind of code
}
```
Is this allowed? Because the compiler is throwing this error:
```
conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
```
|
The version of insert that takes a single key value should return a `std::pair<iterator,bool>`, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this:
```
if( set.insert( key ).second ) {
// code
}
```
|
220,719 |
<p>I have an application that detects if there is another instance of the app running and exits if one is found. This part seems to work reliably. My app takes a command-line argument that I would like to pass to the already running instance. I have the following code so far:</p>
<h2>Project1.dpr</h2>
<pre><code>program Project1;
uses
...
AppInstanceControl in 'AppInstanceControl.pas';
if not AppInstanceControl.RestoreIfRunning(Application.Handle) then
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end;
end.
</code></pre>
<h2>AppInstanceControl.pas</h2>
<p>{ Based on code by Zarko Gajic found at <a href="http://delphi.about.com/library/code/ncaa100703a.htm" rel="noreferrer">http://delphi.about.com/library/code/ncaa100703a.htm</a>}</p>
<pre><code>unit AppInstanceControl;
interface
uses
Windows,
SysUtils;
function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean;
implementation
uses
Messages;
type
PInstanceInfo = ^TInstanceInfo;
TInstanceInfo = packed record
PreviousHandle: THandle;
RunCounter: integer;
end;
var
UMappingHandle: THandle;
UInstanceInfo: PInstanceInfo;
UMappingName: string;
URemoveMe: boolean = True;
function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean;
var
LCopyDataStruct : TCopyDataStruct;
begin
Result := True;
UMappingName := StringReplace(
ParamStr(0),
'\',
'',
[rfReplaceAll, rfIgnoreCase]);
UMappingHandle := CreateFileMapping($FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(TInstanceInfo),
PChar(UMappingName));
if UMappingHandle = 0 then
RaiseLastOSError
else
begin
if GetLastError <> ERROR_ALREADY_EXISTS then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
UInstanceInfo^.PreviousHandle := AAppHandle;
UInstanceInfo^.RunCounter := 1;
Result := False;
end
else //already runing
begin
UMappingHandle := OpenFileMapping(
FILE_MAP_ALL_ACCESS,
False,
PChar(UMappingName));
if UMappingHandle <> 0 then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
if UInstanceInfo^.RunCounter >= AMaxInstances then
begin
URemoveMe := False;
if IsIconic(UInstanceInfo^.PreviousHandle) then
ShowWindow(UInstanceInfo^.PreviousHandle, SW_RESTORE);
SetForegroundWindow(UInstanceInfo^.PreviousHandle);
end
else
begin
UInstanceInfo^.PreviousHandle := AAppHandle;
UInstanceInfo^.RunCounter := 1 + UInstanceInfo^.RunCounter;
Result := False;
end
end;
end;
end;
if (Result) and (CommandLineParam <> '') then
begin
LCopyDataStruct.dwData := 0; //string
LCopyDataStruct.cbData := 1 + Length(CommandLineParam);
LCopyDataStruct.lpData := PChar(CommandLineParam);
SendMessage(UInstanceInfo^.PreviousHandle, WM_COPYDATA, Integer(AAppHandle), Integer(@LCopyDataStruct));
end;
end; (*RestoreIfRunning*)
initialization
finalization
//remove this instance
if URemoveMe then
begin
UMappingHandle := OpenFileMapping(
FILE_MAP_ALL_ACCESS,
False,
PChar(UMappingName));
if UMappingHandle <> 0 then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
UInstanceInfo^.RunCounter := -1 + UInstanceInfo^.RunCounter;
end
else
RaiseLastOSError;
end;
if Assigned(UInstanceInfo) then UnmapViewOfFile(UInstanceInfo);
if UMappingHandle <> 0 then CloseHandle(UMappingHandle);
end.
</code></pre>
<h2>and in the main form unit:</h2>
<pre><code>procedure TFormMain.WMCopyData(var Msg: TWMCopyData);
var
LMsgString: string;
begin
Assert(Msg.CopyDataStruct.dwData = 0);
LMsgString := PChar(Msg.CopyDataStruct.lpData);
//do stuff with the received string
end;
</code></pre>
<p>I'm pretty sure the problem is that I'm trying to send the message to the handle of the running app instance but trying to process the message on the main form. I'm thinking I have two options here:</p>
<p>A) From the application's handle somehow get the handle of its main form and send the message there.</p>
<p>B) Handle receiving the message at the application rather than the main form level.</p>
<p>I'm not really sure how to go about either. Is there a better approach?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 220739,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you use DDE?\nTake a look at the links returned by this search: <a href=\"http://www.google.com/search?q=delphi+dde\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=delphi+dde</a></p>\n"
},
{
"answer_id": 220852,
"author": "Tim Knipe",
"author_id": 10493,
"author_profile": "https://Stackoverflow.com/users/10493",
"pm_score": 4,
"selected": false,
"text": "<p>You don't need to create a file mapping if you use WM_COPYDATA. That's the whole point of WM_COPYDATA - it does all that for you.</p>\n\n<p>To send a string</p>\n\n<pre><code>procedure IPCSendMessage(target: HWND; const message: string);\nvar\n cds: TCopyDataStruct;\nbegin\n cds.dwData := 0;\n cds.cbData := Length(message) * SizeOf(Char);\n cds.lpData := Pointer(@message[1]);\n\n SendMessage(target, WM_COPYDATA, 0, LPARAM(@cds));\nend;\n</code></pre>\n\n<p>To receive a string</p>\n\n<pre><code>procedure TForm1.WMCopyData(var msg: TWMCopyData);\nvar\n message: string;\nbegin\n SetLength(message, msg.CopyDataStruct.cbData div SizeOf(Char));\n Move(msg.CopyDataStruct.lpData^, message[1], msg.CopyDataStruct.cbData);\n\n // do something with the message e.g.\n Edit1.Text := message;\nend;\n</code></pre>\n\n<p>Modify as needed to send other data. </p>\n"
},
{
"answer_id": 221263,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "<p>It turns out that this is really hard to do reliably. I just spent two hours trying to get all the glitches out of a five-minute solution :( Seems to be working now, though.</p>\n\n<p>The code below works in D2007 both with new-style (MainFormOnTaskbar = True) and old-style approach. Therefore, I believe it will also work in older Delphi version. It was tested with the application in minimized and normal state.</p>\n\n<p>Test project is available at <a href=\"http://17slon.com/krama/ReActivate.zip\" rel=\"nofollow noreferrer\">http://17slon.com/krama/ReActivate.zip</a> (less than 3 KB).</p>\n\n<p>For online reading, indexing purposes and backup, all important units are attached below.</p>\n\n<h3>Main program</h3>\n\n<pre><code>program ReActivate;\n\nuses\n Forms,\n GpReActivator, \n raMain in 'raMain.pas' {frmReActivate};\n\n{$R *.res}\n\nbegin\n if ReactivateApplication(TfrmReActivate, WM_REACTIVATE) then\n Exit;\n\n Application.Initialize;\n Application.MainFormOnTaskbar := True;\n// Application.MainFormOnTaskbar := False;\n Application.CreateForm(TfrmReActivate, frmReActivate);\n Application.Run;\nend.\n</code></pre>\n\n<h3>Main unit</h3>\n\n<pre><code>unit raMain;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs;\n\nconst\n WM_REACTIVATE = WM_APP;\n\ntype\n TfrmReActivate = class(TForm)\n private\n public\n procedure ReActivate(var msg: TMessage); message WM_REACTIVATE;\n end;\n\nvar\n frmReActivate: TfrmReActivate;\n\nimplementation\n\n{$R *.dfm}\n\nuses\n GpReactivator;\n\n{ TfrmReActivate }\n\nprocedure TfrmReActivate.ReActivate(var msg: TMessage);\nbegin\n GpReactivator.Activate;\nend; \n\nend.\n</code></pre>\n\n<h3>Helper unit</h3>\n\n<pre><code>unit GpReActivator;\n\ninterface\n\nuses\n Classes;\n\nprocedure Activate;\nfunction ReActivateApplication(mainFormClass: TComponentClass; reactivateMsg: cardinal):\n boolean;\n\nimplementation\n\nuses\n Windows,\n Messages,\n SysUtils,\n Forms;\n\ntype\n TProcWndInfo = record\n ThreadID : DWORD;\n MainFormClass: TComponentClass;\n FoundWindow : HWND;\n end; { TProcWndInfo }\n PProcWndInfo = ^TProcWndInfo;\n\nvar\n fileMapping : THandle;\n fileMappingResult: integer;\n\nfunction ForceForegroundWindow(hwnd: THandle): boolean;\nvar\n foregroundThreadID: DWORD;\n thisThreadID : DWORD;\n timeout : DWORD;\nbegin\n if GetForegroundWindow = hwnd then\n Result := true\n else begin\n\n // Windows 98/2000 doesn't want to foreground a window when some other\n // window has keyboard focus\n\n if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or\n ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and\n ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and (Win32MinorVersion > 0)))) then\n begin\n\n // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm\n // Converted to Delphi by Ray Lischner\n // Published in The Delphi Magazine 55, page 16\n\n Result := false;\n foregroundThreadID := GetWindowThreadProcessID(GetForegroundWindow,nil);\n thisThreadID := GetWindowThreadPRocessId(hwnd,nil);\n if AttachThreadInput(thisThreadID, foregroundThreadID, true) then begin\n BringWindowToTop(hwnd); //IE 5.5 - related hack\n SetForegroundWindow(hwnd);\n AttachThreadInput(thisThreadID, foregroundThreadID, false);\n Result := (GetForegroundWindow = hwnd);\n end;\n if not Result then begin\n\n // Code by Daniel P. Stasinski <[email protected]>\n\n SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE);\n BringWindowToTop(hwnd); //IE 5.5 - related hack\n SetForegroundWindow(hWnd);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE);\n end;\n end\n else begin\n BringWindowToTop(hwnd); //IE 5.5 - related hack\n SetForegroundWindow(hwnd);\n end;\n\n Result := (GetForegroundWindow = hwnd);\n end;\nend; { ForceForegroundWindow }\n\nprocedure Activate;\nbegin\n if (Application.MainFormOnTaskBar and (Application.MainForm.WindowState = wsMinimized))\n or\n ((not Application.MainFormOnTaskBar) and (not IsWindowVisible(Application.MainForm.Handle)))\n then\n Application.Restore\n else\n Application.BringToFront;\n ForceForegroundWindow(Application.MainForm.Handle);\nend; { Activate }\n\nfunction IsTopDelphiWindow(wnd: HWND): boolean;\nvar\n parentWnd: HWND;\n winClass : array [0..1024] of char;\nbegin\n parentWnd := GetWindowLong(wnd, GWL_HWNDPARENT);\n Result :=\n (parentWnd = 0)\n or\n (GetWindowLong(parentWnd, GWL_HWNDPARENT) = 0) and\n (GetClassName(parentWnd, winClass, SizeOf(winClass)) <> 0) and\n (winClass = 'TApplication');\nend; { IsTopDelphiWindow }\n\nfunction EnumGetProcessWindow(wnd: HWND; userParam: LPARAM): BOOL; stdcall;\nvar\n procWndInfo: PProcWndInfo;\n winClass : array [0..1024] of char;\nbegin\n procWndInfo := PProcWndInfo(userParam);\n if (GetWindowThreadProcessId(wnd, nil) = procWndInfo.ThreadID) and\n (GetClassName(wnd, winClass, SizeOf(winClass)) <> 0) and\n IsTopDelphiWindow(wnd) and\n (string(winClass) = procWndInfo.MainFormClass.ClassName) then\n begin\n procWndInfo.FoundWindow := Wnd;\n Result := false;\n end\n else\n Result := true;\nend; { EnumGetProcessWindow }\n\nfunction GetThreadWindow(threadID: cardinal; mainFormClass: TComponentClass): HWND;\nvar\n procWndInfo: TProcWndInfo;\nbegin\n procWndInfo.ThreadID := threadID;\n procWndInfo.MainFormClass := mainFormClass;\n procWndInfo.FoundWindow := 0;\n EnumWindows(@EnumGetProcessWindow, LPARAM(@procWndInfo));\n Result := procWndInfo.FoundWindow;\nend; { GetThreadWindow }\n\nfunction ReActivateApplication(mainFormClass: TComponentClass; reactivateMsg: cardinal):\n boolean;\nvar\n mappingData: PDWORD;\nbegin\n Result := false;\n if fileMappingResult = NO_ERROR then begin // first owner\n mappingData := MapViewOfFile(fileMapping, FILE_MAP_WRITE, 0, 0, SizeOf(DWORD));\n Win32Check(assigned(mappingData));\n mappingData^ := GetCurrentThreadID;\n UnmapViewOfFile(mappingData);\n end\n else if fileMappingResult = ERROR_ALREADY_EXISTS then begin // app already started\n mappingData := MapViewOfFile(fileMapping, FILE_MAP_READ, 0, 0, SizeOf(DWORD));\n if mappingData^ <> 0 then begin // 0 = race condition\n PostMessage(GetThreadWindow(mappingData^, mainFormClass), reactivateMsg, 0, 0);\n Result := true;\n end;\n UnmapViewOfFile(mappingData);\n Exit;\n end\n else\n RaiseLastWin32Error;\nend; { ReActivateApplication }\n\ninitialization\n fileMapping := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0,\n SizeOf(DWORD), PChar(StringReplace(ParamStr(0), '\\', '', [rfReplaceAll, rfIgnoreCase])));\n Win32Check(fileMapping <> 0);\n fileMappingResult := GetLastError;\nfinalization\n if fileMapping <> 0 then\n CloseHandle(fileMapping);\nend.\n</code></pre>\n\n<p>All code is released to public domain and can be used without and licencing considerations.</p>\n"
},
{
"answer_id": 224549,
"author": "lukeck",
"author_id": 2189521,
"author_profile": "https://Stackoverflow.com/users/2189521",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up saving the MainForm's handle into the InstanceInfo record in the file mapping then sending the message to the previous instance's main form handle if there was one.</p>\n\n<p>In the project dpr:</p>\n\n<pre><code> if not AppInstanceControl.RestoreIfRunning(Application.Handle) then\n begin\n Application.Initialize;\n Application.MainFormOnTaskbar := True;\n Application.CreateForm(TFormMain, FormMain);\n SetRunningInstanceMainFormHandle(FormMain.Handle);\n Application.Run;\n end else\n SendMsgToRunningInstanceMainForm('Message string goes here');\n</code></pre>\n\n<h2>AppInstanceControl.pas</h2>\n\n<pre><code>type\n PInstanceInfo = ^TInstanceInfo;\n TInstanceInfo = packed record\n PreviousHandle: THandle;\n PreviousMainFormHandle: THandle;\n RunCounter: integer;\n end;\n\nprocedure SetRunningInstanceMainFormHandle(const AMainFormHandle: THandle);\nbegin\n UMappingHandle := OpenFileMapping(\n FILE_MAP_ALL_ACCESS,\n False,\n PChar(UMappingName));\n if UMappingHandle <> 0 then\n begin\n UInstanceInfo := MapViewOfFile(UMappingHandle,\n FILE_MAP_ALL_ACCESS,\n 0,\n 0,\n SizeOf(TInstanceInfo));\n\n UInstanceInfo^.PreviousMainFormHandle := AMainFormHandle;\n end;\nend;\n\nprocedure SendMsgToRunningInstanceMainForm(const AMsg: string);\nvar\n LCopyDataStruct : TCopyDataStruct;\nbegin\n UMappingHandle := OpenFileMapping(\n FILE_MAP_ALL_ACCESS,\n False,\n PChar(UMappingName));\n if UMappingHandle <> 0 then\n begin\n UInstanceInfo := MapViewOfFile(UMappingHandle,\n FILE_MAP_ALL_ACCESS,\n 0,\n 0,\n SizeOf(TInstanceInfo));\n\n\n LCopyDataStruct.dwData := 0; //string\n LCopyDataStruct.cbData := 1 + Length(AMsg);\n LCopyDataStruct.lpData := PChar(AMsg);\n\n SendMessage(UInstanceInfo^.PreviousMainFormHandle, WM_COPYDATA, Integer(Application.Handle), Integer(@LCopyDataStruct));\n end;\nend;\n</code></pre>\n\n<p>This seems to work reliably. I was going to post full source but I'd like to incorporate some of gabr's code that looks like it much more reliably sets focus to the running instance first.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189521/"
] |
I have an application that detects if there is another instance of the app running and exits if one is found. This part seems to work reliably. My app takes a command-line argument that I would like to pass to the already running instance. I have the following code so far:
Project1.dpr
------------
```
program Project1;
uses
...
AppInstanceControl in 'AppInstanceControl.pas';
if not AppInstanceControl.RestoreIfRunning(Application.Handle) then
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end;
end.
```
AppInstanceControl.pas
----------------------
{ Based on code by Zarko Gajic found at <http://delphi.about.com/library/code/ncaa100703a.htm>}
```
unit AppInstanceControl;
interface
uses
Windows,
SysUtils;
function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean;
implementation
uses
Messages;
type
PInstanceInfo = ^TInstanceInfo;
TInstanceInfo = packed record
PreviousHandle: THandle;
RunCounter: integer;
end;
var
UMappingHandle: THandle;
UInstanceInfo: PInstanceInfo;
UMappingName: string;
URemoveMe: boolean = True;
function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean;
var
LCopyDataStruct : TCopyDataStruct;
begin
Result := True;
UMappingName := StringReplace(
ParamStr(0),
'\',
'',
[rfReplaceAll, rfIgnoreCase]);
UMappingHandle := CreateFileMapping($FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(TInstanceInfo),
PChar(UMappingName));
if UMappingHandle = 0 then
RaiseLastOSError
else
begin
if GetLastError <> ERROR_ALREADY_EXISTS then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
UInstanceInfo^.PreviousHandle := AAppHandle;
UInstanceInfo^.RunCounter := 1;
Result := False;
end
else //already runing
begin
UMappingHandle := OpenFileMapping(
FILE_MAP_ALL_ACCESS,
False,
PChar(UMappingName));
if UMappingHandle <> 0 then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
if UInstanceInfo^.RunCounter >= AMaxInstances then
begin
URemoveMe := False;
if IsIconic(UInstanceInfo^.PreviousHandle) then
ShowWindow(UInstanceInfo^.PreviousHandle, SW_RESTORE);
SetForegroundWindow(UInstanceInfo^.PreviousHandle);
end
else
begin
UInstanceInfo^.PreviousHandle := AAppHandle;
UInstanceInfo^.RunCounter := 1 + UInstanceInfo^.RunCounter;
Result := False;
end
end;
end;
end;
if (Result) and (CommandLineParam <> '') then
begin
LCopyDataStruct.dwData := 0; //string
LCopyDataStruct.cbData := 1 + Length(CommandLineParam);
LCopyDataStruct.lpData := PChar(CommandLineParam);
SendMessage(UInstanceInfo^.PreviousHandle, WM_COPYDATA, Integer(AAppHandle), Integer(@LCopyDataStruct));
end;
end; (*RestoreIfRunning*)
initialization
finalization
//remove this instance
if URemoveMe then
begin
UMappingHandle := OpenFileMapping(
FILE_MAP_ALL_ACCESS,
False,
PChar(UMappingName));
if UMappingHandle <> 0 then
begin
UInstanceInfo := MapViewOfFile(UMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
UInstanceInfo^.RunCounter := -1 + UInstanceInfo^.RunCounter;
end
else
RaiseLastOSError;
end;
if Assigned(UInstanceInfo) then UnmapViewOfFile(UInstanceInfo);
if UMappingHandle <> 0 then CloseHandle(UMappingHandle);
end.
```
and in the main form unit:
--------------------------
```
procedure TFormMain.WMCopyData(var Msg: TWMCopyData);
var
LMsgString: string;
begin
Assert(Msg.CopyDataStruct.dwData = 0);
LMsgString := PChar(Msg.CopyDataStruct.lpData);
//do stuff with the received string
end;
```
I'm pretty sure the problem is that I'm trying to send the message to the handle of the running app instance but trying to process the message on the main form. I'm thinking I have two options here:
A) From the application's handle somehow get the handle of its main form and send the message there.
B) Handle receiving the message at the application rather than the main form level.
I'm not really sure how to go about either. Is there a better approach?
Thanks.
|
You don't need to create a file mapping if you use WM\_COPYDATA. That's the whole point of WM\_COPYDATA - it does all that for you.
To send a string
```
procedure IPCSendMessage(target: HWND; const message: string);
var
cds: TCopyDataStruct;
begin
cds.dwData := 0;
cds.cbData := Length(message) * SizeOf(Char);
cds.lpData := Pointer(@message[1]);
SendMessage(target, WM_COPYDATA, 0, LPARAM(@cds));
end;
```
To receive a string
```
procedure TForm1.WMCopyData(var msg: TWMCopyData);
var
message: string;
begin
SetLength(message, msg.CopyDataStruct.cbData div SizeOf(Char));
Move(msg.CopyDataStruct.lpData^, message[1], msg.CopyDataStruct.cbData);
// do something with the message e.g.
Edit1.Text := message;
end;
```
Modify as needed to send other data.
|
220,747 |
<p>I have three related tables "A(id, val)", "B(id, val)", and a link table with a value "AB(aid, bid, val)"</p>
<p>I am querying against B to bring back A values, for example:</p>
<pre><code>SELECT A.*
FROM A INNER JOIN AB ON A.id = AB.aid INNER JOIN B ON AB.bid = B.id
WHERE B.val = 'foo';
</code></pre>
<p>Every A has many B's and every B has many A's.</p>
<p>And the catch that I'm falling apart on is the need to filter the set so that the query returns rows only when AB.val is a max for any given A/B pair</p>
<p>E.g. if I have the data:</p>
<h2>A</h2>
<pre><code>id val
1 something
2 somethingelse
</code></pre>
<h2>B</h2>
<pre><code>id val
1 foo
2 bar
</code></pre>
<h2>AB</h2>
<pre><code>aid bid val
1 1 3
1 2 2
2 1 1
2 2 4
</code></pre>
<p>I would want to select only the first and last rows of AB since they are the max values for each of the A's and then be able to query against B.val = 'foo' to return only the first row. I don't have a clue on how I can constrain against only the max val row in the AB table.</p>
<p>The best I've been able to get is</p>
<pre><code>SELECT *
FROM A
INNER JOIN
(SELECT aid, bid, MAX(val) AS val FROM AB GROUP BY aid) as AB
ON A.id = AB.aid
INNER JOIN B ON AB.id = B.id
WHERE B.val = 'foo'
</code></pre>
<p>but this doesn't quite work. First, it just feels to be the wrong approach, second, it returns bad bid values. That is, the bid returned from the subquery is not necessarily from the same row as the max(val). I believe this is a known group by issue where selection of values to return when the column is not specified for either collation or grouping is undefined.</p>
<p>I hope that some of the above makes sense, I've been banging my head against a wall for the past few hours over this and any help at all would be hugely appreciated. Thanks.</p>
<p>(For those wondering, the actual use of this is for a Dictionary backend where A is the Word Table and B is the Phoneme Table. AB is the WordPhoneme table with a 'position' column. The query is to find all words that end with a specified phoneme. (a phoneme is a word sound, similar in usage to the international phonetic alphabet )</p>
|
[
{
"answer_id": 220798,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to do another join to get ab's max val for each a.id first.</p>\n\n<p>Something like this:</p>\n\n<pre><code>select a.*\nfrom a\nleft join (\n select aid, max(val) as val \n from ab \n group by aid\n) abmax on abmax.aid=a.id\ninner join ab on ab.aid=abmax.aid and ab.val=abmax.val\ninner join b on b.id=ab.bid\nwhere b.val='foo'\n</code></pre>\n"
},
{
"answer_id": 220829,
"author": "patmortech",
"author_id": 19090,
"author_profile": "https://Stackoverflow.com/users/19090",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another way that I just tested out:</p>\n\n<pre><code>select a.*\nfrom ab\n inner join b on(ab.bid=b.id)\n inner join a on (ab.aid=a.id)\nwhere ab.val = (select max(val) from ab AS ab2 where ab2.aid = ab.aid)\n and b.val='foo'\n</code></pre>\n"
},
{
"answer_id": 220938,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>I often use the following trick to get the greatest per group:</p>\n\n<pre><code>SELECT a.*\nFROM ab AS ab1\n LEFT OUTER JOIN ab AS ab2 ON (ab1.aid = ab2.aid AND ab1.val < ab2.val)\n JOIN a ON (ab1.aid = a.id)\n JOIN b ON (ab1.bid = b.id)\nWHERE ab2.aid IS NULL\n AND b.val = 'foo';\n</code></pre>\n\n<p>The trick is to join to the AB table to itself in an outer join. Return ab1 where no rows exist with the same value for aid and a greater value for val. Therefore ab1 has the greatest val per group of rows with a given value for aid.</p>\n"
},
{
"answer_id": 221553,
"author": "MBoy",
"author_id": 15511,
"author_profile": "https://Stackoverflow.com/users/15511",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure which sql you are using but in MS SQL I create a table-valued database function to return the max values from table A then join this to table B. I find this much easier to understand than complex joins when I look back on my queries at a later stage. </p>\n"
},
{
"answer_id": 222057,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT *\nFROM\n(\n SELECT\n A.*,\n (SELECT top 1 AB.BID FROM AB WHERE A.AID = AB.AID ORDER BY AB.val desc) as BID\n FROM A\n) as Aplus\nJOIN B ON Aplus.BID = B.BID\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have three related tables "A(id, val)", "B(id, val)", and a link table with a value "AB(aid, bid, val)"
I am querying against B to bring back A values, for example:
```
SELECT A.*
FROM A INNER JOIN AB ON A.id = AB.aid INNER JOIN B ON AB.bid = B.id
WHERE B.val = 'foo';
```
Every A has many B's and every B has many A's.
And the catch that I'm falling apart on is the need to filter the set so that the query returns rows only when AB.val is a max for any given A/B pair
E.g. if I have the data:
A
-
```
id val
1 something
2 somethingelse
```
B
-
```
id val
1 foo
2 bar
```
AB
--
```
aid bid val
1 1 3
1 2 2
2 1 1
2 2 4
```
I would want to select only the first and last rows of AB since they are the max values for each of the A's and then be able to query against B.val = 'foo' to return only the first row. I don't have a clue on how I can constrain against only the max val row in the AB table.
The best I've been able to get is
```
SELECT *
FROM A
INNER JOIN
(SELECT aid, bid, MAX(val) AS val FROM AB GROUP BY aid) as AB
ON A.id = AB.aid
INNER JOIN B ON AB.id = B.id
WHERE B.val = 'foo'
```
but this doesn't quite work. First, it just feels to be the wrong approach, second, it returns bad bid values. That is, the bid returned from the subquery is not necessarily from the same row as the max(val). I believe this is a known group by issue where selection of values to return when the column is not specified for either collation or grouping is undefined.
I hope that some of the above makes sense, I've been banging my head against a wall for the past few hours over this and any help at all would be hugely appreciated. Thanks.
(For those wondering, the actual use of this is for a Dictionary backend where A is the Word Table and B is the Phoneme Table. AB is the WordPhoneme table with a 'position' column. The query is to find all words that end with a specified phoneme. (a phoneme is a word sound, similar in usage to the international phonetic alphabet )
|
I think you need to do another join to get ab's max val for each a.id first.
Something like this:
```
select a.*
from a
left join (
select aid, max(val) as val
from ab
group by aid
) abmax on abmax.aid=a.id
inner join ab on ab.aid=abmax.aid and ab.val=abmax.val
inner join b on b.id=ab.bid
where b.val='foo'
```
|
220,751 |
<p>I have a DataTable that has a boolean column called [Invalid]. I need to divide this data up by this Invalid column - valid rows can be edited, invalid rows cannot. My original plan was to use two BindingSources and set the Filter property ([Invalid] = 'false', for instance), which plays right into my hands because I have two DataGridViews and so I need two BindingSources anyway.</p>
<p>This doesn't work: the BindingSources set the Filter property associated with the DataTable, so both BindingSources hold the same data. Am I going to have to do two fetches from the database, or can I do what I want with the objects I have?</p>
|
[
{
"answer_id": 220798,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to do another join to get ab's max val for each a.id first.</p>\n\n<p>Something like this:</p>\n\n<pre><code>select a.*\nfrom a\nleft join (\n select aid, max(val) as val \n from ab \n group by aid\n) abmax on abmax.aid=a.id\ninner join ab on ab.aid=abmax.aid and ab.val=abmax.val\ninner join b on b.id=ab.bid\nwhere b.val='foo'\n</code></pre>\n"
},
{
"answer_id": 220829,
"author": "patmortech",
"author_id": 19090,
"author_profile": "https://Stackoverflow.com/users/19090",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another way that I just tested out:</p>\n\n<pre><code>select a.*\nfrom ab\n inner join b on(ab.bid=b.id)\n inner join a on (ab.aid=a.id)\nwhere ab.val = (select max(val) from ab AS ab2 where ab2.aid = ab.aid)\n and b.val='foo'\n</code></pre>\n"
},
{
"answer_id": 220938,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>I often use the following trick to get the greatest per group:</p>\n\n<pre><code>SELECT a.*\nFROM ab AS ab1\n LEFT OUTER JOIN ab AS ab2 ON (ab1.aid = ab2.aid AND ab1.val < ab2.val)\n JOIN a ON (ab1.aid = a.id)\n JOIN b ON (ab1.bid = b.id)\nWHERE ab2.aid IS NULL\n AND b.val = 'foo';\n</code></pre>\n\n<p>The trick is to join to the AB table to itself in an outer join. Return ab1 where no rows exist with the same value for aid and a greater value for val. Therefore ab1 has the greatest val per group of rows with a given value for aid.</p>\n"
},
{
"answer_id": 221553,
"author": "MBoy",
"author_id": 15511,
"author_profile": "https://Stackoverflow.com/users/15511",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure which sql you are using but in MS SQL I create a table-valued database function to return the max values from table A then join this to table B. I find this much easier to understand than complex joins when I look back on my queries at a later stage. </p>\n"
},
{
"answer_id": 222057,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT *\nFROM\n(\n SELECT\n A.*,\n (SELECT top 1 AB.BID FROM AB WHERE A.AID = AB.AID ORDER BY AB.val desc) as BID\n FROM A\n) as Aplus\nJOIN B ON Aplus.BID = B.BID\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133/"
] |
I have a DataTable that has a boolean column called [Invalid]. I need to divide this data up by this Invalid column - valid rows can be edited, invalid rows cannot. My original plan was to use two BindingSources and set the Filter property ([Invalid] = 'false', for instance), which plays right into my hands because I have two DataGridViews and so I need two BindingSources anyway.
This doesn't work: the BindingSources set the Filter property associated with the DataTable, so both BindingSources hold the same data. Am I going to have to do two fetches from the database, or can I do what I want with the objects I have?
|
I think you need to do another join to get ab's max val for each a.id first.
Something like this:
```
select a.*
from a
left join (
select aid, max(val) as val
from ab
group by aid
) abmax on abmax.aid=a.id
inner join ab on ab.aid=abmax.aid and ab.val=abmax.val
inner join b on b.id=ab.bid
where b.val='foo'
```
|
220,767 |
<p>How exactly do you make an auto-refreshing <code>div</code> with JavaScript (specifically, jQuery)?</p>
<p>I know about the <code>setTimeout</code> method, but is it really a good practice ? Is there a better method?</p>
<pre><code>function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
});
window.setTimeout("update();", 10000);
}
</code></pre>
|
[
{
"answer_id": 220774,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://plugins.jquery.com/project/Timer\" rel=\"nofollow noreferrer\">There's a jQuery Timer plugin</a> you may want to try</p>\n"
},
{
"answer_id": 220800,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 6,
"selected": true,
"text": "<p>Another modification:</p>\n\n<pre><code>function update() {\n $.get(\"response.php\", function(data) {\n $(\"#some_div\").html(data);\n window.setTimeout(update, 10000);\n });\n}\n</code></pre>\n\n<p>The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening. </p>\n\n<p>Also, if the server fails to respond, it won't keep trying. </p>\n\n<p>I've used a similar method in the past using .ajax to handle even more complex behaviour:</p>\n\n<pre><code>function update() {\n $(\"#notice_div\").html('Loading..'); \n $.ajax({\n type: 'GET',\n url: 'response.php',\n timeout: 2000,\n success: function(data) {\n $(\"#some_div\").html(data);\n $(\"#notice_div\").html(''); \n window.setTimeout(update, 10000);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#notice_div\").html('Timeout contacting server..');\n window.setTimeout(update, 60000);\n }\n}\n</code></pre>\n\n<p>This shows a loading message while loading (put an animated gif in there for typical \"web 2.0\" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.</p>\n\n<p>This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.</p>\n"
},
{
"answer_id": 5692861,
"author": "Faghani",
"author_id": 712021,
"author_profile": "https://Stackoverflow.com/users/712021",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function update() {\n $(\"#notice_div\").html('Loading..'); \n $.ajax({\n type: 'GET',\n url: 'jbede.php',\n timeout: 2000,\n success: function(data) {\n $(\"#some_div\").html(data);\n $(\"#notice_div\").html(''); \n window.setTimeout(update, 10000);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#notice_div\").html('Timeout contacting server..');\n window.setTimeout(update, 60000);\n }\n});\n}\n$(document).ready(function() {\n update();\n});\n</code></pre>\n\n<p>This is Better Code</p>\n"
},
{
"answer_id": 9261806,
"author": "Viktor Trón",
"author_id": 641672,
"author_profile": "https://Stackoverflow.com/users/641672",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(document).ready(function() {\n $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh\n setInterval(function() {\n $('#notice_div').load('response.php');\n }, 3000); // the \"3000\" \n});\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26721/"
] |
How exactly do you make an auto-refreshing `div` with JavaScript (specifically, jQuery)?
I know about the `setTimeout` method, but is it really a good practice ? Is there a better method?
```
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
});
window.setTimeout("update();", 10000);
}
```
|
Another modification:
```
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
```
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
```
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
```
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
|
220,772 |
<p>Before I explain what I'm trying to do, note that I have the good fortune of only having to target Webkit (meaning, I can use lots of neat CSS).</p>
<p>So, basically, I want to have a block with a flexible height, position fixed, maximum height being that of the available window height, with some elements at the top and bottom of the block that are always visible, and in the middle an area with overflow auto. Basically it'd look like this:</p>
<pre>
----------------------
| Top item | |
| | |
| stuff | |
| | |
| | |
| Last item | |
|------------ |
| |
| |
----------------------
----------------------
| Top item | |
|-----------| |
| lots |^| |
| of |_| |
| stuff |_| |
| | | |
| | | |
|-----------| |
| Last item | |
----------------------</pre>
<p>Can it be done with CSS? Or will I have to hack it with Javascript? I'd be willing to accept a little div-itis if that's what it takes to make this work—better div-itis than trying to account for every stupid little thing like reflow and window resize and all of that nonsense.</p>
<p>I'm prepared for the bad news that this isn't something CSS can do, but I've been pleasantly surprised by the magic some folks on SO can work before.</p>
|
[
{
"answer_id": 220774,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://plugins.jquery.com/project/Timer\" rel=\"nofollow noreferrer\">There's a jQuery Timer plugin</a> you may want to try</p>\n"
},
{
"answer_id": 220800,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 6,
"selected": true,
"text": "<p>Another modification:</p>\n\n<pre><code>function update() {\n $.get(\"response.php\", function(data) {\n $(\"#some_div\").html(data);\n window.setTimeout(update, 10000);\n });\n}\n</code></pre>\n\n<p>The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening. </p>\n\n<p>Also, if the server fails to respond, it won't keep trying. </p>\n\n<p>I've used a similar method in the past using .ajax to handle even more complex behaviour:</p>\n\n<pre><code>function update() {\n $(\"#notice_div\").html('Loading..'); \n $.ajax({\n type: 'GET',\n url: 'response.php',\n timeout: 2000,\n success: function(data) {\n $(\"#some_div\").html(data);\n $(\"#notice_div\").html(''); \n window.setTimeout(update, 10000);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#notice_div\").html('Timeout contacting server..');\n window.setTimeout(update, 60000);\n }\n}\n</code></pre>\n\n<p>This shows a loading message while loading (put an animated gif in there for typical \"web 2.0\" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.</p>\n\n<p>This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.</p>\n"
},
{
"answer_id": 5692861,
"author": "Faghani",
"author_id": 712021,
"author_profile": "https://Stackoverflow.com/users/712021",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function update() {\n $(\"#notice_div\").html('Loading..'); \n $.ajax({\n type: 'GET',\n url: 'jbede.php',\n timeout: 2000,\n success: function(data) {\n $(\"#some_div\").html(data);\n $(\"#notice_div\").html(''); \n window.setTimeout(update, 10000);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#notice_div\").html('Timeout contacting server..');\n window.setTimeout(update, 60000);\n }\n});\n}\n$(document).ready(function() {\n update();\n});\n</code></pre>\n\n<p>This is Better Code</p>\n"
},
{
"answer_id": 9261806,
"author": "Viktor Trón",
"author_id": 641672,
"author_profile": "https://Stackoverflow.com/users/641672",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(document).ready(function() {\n $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh\n setInterval(function() {\n $('#notice_div').load('response.php');\n }, 3000); // the \"3000\" \n});\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17964/"
] |
Before I explain what I'm trying to do, note that I have the good fortune of only having to target Webkit (meaning, I can use lots of neat CSS).
So, basically, I want to have a block with a flexible height, position fixed, maximum height being that of the available window height, with some elements at the top and bottom of the block that are always visible, and in the middle an area with overflow auto. Basically it'd look like this:
```
----------------------
| Top item | |
| | |
| stuff | |
| | |
| | |
| Last item | |
|------------ |
| |
| |
----------------------
----------------------
| Top item | |
|-----------| |
| lots |^| |
| of |_| |
| stuff |_| |
| | | |
| | | |
|-----------| |
| Last item | |
----------------------
```
Can it be done with CSS? Or will I have to hack it with Javascript? I'd be willing to accept a little div-itis if that's what it takes to make this work—better div-itis than trying to account for every stupid little thing like reflow and window resize and all of that nonsense.
I'm prepared for the bad news that this isn't something CSS can do, but I've been pleasantly surprised by the magic some folks on SO can work before.
|
Another modification:
```
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
```
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
```
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
```
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
|
220,777 |
<p>One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?</p>
|
[
{
"answer_id": 220830,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>If they're not being automatically detected, try manually copying them into py2exe's temporary build directory. They will be included in the final executable.</p>\n"
},
{
"answer_id": 220892,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>You can modify the setup script to copy the files explicitly:</p>\n\n<pre><code>script = \"PyInvaders.py\" #name of starting .PY\nproject_name = os.path.splitext(os.path.split(script)[1])[0]\nsetup(name=project_name, scripts=[script]) #this installs the program\n\n#also need to hand copy the extra files here\ndef installfile(name):\n dst = os.path.join('dist', project_name)\n print 'copying', name, '->', dst\n if os.path.isdir(name):\n dst = os.path.join(dst, name)\n if os.path.isdir(dst):\n shutil.rmtree(dst)\n shutil.copytree(name, dst)\n elif os.path.isfile(name):\n shutil.copy(name, dst)\n else:\n print 'Warning, %s not found' % name\n\npygamedir = os.path.split(pygame.base.__file__)[0]\ninstallfile(os.path.join(pygamedir, pygame.font.get_default_font()))\ninstallfile(os.path.join(pygamedir, 'pygame_icon.bmp'))\nfor data in extra_data:\n installfile(data)\n</code></pre>\n\n<p>etc... modify to suit your needs, of course.</p>\n"
},
{
"answer_id": 224154,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you could use the data_files option to setup():</p>\n\n<pre><code>import glob\nsetup(name='MyApp',\n # other options,\n data_files=[('.', glob.glob('*.dll')),\n ('.', glob.glob('*.pyd'))],\n )\n</code></pre>\n\n<p>data_files should be a list of tuples, where each tuple contains:</p>\n\n<ol>\n<li>The target directory.</li>\n<li>A list of files to copy.</li>\n</ol>\n\n<p>This won't put the files into library.zip, which shouldn't be a problem for dlls, but I don't know about pyd files.</p>\n"
},
{
"answer_id": 224274,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 4,
"selected": false,
"text": "<p>.pyd's and .DLL's are different here, in that a .pyd ought to be automatically found by modulefinder and so included (as long as you have the appropriate \"import\" statement) without needing to do anything. If one is missed, you do the same thing as if a .py file was missed (they're both just modules): use the \"include\" option for the py2exe options.</p>\n\n<p>Modulefinder will not necessarily find dependencies on .DLLs (py2exe can detect some), so you may need to explicitly include these, with the 'data_files' option.</p>\n\n<p>For example, where you had two .DLL's ('foo.dll' and 'bar.dll') to include, and three .pyd's ('module1.pyd', 'module2.pyd', and 'module3.pyd') to include:</p>\n\n<pre><code>setup(name='App',\n # other options,\n data_files=[('.', 'foo.dll'), ('.', 'bar.dll')],\n options = {\"py2exe\" : {\"includes\" : \"module1,module2,module3\"}}\n )\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20879/"
] |
One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude\_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?
|
.pyd's and .DLL's are different here, in that a .pyd ought to be automatically found by modulefinder and so included (as long as you have the appropriate "import" statement) without needing to do anything. If one is missed, you do the same thing as if a .py file was missed (they're both just modules): use the "include" option for the py2exe options.
Modulefinder will not necessarily find dependencies on .DLLs (py2exe can detect some), so you may need to explicitly include these, with the 'data\_files' option.
For example, where you had two .DLL's ('foo.dll' and 'bar.dll') to include, and three .pyd's ('module1.pyd', 'module2.pyd', and 'module3.pyd') to include:
```
setup(name='App',
# other options,
data_files=[('.', 'foo.dll'), ('.', 'bar.dll')],
options = {"py2exe" : {"includes" : "module1,module2,module3"}}
)
```
|
220,813 |
<p>I have several branches in TFS (dev, test, stage) and when I merge changes into the test branch I want the automated build and deploy script to find all the updated SQL files and deploy them to the test database.</p>
<p>I thought I could do this by finding all the changesets associated with the build since the last good build, finding all the sql files in the changesets and deploying them. However I don't seem to be having the changeset associated with the build for some reason so my question is twofold:</p>
<p>1) How do I ensure that a changeset is associated with a particular build?</p>
<p>2) How can I get a list of files that have changed in the branch since the last good build? I have the last successfully built build but I'm unsure how to get the files without checking the changesets (which as mentioned above are not associated with the build!)</p>
|
[
{
"answer_id": 229681,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 0,
"selected": false,
"text": "<p>So I can understand the intuitive appeal of this approach, but I don't think it's the right way to go.</p>\n\n<p>For one thing it's going to be difficult. But the second problem is that TFS doesn't have a good way to record deployment data.</p>\n\n<p>For the first question, I'm not sure what that means. For the second question you can use the build labels and tf history today list of the changed files.</p>\n\n<p>As an alternative, you could reconsider how you want to manage SQL changes. I use a low-tech method of keeping the current pending changes in one directory, and then after deploying moving the files to a different directory. This method can be enhanced by keeping a deployment history table in the database. You may also want to look into vsts DB addition, the current <a href=\"http://blogs.msdn.com/gertd/archive/2008/09/30/visual-studio-team-system-2008-database-edition-gdr-september-ctp.aspx\" rel=\"nofollow noreferrer\">CTP</a> has a lot of new features around managing database changes. I also hear that <a href=\"http://www.red-gate.com/products/SQL_Packager/index.htm\" rel=\"nofollow noreferrer\">Red Gate</a> has nice database management tools as well.</p>\n"
},
{
"answer_id": 252916,
"author": "mjallday",
"author_id": 6084,
"author_profile": "https://Stackoverflow.com/users/6084",
"pm_score": 4,
"selected": true,
"text": "<p>Thanks Scott,</p>\n\n<p>After a while I found a nice way to manage this. </p>\n\n<p>Basically I created a task which gets the current changesets associated with the build (point 1 of my question is not an issue) and then loop through them looking for .sql files. Once I have a list of those I can create a change script or execute them against the target database.</p>\n\n<p>The code looks something like this:</p>\n\n<pre><code>TeamFoundationServer tfs = new TeamFoundationServer(TfsServerUrl);\nVersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));\n\nvar buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));\n\n\nIBuildDetail build = buildServer.GetBuild(\n new Uri(BuildUri)\n , null\n , QueryOptions.All\n);\n\nbuild.RefreshAllDetails();\n\nvar changesets = InformationNodeConverters.GetAssociatedChangesets(build);\n\nforeach (var changesetSummary in changesets)\n{\n Changeset changeSet = vcs.GetChangeset(changesetSummary.ChangesetId);\n\n sqlFilePaths.AddRange(\n ProcessChangeSet(changeSet)\n );\n\n}\n</code></pre>\n\n<p>and the code inside ProcessChangeSet looks like</p>\n\n<pre><code>List<string> sqlFilePaths = new List<string>();\nforeach (Change change in changeSet.Changes)\n{\n\n if ((change.Item.ItemType == ItemType.File)\n && (change.Item.ServerItem.EndsWith(\".sql\", StringComparison.OrdinalIgnoreCase))\n )\n {\n sqlFilePaths.Add(\n sqlPath\n );\n\n }\n}\nreturn sqlFilePathes;\n</code></pre>\n\n<p>But if anyone wants I'm happy to give them the complete code. Makes making sure stored procedures are in sync across the system. This only leaves schema changes to manually manage within my database which I'm happy to do.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
I have several branches in TFS (dev, test, stage) and when I merge changes into the test branch I want the automated build and deploy script to find all the updated SQL files and deploy them to the test database.
I thought I could do this by finding all the changesets associated with the build since the last good build, finding all the sql files in the changesets and deploying them. However I don't seem to be having the changeset associated with the build for some reason so my question is twofold:
1) How do I ensure that a changeset is associated with a particular build?
2) How can I get a list of files that have changed in the branch since the last good build? I have the last successfully built build but I'm unsure how to get the files without checking the changesets (which as mentioned above are not associated with the build!)
|
Thanks Scott,
After a while I found a nice way to manage this.
Basically I created a task which gets the current changesets associated with the build (point 1 of my question is not an issue) and then loop through them looking for .sql files. Once I have a list of those I can create a change script or execute them against the target database.
The code looks something like this:
```
TeamFoundationServer tfs = new TeamFoundationServer(TfsServerUrl);
VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
var buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));
IBuildDetail build = buildServer.GetBuild(
new Uri(BuildUri)
, null
, QueryOptions.All
);
build.RefreshAllDetails();
var changesets = InformationNodeConverters.GetAssociatedChangesets(build);
foreach (var changesetSummary in changesets)
{
Changeset changeSet = vcs.GetChangeset(changesetSummary.ChangesetId);
sqlFilePaths.AddRange(
ProcessChangeSet(changeSet)
);
}
```
and the code inside ProcessChangeSet looks like
```
List<string> sqlFilePaths = new List<string>();
foreach (Change change in changeSet.Changes)
{
if ((change.Item.ItemType == ItemType.File)
&& (change.Item.ServerItem.EndsWith(".sql", StringComparison.OrdinalIgnoreCase))
)
{
sqlFilePaths.Add(
sqlPath
);
}
}
return sqlFilePathes;
```
But if anyone wants I'm happy to give them the complete code. Makes making sure stored procedures are in sync across the system. This only leaves schema changes to manually manage within my database which I'm happy to do.
|
220,818 |
<p>How can I detect keyboard event in C language without using third party libraries? Should I use signal handling?</p>
|
[
{
"answer_id": 220820,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>Standard C does not have any facilities for detecting keyboard events, unfortunately. You have to rely on platform-specific extensions. Signal handling wont help you.</p>\n"
},
{
"answer_id": 220821,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>You really should use third party libraries. There's definitely no platform-independent way to do it in ANSI C. Signal handling is not the way.</p>\n"
},
{
"answer_id": 220876,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<p>There's not a standard way, but these should get you started.</p>\n\n<p>Windows:</p>\n\n<pre><code>getch();\n</code></pre>\n\n<p>Unix:</p>\n\n<p>Use this code from W. Richard Stevens' Unix Programming book to set your terminal in raw mode, and then use read().</p>\n\n<pre><code>static struct termios save_termios;\nstatic int term_saved;\n\nint tty_raw(int fd) { /* RAW! mode */\n struct termios buf;\n\n if (tcgetattr(fd, &save_termios) < 0) /* get the original state */\n return -1;\n\n buf = save_termios;\n\n buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n /* echo off, canonical mode off, extended input\n processing off, signal chars off */\n\n buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);\n /* no SIGINT on BREAK, CR-toNL off, input parity\n check off, don't strip the 8th bit on input,\n ouput flow control off */\n\n buf.c_cflag &= ~(CSIZE | PARENB);\n /* clear size bits, parity checking off */\n\n buf.c_cflag |= CS8;\n /* set 8 bits/char */\n\n buf.c_oflag &= ~(OPOST);\n /* output processing off */\n\n buf.c_cc[VMIN] = 1; /* 1 byte at a time */\n buf.c_cc[VTIME] = 0; /* no timer on input */\n\n if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)\n return -1;\n\n term_saved = 1;\n\n return 0;\n}\n\n\nint tty_reset(int fd) { /* set it to normal! */\n if (term_saved)\n if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)\n return -1;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 221072,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 2,
"selected": false,
"text": "<p>What about good old <a href=\"http://msdn.microsoft.com/en-us/library/58w7c94c(VS.80).aspx\" rel=\"noreferrer\">kbhit</a> ? If I understand the question correctly this will work. <a href=\"http://linux-sxs.org/programming/kbhit.html\" rel=\"noreferrer\">Here</a> is the kbhit implementation on Linux. </p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130278/"
] |
How can I detect keyboard event in C language without using third party libraries? Should I use signal handling?
|
There's not a standard way, but these should get you started.
Windows:
```
getch();
```
Unix:
Use this code from W. Richard Stevens' Unix Programming book to set your terminal in raw mode, and then use read().
```
static struct termios save_termios;
static int term_saved;
int tty_raw(int fd) { /* RAW! mode */
struct termios buf;
if (tcgetattr(fd, &save_termios) < 0) /* get the original state */
return -1;
buf = save_termios;
buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* echo off, canonical mode off, extended input
processing off, signal chars off */
buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
/* no SIGINT on BREAK, CR-toNL off, input parity
check off, don't strip the 8th bit on input,
ouput flow control off */
buf.c_cflag &= ~(CSIZE | PARENB);
/* clear size bits, parity checking off */
buf.c_cflag |= CS8;
/* set 8 bits/char */
buf.c_oflag &= ~(OPOST);
/* output processing off */
buf.c_cc[VMIN] = 1; /* 1 byte at a time */
buf.c_cc[VTIME] = 0; /* no timer on input */
if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
return -1;
term_saved = 1;
return 0;
}
int tty_reset(int fd) { /* set it to normal! */
if (term_saved)
if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
return -1;
return 0;
}
```
|
220,822 |
<p>Strange performance outcome, I have a LINQ to SQL query which uses several let statements to get various info it looks like this</p>
<pre><code> public IQueryable<SystemNews> GetSystemNews()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from s in _datacontext.SystemNews
let member = GetMemberInfo(s.MemberID)
let determination = GetDetermination(s.DeterminationID.Value)
let daimoku = GetDaimoku(s.DaimokuID.Value)
let entry = GetEntry(s.EntryID.Value)
let encouragment = GetEncouragement(s.EncouragementID.Value)
select new SystemNews
{
NewsDate = s.NewsDate,
MemberID = s.MemberID,
PhotoID = s.PhotoID.Value,
DeterminationID = s.DeterminationID.Value,
DaimokuID = s.DaimokuID.Value,
EntryID = s.EntryID.Value,
EncouragementID = s.EncouragementID.Value,
Member = new LazyList<Members>(member),
Determination = new LazyList<Determinations>(determination),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entry = new LazyList<MemberEntries>(entry),
Encouragement = new LazyList<MemberEncouragements>(encouragment),
IsDeterminationComplete = s.IsDeterminationComplete.Value
};
return results;
}
}
</code></pre>
<p>I created the same thing (basically at least the various info that is obtained in this) into a SQL View, and the LINQ to SQL returned results in under 90 miliseconds where as the view returned the same data actually less info in over 700 milliseconds. Can anyone explain this?</p>
|
[
{
"answer_id": 220840,
"author": "Danny Frencham",
"author_id": 29830,
"author_profile": "https://Stackoverflow.com/users/29830",
"pm_score": 1,
"selected": false,
"text": "<p>Have you used the SQL profiler to check the differences between the SQL being generated by LINQ, and the SQL you are using to compare?</p>\n\n<p>Perhaps the LINQ to SQL query is better optimised?</p>\n"
},
{
"answer_id": 220853,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": 0,
"selected": false,
"text": "<p>You're probably seeing a caching effect; it's not real.</p>\n\n<p>One of the tenets of benchmarking is that you can skew your benchmark either way by running the benchmark once, getting the results in cache, then run it again and report amazing results, or, do the reverse...</p>\n"
},
{
"answer_id": 221090,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>In general, LINQ-to-SQL will be \"about the same\", and I'd agree that caching is porbably an issue here. Really you need to look at the generated SQL; the easiest way being:</p>\n\n<pre><code>_datacontext.Log = Console.Out;\n</code></pre>\n\n<p>Then try running the TSQL directly in Query Analyzer. SPROCs have some advantages in terms of being able to optimise access, use table variables, etc; however, LINQ has the advantage of composability - i.e. you can apply your paging, sorting, projections, etc in the single query. You can <em>at a push</em> do that with an SPROC, but it is very hard work.</p>\n\n<p>But really, the key is in looking at the TSQL; it might be that you haven't loaded all the data, for example (lazy loading).</p>\n"
},
{
"answer_id": 1170989,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": "<p>At a cursory glance it looks like your Linq to SQL query is making use of lazy loading. If I'm right about that then it makes sense that running your query wont actually run all parts of the query at that time. This means that if you compare it to a SQL View which is set to bring back all of these results in one swoop then that would definitely be more work and thus take extra time.</p>\n\n<p>Two other points:</p>\n\n<ol>\n<li><p>Make sure you are timing the actual query execution and not the assignment of the query expression. Remember Linq queries are deferred so when you return your query from the method above it is actually returning the expression not the results. In general three popular ways to make a Linq query execute are by running the ToArray or ToList extension methods or by simply iterating over the results using foreach.</p></li>\n<li><p>If you are in fact doing lazy loading and timing the actual execution of the query and still ending up with better results in Linq to SQL it could be due to differences in having wide flattened results returned by your SQL View in comparison to narrow pieces being queried multiple times with Linq to SQL. </p></li>\n</ol>\n\n<p>I've never done any benchmarks on this to see where the tipping point is but you can imagine the case where you have two tables Table1, and Table2 both with 100 columns per table and 1,000 rows of data in Table1 which also has a one to many relationship to Table2 and generally yields 10 matches in Table2 for every record in Table1. Now if you write a view to pull all of these results back in a single query you will expect around 10,000 rows of data all with about 200 columns wide. By issuing two separate queries however either via Linq to SQL or any other mechanism you can instead get your initial 1,000 row 100 column wide results from Table1 and then pick the remaining Table2 items potentially 10,000 rows by another 100 columns for a total of 1,100,000 cells (which is much less than the 2,000,000 cells from the SQL View). The benefits are even more exaggerated if we assume there is a large degree of overlap between the dependent rows of a many to many relationship. In the most extreme case there is 100% overlap meaning we would only expect a total of 100,010 cells of data to be pulled back which is far less than the 2,000,000 returned by a flattened view.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22093/"
] |
Strange performance outcome, I have a LINQ to SQL query which uses several let statements to get various info it looks like this
```
public IQueryable<SystemNews> GetSystemNews()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from s in _datacontext.SystemNews
let member = GetMemberInfo(s.MemberID)
let determination = GetDetermination(s.DeterminationID.Value)
let daimoku = GetDaimoku(s.DaimokuID.Value)
let entry = GetEntry(s.EntryID.Value)
let encouragment = GetEncouragement(s.EncouragementID.Value)
select new SystemNews
{
NewsDate = s.NewsDate,
MemberID = s.MemberID,
PhotoID = s.PhotoID.Value,
DeterminationID = s.DeterminationID.Value,
DaimokuID = s.DaimokuID.Value,
EntryID = s.EntryID.Value,
EncouragementID = s.EncouragementID.Value,
Member = new LazyList<Members>(member),
Determination = new LazyList<Determinations>(determination),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entry = new LazyList<MemberEntries>(entry),
Encouragement = new LazyList<MemberEncouragements>(encouragment),
IsDeterminationComplete = s.IsDeterminationComplete.Value
};
return results;
}
}
```
I created the same thing (basically at least the various info that is obtained in this) into a SQL View, and the LINQ to SQL returned results in under 90 miliseconds where as the view returned the same data actually less info in over 700 milliseconds. Can anyone explain this?
|
In general, LINQ-to-SQL will be "about the same", and I'd agree that caching is porbably an issue here. Really you need to look at the generated SQL; the easiest way being:
```
_datacontext.Log = Console.Out;
```
Then try running the TSQL directly in Query Analyzer. SPROCs have some advantages in terms of being able to optimise access, use table variables, etc; however, LINQ has the advantage of composability - i.e. you can apply your paging, sorting, projections, etc in the single query. You can *at a push* do that with an SPROC, but it is very hard work.
But really, the key is in looking at the TSQL; it might be that you haven't loaded all the data, for example (lazy loading).
|
220,828 |
<p>I have an application running on multiple IIS servers that need to parse a CSV file that is placed on a common network drive. If I use the <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created.aspx" rel="nofollow noreferrer">System.IO.FileSystemWatcher Created event</a> to be notified of the event when the file is available, how can I ensure only one server parses the file? If all servers are notified of this change, all will try to parse it. Should the first server copy this locally and then parse it? Would this cause errors on the other servers? Should I set the remote directory access to only allow one server read access?</p>
<p>The file contains records that needs to be inserted into a shared database, but there is no unique key for the records. Therefore, if more than one server grabs the file at the same time and inserts the records, there will be duplicates in the database.</p>
|
[
{
"answer_id": 220957,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "<p>Key question is: Does something bad happen when all of them try and parse the file at roughly the same time? Multiple read access is basically allowed on the file system level, so this fact alone would not necessarily break anything.</p>\n\n<p>I would probably try the method of creating a lock file on first file access and make servers look for the lock file before accessing the file. Delete the lock file when you're done.</p>\n\n<p>You could also place an exclusive lock on the file, only one server will be able to do that at a time. The others will fail trying:</p>\n\n<pre><code>FileStream fs = new FileStream(\n FilePath, \n FileMode.Open,\n FileAccess.ReadWrite, \n FileShare.None\n);\n</code></pre>\n"
},
{
"answer_id": 245562,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 0,
"selected": false,
"text": "<p>Another option instead of the lock is to rename the file into a directory. Make a sub-directory for each server and then have a server try and re-name the file into its directory (rename is an atomic operation). The one to succed gets to parse the file.</p>\n\n<p>The lock issue will be tricky as the file will still be visible to each server and they might try and open the file and then repeatly error. The rename will be absolute as to the owner of the file.</p>\n\n<p>Also keep in mind whatever solution you use that there will be the possibility of a \"lost file\". If a server stops processing a file (error, exception, reboot...) it might be abandoned. The typical solution to these types of problems is in addition to things like the file watcher you have servers poll every now and then as well. </p>\n\n<p>Copying the file to a server dir will help a bit with this. One downside would be if a server goes completely off-line, then its file will sit in a dir until the server comes back on-line.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4555/"
] |
I have an application running on multiple IIS servers that need to parse a CSV file that is placed on a common network drive. If I use the [System.IO.FileSystemWatcher Created event](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created.aspx) to be notified of the event when the file is available, how can I ensure only one server parses the file? If all servers are notified of this change, all will try to parse it. Should the first server copy this locally and then parse it? Would this cause errors on the other servers? Should I set the remote directory access to only allow one server read access?
The file contains records that needs to be inserted into a shared database, but there is no unique key for the records. Therefore, if more than one server grabs the file at the same time and inserts the records, there will be duplicates in the database.
|
Key question is: Does something bad happen when all of them try and parse the file at roughly the same time? Multiple read access is basically allowed on the file system level, so this fact alone would not necessarily break anything.
I would probably try the method of creating a lock file on first file access and make servers look for the lock file before accessing the file. Delete the lock file when you're done.
You could also place an exclusive lock on the file, only one server will be able to do that at a time. The others will fail trying:
```
FileStream fs = new FileStream(
FilePath,
FileMode.Open,
FileAccess.ReadWrite,
FileShare.None
);
```
|
220,832 |
<p>If I have the string <code>.....ZZ..ZZ.....</code> or <code>.Z.1.Z.23Z.4.Z55</code>,</p>
<p>Is there an easy way of shifting all <code>Z</code>characters in the string one space right of the current position?</p>
<p>Some additional test strings are:</p>
<ul>
<li><code>.Z</code></li>
<li><code>Z.</code></li>
<li><code>ZZ.</code></li>
<li><code>.ZZ</code></li>
<li><code>Z</code></li>
<li><code>ZZ</code></li>
<li><code>ZZZ</code></li>
</ul>
<p>I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.</p>
|
[
{
"answer_id": 220837,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>Just iterate through the text and swap characters:</p>\n\n<pre><code>int main ()\n{\n char text[] = \"...Z.Z.Z...\", temp;\n int text_len = strlen (text), i;\n for (i = text_len - 1; i >= 0; i--)\n {\n if (text[i] == 'Z')\n {\n temp = text[i+1];\n text[i+1] = text[i];\n text[i] = temp;\n }\n }\n printf (\"%s\\n\", text);\n return 0;\n}\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>[~]$ gcc zshift.c && ./a.out\n....Z.Z.Z..\n</code></pre>\n\n<hr>\n\n<p>There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case.</p>\n\n<pre><code>zshift \"Z.\" -> \".Z\"\nzshift \".Z\" -> \".\"\nzshift \"Z\" -> \"\"\n</code></pre>\n\n<p>I think the behavior of \"dropping\" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped.</p>\n\n<p>If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal:</p>\n\n<pre><code>temp = text[i+1];\nif (temp == 0) continue;\ntext[i+1] = text[i];\ntext[i] = temp;\n</code></pre>\n"
},
{
"answer_id": 220850,
"author": "Steve Lacey",
"author_id": 11077,
"author_profile": "https://Stackoverflow.com/users/11077",
"pm_score": 0,
"selected": false,
"text": "<p>Slight fix to the previous answer (shift to the right and assume '.' means \"can move here\"):</p>\n\n<pre><code> char text[] = \"...Z.Z.Z...\";\n\n for (int i = strlen(text) - 2); i > 0; --i) {\n if (text[i] == 'Z' && text[i + 1] == '.') {\n text[i] = '.';\n text[i + 1] = 'Z';\n }\n }\n</code></pre>\n"
},
{
"answer_id": 220880,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 2,
"selected": false,
"text": "<p>Building on previously posted code here. Function gets str and strlen, overwrites str. Works also with subsequent Z. Going forward for speed improvement with subsequent Z.</p>\n\n<pre><code>void move_z_right (char* str, int strlen) {\n for (unsigned int i = 0; i < strlen - 1; ++i)\n {\n if (str[i] == 'Z')\n {\n unsigned int j = i+1;\n while (str[j] == 'Z' && j < strlen - 1) ++j;\n if (j == strlen) break; // we are at the end, done\n char tmp = str[j];\n str[j] = str[i];\n str[i] = tmp;\n i = j; // continue after new Z next run\n }\n }\n}\n</code></pre>\n\n<p>Note that John Millikin's solution is nicer to read and also correct.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29326/"
] |
If I have the string `.....ZZ..ZZ.....` or `.Z.1.Z.23Z.4.Z55`,
Is there an easy way of shifting all `Z`characters in the string one space right of the current position?
Some additional test strings are:
* `.Z`
* `Z.`
* `ZZ.`
* `.ZZ`
* `Z`
* `ZZ`
* `ZZZ`
I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.
|
Just iterate through the text and swap characters:
```
int main ()
{
char text[] = "...Z.Z.Z...", temp;
int text_len = strlen (text), i;
for (i = text_len - 1; i >= 0; i--)
{
if (text[i] == 'Z')
{
temp = text[i+1];
text[i+1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
return 0;
}
```
Produces:
```
[~]$ gcc zshift.c && ./a.out
....Z.Z.Z..
```
---
There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case.
```
zshift "Z." -> ".Z"
zshift ".Z" -> "."
zshift "Z" -> ""
```
I think the behavior of "dropping" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped.
If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal:
```
temp = text[i+1];
if (temp == 0) continue;
text[i+1] = text[i];
text[i] = temp;
```
|
220,855 |
<p>By default gcc/g++ prints a warning message with the line number only. I am looking for the option by which g++ or gcc associates the build warning messages with the warning ids, so that the warning messages can be identified easily (without parsing). Also can there be any more option to get a more detailed warning message ? (Though I think each of the warning message is pretty much explanatory by itself, but just curious)</p>
<p>Thanks.</p>
|
[
{
"answer_id": 220868,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK, there is no such option - the messages are self-identifying.</p>\n"
},
{
"answer_id": 220909,
"author": "ypnos",
"author_id": 21974,
"author_profile": "https://Stackoverflow.com/users/21974",
"pm_score": 2,
"selected": false,
"text": "<p>GCC does not provide the option to change/add the text of warning messages. See section \"Options to Control Diagnostic Messages Formatting\" in the Manpage.</p>\n\n<p>GCC also does not provide more verbose warning messages.</p>\n\n<p>Sorry.</p>\n"
},
{
"answer_id": 220912,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p>GCC doesn't have a warning ID <-> message mapping. If you'd like to filter particular warning messages, use a CFLAG such as <code>-Wno-pragmas</code> or <code>-Wno-oveflow</code>. The full list of flags is documented in the man page.</p>\n"
},
{
"answer_id": 221132,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>In GCC 4.x there is an option \"-fdiagnostics-show-option\" which displays the option used to switch off the warning:</p>\n\n<pre><code>$ gcc -fdiagnostics-show-option foo.c -Wall -o foo\nfoo.c: In function ‘main’:\nfoo.c:3: warning: unused variable ‘x’ [-Wunused-variable]\nfoo.c:4: warning: control reaches end of non-void function\n</code></pre>\n\n<p>In case you need to parse the warning, this may simplify things (especially in the presence of localized error messages).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29857/"
] |
By default gcc/g++ prints a warning message with the line number only. I am looking for the option by which g++ or gcc associates the build warning messages with the warning ids, so that the warning messages can be identified easily (without parsing). Also can there be any more option to get a more detailed warning message ? (Though I think each of the warning message is pretty much explanatory by itself, but just curious)
Thanks.
|
In GCC 4.x there is an option "-fdiagnostics-show-option" which displays the option used to switch off the warning:
```
$ gcc -fdiagnostics-show-option foo.c -Wall -o foo
foo.c: In function ‘main’:
foo.c:3: warning: unused variable ‘x’ [-Wunused-variable]
foo.c:4: warning: control reaches end of non-void function
```
In case you need to parse the warning, this may simplify things (especially in the presence of localized error messages).
|
220,867 |
<p>What is the best way to deal with XML documents, XSD etc in C# 2.0? </p>
<p>Which classes to use etc. What are the best practices of parsing and making XML documents etc. </p>
<p>EDIT: .Net 3.5 suggestions are also welcome.</p>
|
[
{
"answer_id": 220877,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>It depends on the size; for small to mid size xml, a DOM such as <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"noreferrer\">XmlDocument</a> (any C#/.NET versions) or <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx\" rel=\"noreferrer\">XDocument</a> (.NET 3.5/C# 3.0) is the obvious winner. For using xsd, You can load xml using an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx\" rel=\"noreferrer\">XmlReader</a>, and an XmlReader accepts (to <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx\" rel=\"noreferrer\">Create</a>) an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.aspx\" rel=\"noreferrer\">XmlReaderSettings</a>. The XmlReaderSettings objects has a <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.schemas.aspx\" rel=\"noreferrer\">Schemas</a> property that can be used to perform xsd (or dtd) validation.</p>\n\n<p>For writing xml, the same things apply, noting that it is a little easier to lay out content with LINQ-to-XML (XDocument) than the older XmlDocument.</p>\n\n<p>However, for huge xml, a DOM may chomp too much memory, in which case you might need to use XmlReader/XmlWriter directly.</p>\n\n<p>Finally, for manipulating xml you may wish to use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx\" rel=\"noreferrer\">XslCompiledTransform</a> (an xslt layer).</p>\n\n<p>The alternative to working with xml is to work with an object model; you can use <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx\" rel=\"noreferrer\">xsd.exe</a> to create classes that represent an xsd-compliant model, and simply load the xml <em>as objects</em>, manipulate it with OO, and then serialize those objects again; you do this with <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=\"noreferrer\">XmlSerializer</a>.</p>\n"
},
{
"answer_id": 220888,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 3,
"selected": false,
"text": "<p>First of all, get to know the new <strong>XDocument</strong> and <strong>XElement</strong> classes, because they are an improvement over the previous XmlDocument family. </p>\n\n<ol>\n<li>They work with LINQ </li>\n<li>They are faster and more lightweight</li>\n</ol>\n\n<p><strong>However</strong>, you may have to still use the old classes to work with legacy code - particularly previously generated proxies. In that case, you will need to become familiar with some patterns for interoperating between these XML-handling classes.</p>\n\n<p>I think your question is quite broad, and would require too much in a single answer to give details, but this is the first general answer I thought of, and serves as a start.</p>\n"
},
{
"answer_id": 220981,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 9,
"selected": true,
"text": "<p>The primary means of reading and writing in C# 2.0 is done through the <strong>XmlDocument</strong> class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts.</p>\n\n<h3>Loading XML Directly</h3>\n\n<pre><code>XmlDocument document = new XmlDocument();\ndocument.LoadXml(\"<People><Person Name='Nick' /><Person Name='Joe' /></People>\");\n</code></pre>\n\n<h3>Loading XML From a File</h3>\n\n<pre><code>XmlDocument document = new XmlDocument();\ndocument.Load(@\"C:\\Path\\To\\xmldoc.xml\");\n// Or using an XmlReader/XmlTextReader\nXmlReader reader = XmlReader.Create(@\"C:\\Path\\To\\xmldoc.xml\");\ndocument.Load(reader);\n</code></pre>\n\n<p>I find the easiest/fastest way to read an XML document is by using XPath.</p>\n\n<h3>Reading an XML Document using XPath (Using XmlDocument which allows us to edit)</h3>\n\n<pre><code>XmlDocument document = new XmlDocument();\ndocument.LoadXml(\"<People><Person Name='Nick' /><Person Name='Joe' /></People>\");\n\n// Select a single node\nXmlNode node = document.SelectSingleNode(\"/People/Person[@Name = 'Nick']\");\n\n// Select a list of nodes\nXmlNodeList nodes = document.SelectNodes(\"/People/Person\");\n</code></pre>\n\n<p>If you need to work with XSD documents to validate an XML document you can use this.</p>\n\n<h3>Validating XML Documents against XSD Schemas</h3>\n\n<pre><code>XmlReaderSettings settings = new XmlReaderSettings();\nsettings.ValidateType = ValidationType.Schema;\nsettings.Schemas.Add(\"\", pathToXsd); // targetNamespace, pathToXsd\n\nXmlReader reader = XmlReader.Create(pathToXml, settings);\nXmlDocument document = new XmlDocument();\n\ntry {\n document.Load(reader);\n} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }\n</code></pre>\n\n<h3>Validating XML against XSD at each Node (UPDATE 1)</h3>\n\n<pre><code>XmlReaderSettings settings = new XmlReaderSettings();\nsettings.ValidateType = ValidationType.Schema;\nsettings.Schemas.Add(\"\", pathToXsd); // targetNamespace, pathToXsd\nsettings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);\n\nXmlReader reader = XmlReader.Create(pathToXml, settings);\nwhile (reader.Read()) { }\n\nprivate void settings_ValidationEventHandler(object sender, ValidationEventArgs args)\n{\n // e.Message, e.Severity (warning, error), e.Error\n // or you can access the reader if you have access to it\n // reader.LineNumber, reader.LinePosition.. etc\n}\n</code></pre>\n\n<h3>Writing an XML Document (manually)</h3>\n\n<pre><code>XmlWriter writer = XmlWriter.Create(pathToOutput);\nwriter.WriteStartDocument();\nwriter.WriteStartElement(\"People\");\n\nwriter.WriteStartElement(\"Person\");\nwriter.WriteAttributeString(\"Name\", \"Nick\");\nwriter.WriteEndElement();\n\nwriter.WriteStartElement(\"Person\");\nwriter.WriteStartAttribute(\"Name\");\nwriter.WriteValue(\"Nick\");\nwriter.WriteEndAttribute();\nwriter.WriteEndElement();\n\nwriter.WriteEndElement();\nwriter.WriteEndDocument();\n\nwriter.Flush();\n</code></pre>\n\n<p><strong><em>(UPDATE 1)</em></strong></p>\n\n<p>In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself.</p>\n\n<pre><code> XDocument doc = XDocument.Load(pathToXml);\n List<Person> people = (from xnode in doc.Element(\"People\").Elements(\"Person\")\n select new Person\n {\n Name = xnode.Attribute(\"Name\").Value\n }).ToList();\n</code></pre>\n\n<p><strong><em>(UPDATE 2)</em></strong></p>\n\n<p>A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output.</p>\n\n<pre><code>XDocument doc =\n new XDocument(\n new XDeclaration(\"1.0\", Encoding.UTF8.HeaderName, String.Empty),\n new XComment(\"Xml Document\"),\n new XElement(\"catalog\",\n new XElement(\"book\", new XAttribute(\"id\", \"bk001\"),\n new XElement(\"title\", \"Book Title\")\n )\n )\n );\n</code></pre>\n\n<p>creates </p>\n\n<pre><code><!--Xml Document-->\n<catalog>\n <book id=\"bk001\">\n <title>Book Title</title>\n </book>\n</catalog>\n</code></pre>\n\n<p>All else fails, you can check out this MSDN article that has many examples that I've discussed here and more.\n<a href=\"http://msdn.microsoft.com/en-us/library/aa468556.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa468556.aspx</a></p>\n"
},
{
"answer_id": 220997,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>If you're working in .NET 3.5 and you aren't affraid of experimental code you can check out LINQ to XSD (<a href=\"http://blogs.msdn.com/xmlteam/archive/2008/02/21/linq-to-xsd-alpha-0-2.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/xmlteam/archive/2008/02/21/linq-to-xsd-alpha-0-2.aspx</a>) which will generate .NET classes from an XSD (including built in rules from the XSD).</p>\n\n<p>It then has the ability to write straight out to a file and read from a file ensuring that it conforms to the XSD rules.</p>\n\n<p>I definately suggest having an XSD for any XML document you work with:</p>\n\n<ul>\n<li>Allows you to enforce rules in the XML</li>\n<li>Allows others to see how the XML is/ will be structured</li>\n<li>Can be used for validation of XML</li>\n</ul>\n\n<p>I find that Liquid XML Studio is a great tool for generating XSD's and it's free!</p>\n"
},
{
"answer_id": 220998,
"author": "emremp",
"author_id": 12024,
"author_profile": "https://Stackoverflow.com/users/12024",
"pm_score": 2,
"selected": false,
"text": "<p>101 Linq samples </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb387098.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb387098.aspx</a></p>\n\n<p>and <strong>Linq to XML samples</strong></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/vbasic/bb688087.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vbasic/bb688087.aspx</a></p>\n\n<p>And I think Linq makes XML easy.</p>\n"
},
{
"answer_id": 222576,
"author": "Peter C",
"author_id": 1952,
"author_profile": "https://Stackoverflow.com/users/1952",
"pm_score": 1,
"selected": false,
"text": "<p>If you create a typed dataset in the designer then you automatically get an xsd, a strongly typed object, and can load and save the xml with one line of code.</p>\n"
},
{
"answer_id": 223014,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 4,
"selected": false,
"text": "<p>nyxtom's answer is very good. I'd add a couple of things to it:</p>\n\n<p>If you need read-only access to an XML document, <code>XPathDocument</code> is a much lighter-weight object than <code>XmlDocument</code>. </p>\n\n<p>The downside of using <code>XPathDocument</code> is that you can't use the familiar <code>SelectNodes</code> and <code>SelectSingleNode</code> methods of <code>XmlNode</code>. Instead, you have to use the tools that the <code>IXPathNavigable</code> provides: use <code>CreateNavigator</code> to create an <code>XPathNavigator</code>, and use the <code>XPathNavigator</code> to create <code>XPathNodeIterator</code>s to iterate over the lists of nodes you find via XPath. This generally requires a few more lines of code than the <code>XmlDocument</code> methods.</p>\n\n<p>But: the <code>XmlDocument</code> and <code>XmlNode</code> classes implement <code>IXPathNavigable</code>, so any code you write to use those methods on an <code>XPathDocument</code> will also work on an <code>XmlDocument</code>. If you get used to writing against <code>IXPathNavigable</code>, your methods can work against either object. (This is why using <code>XmlNode</code> and <code>XmlDocument</code> in method signatures is flagged by FxCop.)</p>\n\n<p>Lamentably, <code>XDocument</code> and <code>XElement</code> (and <code>XNode</code> and <code>XObject</code>) don't implement <code>IXPathNavigable</code>.</p>\n\n<p>Another thing not present in nyxtom's answer is <code>XmlReader</code>. You generally use <code>XmlReader</code> to avoid the overhead of parsing the XML stream into an object model before you begin processing it. Instead, you use an <code>XmlReader</code> to process the input stream one XML node at a time. This is essentially .NET's answer to SAX. It lets you write very fast code for processing very large XML documents. </p>\n\n<p><code>XmlReader</code> also provides the simplest way of processing XML document fragments, e.g. the stream of XML elements with no encluding element that SQL Server's FOR XML RAW option returns.</p>\n\n<p>The code you write using <code>XmlReader</code> is generally very tightly coupled to the format of the XML it's reading. Using XPath allows your code to be much, much more loosely coupled to the XML, which is why it's generally the right answer. But when you need to use <code>XmlReader</code>, you really need it.</p>\n"
},
{
"answer_id": 223043,
"author": "Steve Horn",
"author_id": 10589,
"author_profile": "https://Stackoverflow.com/users/10589",
"pm_score": 0,
"selected": false,
"text": "<p>Cookey's answer is good... but here are detailed instructions on how to create a strongly typed object from an XSD(or XML) and serialize/deserialize in a few lines of code:</p>\n\n<p><a href=\"http://www.stevehorn.cc/#!/blog/generate-code-from-xml-schema-xsdexe\" rel=\"nofollow noreferrer\" title=\"Instructions\">Instructions</a></p>\n"
},
{
"answer_id": 2555689,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 1,
"selected": false,
"text": "<p>My personal opinion, as a C# programmer, is that the best way to deal with XML in C# is to delegate that part of the code to a VB .NET project. In .NET 3.5, VB .NET has XML Literals, which make dealing with XML much more intuitive. See here, for example:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb384460.aspx\" rel=\"nofollow noreferrer\">Overview of LINQ to XML in Visual Basic</a></p>\n\n<p>(Be sure to set the page to display VB code, not C# code.)</p>\n\n<p>I'd write the rest of the project in C#, but handle the XML in a referenced VB project.</p>\n"
},
{
"answer_id": 4837444,
"author": "mokumaxCraig",
"author_id": 572807,
"author_profile": "https://Stackoverflow.com/users/572807",
"pm_score": 0,
"selected": false,
"text": "<p>nyxtom,</p>\n\n<p>Shouldn't \"doc\" and \"xdoc\" match in Example 1?</p>\n\n<pre><code>XDocument **doc** = XDocument.Load(pathToXml);\nList<Person> people = (from xnode in **xdoc**.Element(\"People\").Elements(\"Person\")\n select new Person\n {\n Name = xnode.Attribute(\"Name\").Value\n }).ToList();\n</code></pre>\n"
},
{
"answer_id": 35289396,
"author": "Anil Rathod",
"author_id": 1078684,
"author_profile": "https://Stackoverflow.com/users/1078684",
"pm_score": 2,
"selected": false,
"text": "<p>Writing XML with the XmlDocument class </p>\n\n<pre><code>//itemValues is collection of items in Key value pair format\n//fileName i name of XML file which to creatd or modified with content\n private void WriteInXMLFile(System.Collections.Generic.Dictionary<string, object> itemValues, string fileName)\n {\n string filePath = \"C:\\\\\\\\tempXML\\\\\" + fileName + \".xml\";\n try\n {\n\n if (System.IO.File.Exists(filePath))\n {\n XmlDocument doc = new XmlDocument();\n doc.Load(filePath); \n\n XmlNode rootNode = doc.SelectSingleNode(\"Documents\");\n\n XmlNode pageNode = doc.CreateElement(\"Document\");\n rootNode.AppendChild(pageNode);\n\n\n foreach (string key in itemValues.Keys)\n {\n\n XmlNode attrNode = doc.CreateElement(key);\n attrNode.InnerText = Convert.ToString(itemValues[key]);\n pageNode.AppendChild(attrNode);\n //doc.DocumentElement.AppendChild(attrNode);\n\n }\n doc.DocumentElement.AppendChild(pageNode);\n doc.Save(filePath);\n }\n else\n {\n XmlDocument doc = new XmlDocument();\n using(System.IO.FileStream fs = System.IO.File.Create(filePath))\n {\n //Do nothing\n }\n\n XmlNode rootNode = doc.CreateElement(\"Documents\");\n doc.AppendChild(rootNode);\n doc.Save(filePath);\n\n doc.Load(filePath);\n\n XmlNode pageNode = doc.CreateElement(\"Document\");\n rootNode.AppendChild(pageNode);\n\n foreach (string key in itemValues.Keys)\n { \n XmlNode attrNode = doc.CreateElement(key); \n attrNode.InnerText = Convert.ToString(itemValues[key]);\n pageNode.AppendChild(attrNode);\n //doc.DocumentElement.AppendChild(attrNode);\n\n }\n doc.DocumentElement.AppendChild(pageNode);\n\n doc.Save(filePath);\n\n }\n }\n catch (Exception ex)\n {\n\n }\n\n }\n\nOutPut look like below\n<Dcouments>\n <Document>\n <DocID>01<DocID>\n <PageName>121<PageName>\n <Author>Mr. ABC<Author>\n <Dcoument>\n <Document>\n <DocID>02<DocID>\n <PageName>122<PageName>\n <Author>Mr. PQR<Author>\n <Dcoument>\n</Dcouments>\n</code></pre>\n"
},
{
"answer_id": 52056636,
"author": "Michael Hutter",
"author_id": 9134997,
"author_profile": "https://Stackoverflow.com/users/9134997",
"pm_score": 0,
"selected": false,
"text": "<p>If you ever need to convert data between <code>XmlNode</code> <=> <code>XNode</code> <=> <code>XElement</code><br>\n(e. g. in order to use LINQ) this Extensions may be helpful for you:</p>\n\n<pre><code>public static class MyExtensions\n{\n public static XNode GetXNode(this XmlNode node)\n {\n return GetXElement(node);\n }\n\n public static XElement GetXElement(this XmlNode node)\n {\n XDocument xDoc = new XDocument();\n using (XmlWriter xmlWriter = xDoc.CreateWriter())\n node.WriteTo(xmlWriter);\n return xDoc.Root;\n }\n\n public static XmlNode GetXmlNode(this XElement element)\n {\n using (XmlReader xmlReader = element.CreateReader())\n {\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load(xmlReader);\n return xmlDoc;\n }\n }\n\n public static XmlNode GetXmlNode(this XNode node)\n {\n return GetXmlNode(node);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>XmlDocument MyXmlDocument = new XmlDocument();\nMyXmlDocument.Load(\"MyXml.xml\");\nXElement MyXElement = MyXmlDocument.GetXElement(); // Convert XmlNode to XElement\nList<XElement> List = MyXElement.Document\n .Descendants()\n .ToList(); // Now you can use LINQ\n...\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
What is the best way to deal with XML documents, XSD etc in C# 2.0?
Which classes to use etc. What are the best practices of parsing and making XML documents etc.
EDIT: .Net 3.5 suggestions are also welcome.
|
The primary means of reading and writing in C# 2.0 is done through the **XmlDocument** class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts.
### Loading XML Directly
```
XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");
```
### Loading XML From a File
```
XmlDocument document = new XmlDocument();
document.Load(@"C:\Path\To\xmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.xml");
document.Load(reader);
```
I find the easiest/fastest way to read an XML document is by using XPath.
### Reading an XML Document using XPath (Using XmlDocument which allows us to edit)
```
XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");
// Select a single node
XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']");
// Select a list of nodes
XmlNodeList nodes = document.SelectNodes("/People/Person");
```
If you need to work with XSD documents to validate an XML document you can use this.
### Validating XML Documents against XSD Schemas
```
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
XmlReader reader = XmlReader.Create(pathToXml, settings);
XmlDocument document = new XmlDocument();
try {
document.Load(reader);
} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }
```
### Validating XML against XSD at each Node (UPDATE 1)
```
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
XmlReader reader = XmlReader.Create(pathToXml, settings);
while (reader.Read()) { }
private void settings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
// e.Message, e.Severity (warning, error), e.Error
// or you can access the reader if you have access to it
// reader.LineNumber, reader.LinePosition.. etc
}
```
### Writing an XML Document (manually)
```
XmlWriter writer = XmlWriter.Create(pathToOutput);
writer.WriteStartDocument();
writer.WriteStartElement("People");
writer.WriteStartElement("Person");
writer.WriteAttributeString("Name", "Nick");
writer.WriteEndElement();
writer.WriteStartElement("Person");
writer.WriteStartAttribute("Name");
writer.WriteValue("Nick");
writer.WriteEndAttribute();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
```
***(UPDATE 1)***
In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself.
```
XDocument doc = XDocument.Load(pathToXml);
List<Person> people = (from xnode in doc.Element("People").Elements("Person")
select new Person
{
Name = xnode.Attribute("Name").Value
}).ToList();
```
***(UPDATE 2)***
A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output.
```
XDocument doc =
new XDocument(
new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),
new XComment("Xml Document"),
new XElement("catalog",
new XElement("book", new XAttribute("id", "bk001"),
new XElement("title", "Book Title")
)
)
);
```
creates
```
<!--Xml Document-->
<catalog>
<book id="bk001">
<title>Book Title</title>
</book>
</catalog>
```
All else fails, you can check out this MSDN article that has many examples that I've discussed here and more.
<http://msdn.microsoft.com/en-us/library/aa468556.aspx>
|
220,872 |
<p>Just wondering if anyone has seen any usable progress bar for C# .net apps. My app takes about 20-60 secs to load and I would love to show users a progress bar while they wait. I saw <a href="http://www.codeproject.com/KB/aspnet/ASPNETAJAXPageLoader.aspx" rel="nofollow noreferrer">this one</a> but the sample site doesn't seem to work which doesn't inspire confidence.</p>
|
[
{
"answer_id": 220903,
"author": "Søren Pedersen",
"author_id": 379419,
"author_profile": "https://Stackoverflow.com/users/379419",
"pm_score": 1,
"selected": false,
"text": "<p>I would look into this blog post - seems like a good way to do it. I haven't tested it myself...</p>\n\n<p><a href=\"http://mattberseth.com/blog/2008/05/aspnet_ajax_progress_bar_contr.html\" rel=\"nofollow noreferrer\">http://mattberseth.com/blog/2008/05/aspnet_ajax_progress_bar_contr.html</a></p>\n"
},
{
"answer_id": 223796,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"http://ajax.net-tutorials.com/controls/updateprogress-control/\" rel=\"nofollow noreferrer\">AJAX UpdateProgress control</a>. </p>\n\n<pre><code><asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" />\n <asp:UpdateProgress runat=\"server\" id=\"PageUpdateProgress\">\n <ProgressTemplate>\n Loading...\n </ProgressTemplate>\n </asp:UpdateProgress>\n <asp:UpdatePanel runat=\"server\" id=\"Panel\">\n <ContentTemplate>\n <asp:Button runat=\"server\" id=\"UpdateButton\" onclick=\"UpdateButton_Click\" text=\"Update\" />\n </ContentTemplate>\n </asp:UpdatePanel>\n</code></pre>\n\n<p>If you want animation, all you need to do is pop an animated .gif into the 'ProgressTemplate'.</p>\n"
},
{
"answer_id": 12418314,
"author": "nikinup",
"author_id": 1256450,
"author_profile": "https://Stackoverflow.com/users/1256450",
"pm_score": 1,
"selected": false,
"text": "<p>In aspx page you need to write this,I have added certain CSS class which you yourself need to define, functinality wise this code will help you</p>\n\n<pre><code><asp:Panel ID=\"ProgressIndicatorPanel\" runat=\"server\" Style=\"display: none\" CssClass=\"modalPopup\">\n <div id=\"ProgressDiv\" class=\"progressStyle\">\n <ul class=\"ProgressStyleTable\" style=\"list-style:none;height:60px\">\n <li style=\"position:static;float:left;margin-top:0.5em;margin-left:0.5em\">\n <asp:Image ID=\"ProgressImage\" runat=\"server\" SkinID=\"ProgressImage\" />\n </li>\n <li style=\"position:static;float:left;margin-top:0.5em;margin-left:0.5em;margin-right:0.5em\">\n <span id=\"ProgressTextTableCell\"> Loading, please wait... </span>\n </li>\n </ul>\n </div>\n </asp:Panel>\n</code></pre>\n\n<p>Define a function say ProgressIndicator as follows</p>\n\n<pre><code>var ProgressIndicator = function (progPrefix) {\n var divId = 'ProgressDiv';\n var textId = 'ProgressTextTableCell';\n var progressCss = \"progressStyle\";\n\n if (progPrefix != null) {\n divId = progPrefix + divId;\n textId = progPrefix + textId;\n }\n\n this.Start = function (textString) {\n if (textString) {\n $('#' + textId).text(textString);\n }\n else {\n $('#' + textId).text('Loading, please wait...');\n }\n this.Center();\n //$('#' + divId).show();\n var modalPopupBehavior = $find('ProgressModalPopupBehaviour');\n if (modalPopupBehavior != null) modalPopupBehavior.show();\n }\n\n this.Center = function () {\n var viewportWidth = jQuery(window).width();\n var viewportHeight = jQuery(window).height();\n var progressDiv = $(\"#\" + divId);\n var elWidth = progressDiv.width();\n var elHeight = progressDiv.height();\n progressDiv.css({ top: ((viewportHeight / 2) - (elHeight / 2)) + $(window).scrollTop(),\n left: ((viewportWidth / 2) - (elWidth / 2)) + $(window).scrollLeft(), visibility: 'visible'\n });\n }\n\n this.Stop = function () {\n //$(\"#\" + divId).hide();\n var modalPopupBehavior = $find('ProgressModalPopupBehaviour');\n if (modalPopupBehavior != null) modalPopupBehavior.hide();\n }\n};\n</code></pre>\n\n<p>The example given conatins a Progress Indicator with Modal ,i:e when progress Indicator is running it disables other operations to be performed on the screen.You can remove the Modal part if you doesnt need it .</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
Just wondering if anyone has seen any usable progress bar for C# .net apps. My app takes about 20-60 secs to load and I would love to show users a progress bar while they wait. I saw [this one](http://www.codeproject.com/KB/aspnet/ASPNETAJAXPageLoader.aspx) but the sample site doesn't seem to work which doesn't inspire confidence.
|
You can use the [AJAX UpdateProgress control](http://ajax.net-tutorials.com/controls/updateprogress-control/).
```
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdateProgress runat="server" id="PageUpdateProgress">
<ProgressTemplate>
Loading...
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" id="Panel">
<ContentTemplate>
<asp:Button runat="server" id="UpdateButton" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
```
If you want animation, all you need to do is pop an animated .gif into the 'ProgressTemplate'.
|
220,879 |
<p>I don't need this, obviously; I'm just curious about what's going on here. Am I missing
something simple? Can I rely on this behaviour in all versions of Perl?)</p>
<p>Perl v5.8.8:</p>
<pre><code>%h = ( 0=>'zero', 1=>'one', 2=>'two' );
while ($k = each %h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
</code></pre>
<p>outputs</p>
<pre><code>deleted one; remaining: zero two
deleted zero; remaining: two
deleted two; remaining:
</code></pre>
<p><code>man perlfunc</code> (each) does not explain why the
while loop continues when <code>$k</code> is assigned 0.
The code behaves as if the condition on the <code>while</code> loop
were <code>($k = each %h, defined $k)</code>.</p>
<p>If the loop condition is actually changed to
<code>($k = each %h, $k)</code> then it does indeed
stop at <code>$k = 0</code> as expected.</p>
<p>It also stops at <code>$k = 0</code> for the following
reimplementation of <code>each</code>:</p>
<pre><code>%h = ( 0=>'zero', 1=>'one', 2=>'two' );
sub each2 {
return each %{$_[0]};
}
while ($k = each2 \%h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
</code></pre>
<p>outputs just:</p>
<pre><code>deleted one; remaining: zero two
</code></pre>
|
[
{
"answer_id": 220999,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 5,
"selected": false,
"text": "<p>You're calling <code>each</code> in scalar context, so it's not working because of a list return value.</p>\n\n<p>Just like</p>\n\n<pre><code>while ($line = <FILE>)\n</code></pre>\n\n<p>is special-cased to add an implicit <code>defined</code>, so is</p>\n\n<pre><code>while ($key = each %hash)\n</code></pre>\n\n<p>In 5.8.8, that happens in op.c, lines 3760-3766:</p>\n\n<pre><code>case OP_SASSIGN:\n if (k1->op_type == OP_READDIR\n || k1->op_type == OP_GLOB\n || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)\n || k1->op_type == OP_EACH)\n expr = newUNOP(OP_DEFINED, 0, expr);\n break;\n</code></pre>\n\n<p>I'm not sure if this applies to all versions of Perl 5.</p>\n\n<p>See also: <a href=\"http://www.perlmonks.org/?node_id=132451\" rel=\"noreferrer\">When does while() test for defined vs truth</a> on PerlMonks. I can't find where this is mentioned in the Perl docs (the <code><FILE></code> case is mentioned, but I don't see the <code>each</code> case).</p>\n"
},
{
"answer_id": 222764,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks, cjm.\nIt was clear some kind of implicit addition of a <code>defined</code>\nwas going on like that for glob but not where it was \ndocumented. Now at least I know the limited cases in which\nthat special handling applies.</p>\n\n<p>But the information should be in the perlfunc documentation,\nnot just the Perl source code!</p>\n"
},
{
"answer_id": 223337,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 3,
"selected": false,
"text": "<p>cjm is right. I just want to add that when coming up against strange things like this its often helpful to run your code through <a href=\"http://search.cpan.org/perldoc?B::Deparse\" rel=\"nofollow noreferrer\">B::Deparse</a> to see how Perl understood your code. I like to use the -p switch to show precedence mistakes, too.</p>\n\n<pre><code>$ perl -MO=Deparse,p your_example.plx\n(%h) = (0, 'zero', 1, 'one', 2, 'two');\nwhile (defined($k = each %h)) {\n $v = delete $h{$k};\n print \"deleted $v; remaining: @h{0..2}\\n\";\n}\nyour_example.plx syntax OK\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I don't need this, obviously; I'm just curious about what's going on here. Am I missing
something simple? Can I rely on this behaviour in all versions of Perl?)
Perl v5.8.8:
```
%h = ( 0=>'zero', 1=>'one', 2=>'two' );
while ($k = each %h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
```
outputs
```
deleted one; remaining: zero two
deleted zero; remaining: two
deleted two; remaining:
```
`man perlfunc` (each) does not explain why the
while loop continues when `$k` is assigned 0.
The code behaves as if the condition on the `while` loop
were `($k = each %h, defined $k)`.
If the loop condition is actually changed to
`($k = each %h, $k)` then it does indeed
stop at `$k = 0` as expected.
It also stops at `$k = 0` for the following
reimplementation of `each`:
```
%h = ( 0=>'zero', 1=>'one', 2=>'two' );
sub each2 {
return each %{$_[0]};
}
while ($k = each2 \%h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
```
outputs just:
```
deleted one; remaining: zero two
```
|
You're calling `each` in scalar context, so it's not working because of a list return value.
Just like
```
while ($line = <FILE>)
```
is special-cased to add an implicit `defined`, so is
```
while ($key = each %hash)
```
In 5.8.8, that happens in op.c, lines 3760-3766:
```
case OP_SASSIGN:
if (k1->op_type == OP_READDIR
|| k1->op_type == OP_GLOB
|| (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
|| k1->op_type == OP_EACH)
expr = newUNOP(OP_DEFINED, 0, expr);
break;
```
I'm not sure if this applies to all versions of Perl 5.
See also: [When does while() test for defined vs truth](http://www.perlmonks.org/?node_id=132451) on PerlMonks. I can't find where this is mentioned in the Perl docs (the `<FILE>` case is mentioned, but I don't see the `each` case).
|
220,887 |
<p>In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing </p>
<pre><code>require "converter.rb"
require "screenFixer.rb"
.
.
.
</code></pre>
<p>at the top of the main class. How do I do this in Java? Is it "import?"</p>
<p>Also, could someone please come up with a better title for this question?</p>
|
[
{
"answer_id": 220904,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>\npublic class Example {\n public Example(IConverter converter, IScreenFixer screenFixer) {\n\n }\n}\n\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Facade_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Facade_pattern</a> ?</p>\n"
},
{
"answer_id": 220921,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 4,
"selected": true,
"text": "<p>If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement.</p>\n\n<p>i.e. </p>\n\n<pre><code>package com.boo;\n\nimport com.foo.Bar;\n\npublic class StackOverflow {\n\nprivate Bar myBar;\n\n}\n</code></pre>\n"
},
{
"answer_id": 220925,
"author": "Alexander K",
"author_id": 17592,
"author_profile": "https://Stackoverflow.com/users/17592",
"pm_score": 1,
"selected": false,
"text": "<p>You don't import you own *.java files in java. Instead you do like this.</p>\n\n<pre><code>javac file1.java file2.java file3.java\njava file1\n</code></pre>\n"
},
{
"answer_id": 220940,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>If these other classes are only going to be used by your 'main' class, there are a couple of options to consider which don't require any imports:</p>\n\n<ul>\n<li>You could make them private static nested classes inside your main class.</li>\n<li>You could make them 'package-access' (the default - no access modifier)</li>\n</ul>\n\n<p>If they're public classes elsewhere, however, you will indeed need an import (or fully qualify them everywhere, but that's horrible).</p>\n"
},
{
"answer_id": 221167,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 1,
"selected": false,
"text": "<p>you should really read a bit about Object Oriented programming.</p>\n\n<p>you don't organize little guys in bigger guy do get work done.</p>\n\n<p>Classes in hold some data and provide method to manipulate that data in meaninful ways. Data usually are variables of some other Class, you must declare where from do you get those. You do this declaration by specifying import statement. </p>\n\n<p>BTW you should explicitly create a class instance to use it, i.e. invoke class constructor method</p>\n\n<pre><code>package com.foo;\nimport com.foo.Bar;\n\npublic class StackOverflow {\n\nprivate Bar myBar;\n public StackOverflow() { //this is a constructor of StackOverflow class\n myBar = new Bar(); //i'm invoking constructor of Bar class\n }\n}\n</code></pre>\n"
},
{
"answer_id": 221312,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "<p>If all the classes you write are in the same package you do not need to do anything special to use them. If class A wants the service of class B then in class A you may just instantiate an object of B and invoke the methods of B that you want.</p>\n\n<p>If the classes are in different packages however, or if you are using classes from third parties then you will need an import statement</p>\n\n<pre><code>import package.ClasName;\n</code></pre>\n\n<p>at the top of the file in which you refer to the class.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing
```
require "converter.rb"
require "screenFixer.rb"
.
.
.
```
at the top of the main class. How do I do this in Java? Is it "import?"
Also, could someone please come up with a better title for this question?
|
If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement.
i.e.
```
package com.boo;
import com.foo.Bar;
public class StackOverflow {
private Bar myBar;
}
```
|
220,891 |
<p>I have a COM SDK written in C++ and I'd like to create documentation for my product. I understand that most people will probably not use C++ for integration with this COM component, but many will. </p>
<p>Which method is best to describe the API, without losing details that a C++ developer would need to know. </p>
|
[
{
"answer_id": 220904,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>\npublic class Example {\n public Example(IConverter converter, IScreenFixer screenFixer) {\n\n }\n}\n\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Facade_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Facade_pattern</a> ?</p>\n"
},
{
"answer_id": 220921,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 4,
"selected": true,
"text": "<p>If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement.</p>\n\n<p>i.e. </p>\n\n<pre><code>package com.boo;\n\nimport com.foo.Bar;\n\npublic class StackOverflow {\n\nprivate Bar myBar;\n\n}\n</code></pre>\n"
},
{
"answer_id": 220925,
"author": "Alexander K",
"author_id": 17592,
"author_profile": "https://Stackoverflow.com/users/17592",
"pm_score": 1,
"selected": false,
"text": "<p>You don't import you own *.java files in java. Instead you do like this.</p>\n\n<pre><code>javac file1.java file2.java file3.java\njava file1\n</code></pre>\n"
},
{
"answer_id": 220940,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>If these other classes are only going to be used by your 'main' class, there are a couple of options to consider which don't require any imports:</p>\n\n<ul>\n<li>You could make them private static nested classes inside your main class.</li>\n<li>You could make them 'package-access' (the default - no access modifier)</li>\n</ul>\n\n<p>If they're public classes elsewhere, however, you will indeed need an import (or fully qualify them everywhere, but that's horrible).</p>\n"
},
{
"answer_id": 221167,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 1,
"selected": false,
"text": "<p>you should really read a bit about Object Oriented programming.</p>\n\n<p>you don't organize little guys in bigger guy do get work done.</p>\n\n<p>Classes in hold some data and provide method to manipulate that data in meaninful ways. Data usually are variables of some other Class, you must declare where from do you get those. You do this declaration by specifying import statement. </p>\n\n<p>BTW you should explicitly create a class instance to use it, i.e. invoke class constructor method</p>\n\n<pre><code>package com.foo;\nimport com.foo.Bar;\n\npublic class StackOverflow {\n\nprivate Bar myBar;\n public StackOverflow() { //this is a constructor of StackOverflow class\n myBar = new Bar(); //i'm invoking constructor of Bar class\n }\n}\n</code></pre>\n"
},
{
"answer_id": 221312,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "<p>If all the classes you write are in the same package you do not need to do anything special to use them. If class A wants the service of class B then in class A you may just instantiate an object of B and invoke the methods of B that you want.</p>\n\n<p>If the classes are in different packages however, or if you are using classes from third parties then you will need an import statement</p>\n\n<pre><code>import package.ClasName;\n</code></pre>\n\n<p>at the top of the file in which you refer to the class.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
I have a COM SDK written in C++ and I'd like to create documentation for my product. I understand that most people will probably not use C++ for integration with this COM component, but many will.
Which method is best to describe the API, without losing details that a C++ developer would need to know.
|
If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement.
i.e.
```
package com.boo;
import com.foo.Bar;
public class StackOverflow {
private Bar myBar;
}
```
|
220,902 |
<p>I'm building a python application from some source code I've found <a href="http://code.google.com/p/enso" rel="nofollow noreferrer">Here</a></p>
<p>I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:</p>
<p>When running the application this message appears.</p>
<p><a href="http://img511.imageshack.us/img511/4481/loadfr0.png" rel="nofollow noreferrer">alt text http://img511.imageshack.us/img511/4481/loadfr0.png</a></p>
<p>This python app, usues swig to link to c/c++ code.</p>
<p>I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too ) </p>
<p>The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.</p>
<p>For what I've read in here:
<a href="http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx</a></p>
<p>The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.</p>
<p>Could anyone point me to the correct direction?</p>
<p>This is the content of the manifest fie:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.</p>
<p>ps. if only everything was as easy as jar files :( </p>
<p>This is the stack trace for completeness</p>
<pre><code>None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÝnculos dinßmicos (DLL).
</code></pre>
|
[
{
"answer_id": 220955,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>You probably need to install the VC++ runtime redistributables. The links to them are <a href=\"https://stackoverflow.com/questions/99479/visual-cstudio-application-configuration-incorrect#100310\">here</a>.</p>\n"
},
{
"answer_id": 221092,
"author": "Spike Curtis",
"author_id": 29882,
"author_profile": "https://Stackoverflow.com/users/29882",
"pm_score": 1,
"selected": true,
"text": "<p>I've been able to compile and run Enso by using /LD as a compiler flag. This links dynamically to the MS Visual C++ runtime, and seems to allow you to get away without a manifest.</p>\n\n<p>If you're using SCons, see the diff file here: <a href=\"http://paste2.org/p/69732\" rel=\"nofollow noreferrer\">http://paste2.org/p/69732</a></p>\n"
},
{
"answer_id": 221200,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p><strong>update</strong>\nI've downloaded python2.6 and VS C++ express edition 2008 and the problem with the msvcr80.dll is gone ( I assume because Python and VSC++2008xe use msvscr90.dll) </p>\n\n<p>I've compile with /LD and all the changes listed here: <a href=\"http://paste2.org/p/69732\" rel=\"nofollow noreferrer\">http://paste2.org/p/69732</a> </p>\n\n<p>And now the problem follows:</p>\n\n<pre><code>INFO:root:Skipping provider enso.platform.osx.\nINFO:root:Skipping provider enso.platform.linux.\nINFO:root:Added provider enso.platform.win32.\nINFO:root:Obtained interface 'input' from provider 'enso.platform.win32'.\nTraceback (most recent call last):\n File \"scripts\\run_enso.py\", line 23, in <module>\n enso.run()\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\__init__.py\", line 41, in run\n from enso.quasimode import Quasimode\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\quasimode\\__init__.py\", line 62, in <module>\n from enso.quasimode.window import TheQuasimodeWindow\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\quasimode\\window.py\", line 65, in <module>\n from enso.quasimode.linewindows import TextWindow\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\quasimode\\linewindows.py\", line 44, in <module>\n from enso import cairo\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\cairo.py\", line 3, in <module>\n __cairoImpl = enso.providers.getInterface( \"cairo\" )\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\providers.py\", line 137, in getInterface\n interface = provider.provideInterface( name )\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\platform\\win32\\__init__.py\", line 61, in provideInterface\n import enso.platform.win32.cairo\n File \"C:\\oreyes\\apps\\enso\\enso-comunity\\enso\\platform\\win32\\cairo\\__init__.py\", line 1, in <module>\n from _cairo import *\nImportError: No module named _cairo\n</code></pre>\n"
},
{
"answer_id": 222263,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at your update, it looks like you need to install <a href=\"http://www.cairographics.org/pycairo/\" rel=\"nofollow noreferrer\">Pycairo</a> since you're missing the _cairo module installed as part of Pycairo. See the <a href=\"http://www.cairographics.org/download/\" rel=\"nofollow noreferrer\">Pycairo downloads page</a> for instructions on how to obtain/install binaries for Windows.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I'm building a python application from some source code I've found [Here](http://code.google.com/p/enso)
I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:
When running the application this message appears.
[alt text http://img511.imageshack.us/img511/4481/loadfr0.png](http://img511.imageshack.us/img511/4481/loadfr0.png)
This python app, usues swig to link to c/c++ code.
I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too )
The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.
For what I've read in here:
<http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx>
The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.
Could anyone point me to the correct direction?
This is the content of the manifest fie:
```
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
```
I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.
ps. if only everything was as easy as jar files :(
This is the stack trace for completeness
```
None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÝnculos dinßmicos (DLL).
```
|
I've been able to compile and run Enso by using /LD as a compiler flag. This links dynamically to the MS Visual C++ runtime, and seems to allow you to get away without a manifest.
If you're using SCons, see the diff file here: <http://paste2.org/p/69732>
|
220,966 |
<p>I have a 2 variable 100x100 data table in excel.</p>
<p>I need to have a function that returns all the possible sets of variables that yield a given target value.
What I am looking at is some kind of a reursive 2 dimensional lookup function. Can someone point me in the right direction?</p>
|
[
{
"answer_id": 221164,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>Would the Solver suit?</p>\n\n<p><a href=\"http://office.microsoft.com/en-us/excel/HA011118641033.aspx\" rel=\"nofollow noreferrer\">http://office.microsoft.com/en-us/excel/HA011118641033.aspx</a></p>\n"
},
{
"answer_id": 221395,
"author": "Vaibhav Garg",
"author_id": 27795,
"author_profile": "https://Stackoverflow.com/users/27795",
"pm_score": 0,
"selected": false,
"text": "<p>I tried this a lot without using VBA but doesn't seem to be possible without it. \nTo solve this issue , I needed to loop through the entire array and found closest values. These values were then derefernced using calls and range properties and the output was generated in a range being incremented at each valid match.</p>\n\n<p>The quick and dirty implementation is as under:</p>\n\n<pre><code>Dim arr As Range\nDim tempval As Range\nDim op As Integer\n\nSet arr = Worksheets(\"sheet1\").Range(\"b2:ao41\")\nop = 1\nRange(\"B53:D153\").ClearContents\n\n\n\n\n\nFor Each tempval In arr\nIf Round(tempval.Value, 0) = Round(Range(\"b50\").Value, 0) Then\n\nRange(\"b52\").Offset(op, 0).Value = Range(\"a\" & tempval.Row).Value\nRange(\"b52\").Offset(op, 1).Value = Cells(tempval.Column, 1).Value\nRange(\"b52\").Offset(op, 2).Value = tempval.Value\nop = op + 1\n\nEnd If\n\nNext\nRange(\"b50\").Select\n</code></pre>\n\n<p>I am still looking for an approach without VBA.</p>\n"
},
{
"answer_id": 221447,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>There is no built-in function that will do what you want, I'm 99% sure of that.</p>\n\n<p>A VBA function that returns an array could be built, along the lines of the quick-and-dirty Sub already shown. Create an Variant to hold the output, perhaps Redimmed to the maximum possible number of results and Redim Preserve-d down to the actual number at the end. Then return that as the result of the function which then needs to be called as an array function (Control-Shift-Enter).</p>\n\n<p>One down-side is that you'd have to ensure that the target range was large enough to hold the entire result: Excel won't do that automatically.</p>\n"
},
{
"answer_id": 221678,
"author": "Mark Pattison",
"author_id": 15519,
"author_profile": "https://Stackoverflow.com/users/15519",
"pm_score": 0,
"selected": false,
"text": "<p>I've got a solution that doesn't use VBA, but it's fairly messy. It involves creating a further one-dimensional table in Excel and doing lookups on that. For a 100x100 data table, the new table would need 10,000 rows.</p>\n\n<p>Apologies if this doesn't fit your needs.</p>\n\n<p>A summary is below - let me know if you need more detail. N = the dimension of the data, e.g. 100 in your example.</p>\n\n<p>First, create a new table with five columns and NxN rows. In each case, replace my column names with the appropriate Excel reference</p>\n\n<p>The first column (call it INDEX) simply lists 1, 2... NxN.</p>\n\n<p>The second column (DATAROW) contains a formula to loop through 1, 2... N, 1, 2...N... This can be done using something like =MOD(INDEX-1, N)+1</p>\n\n<p>The third column (DATACOL) contains 1, 1, 1... 2, 2, 2... (N times each).\nThis can be done with =INT((INDEX-1)/N)+1</p>\n\n<p>The fourth column (VALUE) contains the value from your data table, using something like:\n=OFFSET($A$1, DATAROW, DATACOL), assuming your data table starts at $A$1</p>\n\n<p>We have now got a one-dimensional table holding all your data.</p>\n\n<p>The fifth column (LOOKUP) contains the formula:\n=MATCH(target, OFFSET(VALUERANGE, [LOOKUP-1], 0),0)+ [LOOKUP-1]</p>\n\n<p>where [LOOKUP-1] refers to the cell immediately above (e.g. in cell F4 this refers to F3). You'll need a 0 above the first cell in the LOOKUP column.</p>\n\n<p>VALUERANGE should be a fixed (named or using $ signs) reference to the entire VALUE column.</p>\n\n<p>The LOOKUP column then holds INDEX numbers which can be used to look up DATAROW and DATACOL to find the position of the match in the data.</p>\n\n<p>This works by searching for matches in VALUERANGE, then searching for matches in an adjusted range starting after the previous match.</p>\n\n<p>It's much easier in a spreadsheet then via the explanation above, but that's the best I can do for the moment...</p>\n"
},
{
"answer_id": 221812,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 2,
"selected": true,
"text": "<p>It can be done without VBA, fairly compactly, like so.</p>\n<p>Suppose your 100x100 table is in B2:CW101, and we put a list of numbers 1 to 100 down the left from A2 to A101, and again 1 to 100 across the top from B1 to CW1</p>\n<p>Create a column of cells underneath, starting (say) in B104</p>\n<pre><code> B104=MAX(($A$2:$A$101*100+$B$1:$CW$1<B103)*($B$2:$CW$101=TargetValue)*($A$2:$A$101*100+$B$1:$CW$1))\n</code></pre>\n<p>This is an "array" formula,so press <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>Enter</kbd> instead of <kbd>Enter</kbd>, and curly brackets {} should appear around the formula.</p>\n<p>Then copy down for as many rows as you might need. You also need to put a large number above your first formula, i.e. in B103, e.g. 999999.</p>\n<p>What the formula does is to calculate Rowx100+Column, but only for each successful cell, and the MAX function finds the largest result, excluding all previous results found, i.e. it finds the target results one at a time, starting from bottom right and working up to top left. (With a little effort you could get it to search the other way).</p>\n<p>This will give you results like 9922, which is row 99, column 22, and you can easily extract these values from the number.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27795/"
] |
I have a 2 variable 100x100 data table in excel.
I need to have a function that returns all the possible sets of variables that yield a given target value.
What I am looking at is some kind of a reursive 2 dimensional lookup function. Can someone point me in the right direction?
|
It can be done without VBA, fairly compactly, like so.
Suppose your 100x100 table is in B2:CW101, and we put a list of numbers 1 to 100 down the left from A2 to A101, and again 1 to 100 across the top from B1 to CW1
Create a column of cells underneath, starting (say) in B104
```
B104=MAX(($A$2:$A$101*100+$B$1:$CW$1<B103)*($B$2:$CW$101=TargetValue)*($A$2:$A$101*100+$B$1:$CW$1))
```
This is an "array" formula,so press `Ctrl`-`Shift`-`Enter` instead of `Enter`, and curly brackets {} should appear around the formula.
Then copy down for as many rows as you might need. You also need to put a large number above your first formula, i.e. in B103, e.g. 999999.
What the formula does is to calculate Rowx100+Column, but only for each successful cell, and the MAX function finds the largest result, excluding all previous results found, i.e. it finds the target results one at a time, starting from bottom right and working up to top left. (With a little effort you could get it to search the other way).
This will give you results like 9922, which is row 99, column 22, and you can easily extract these values from the number.
|
220,975 |
<p>How to put underline for first letter for access key for ?</p>
|
[
{
"answer_id": 220985,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>Tried the AccessKey attribute?</p>\n\n<pre><code><asp:button id=\"Button1\" runat=\"server\" Text=\"Print\" AccessKey=\"P\" />\n</code></pre>\n\n<p>If it is really underlined is out of your control. The user agent (e.g. browser) is deciding that.</p>\n"
},
{
"answer_id": 221022,
"author": "Rob Bell",
"author_id": 2179408,
"author_profile": "https://Stackoverflow.com/users/2179408",
"pm_score": 2,
"selected": false,
"text": "<p>asp:buttons are output as html \"input\" tags with a type of \"submit\". The text displayed on them is output in the \"value\" attribute of the tag, and so cannot contain any styling or html. If you could get an asp:button to output as an html button then you could try something like:</p>\n\n<pre><code><button id=\"mybutton\" runat=\"server\" onserverclick=\"myfunction\">\n<span style=\"text-decoration:underline;\">P</span>rint</button>\n</code></pre>\n\n<p>and use a normal button event in your c# code:</p>\n\n<pre><code>protected void myfunction(object sender, EventArgs e)\n{\n Response.Write(\"clicked\");\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29867/"
] |
How to put underline for first letter for access key for ?
|
asp:buttons are output as html "input" tags with a type of "submit". The text displayed on them is output in the "value" attribute of the tag, and so cannot contain any styling or html. If you could get an asp:button to output as an html button then you could try something like:
```
<button id="mybutton" runat="server" onserverclick="myfunction">
<span style="text-decoration:underline;">P</span>rint</button>
```
and use a normal button event in your c# code:
```
protected void myfunction(object sender, EventArgs e)
{
Response.Write("clicked");
}
```
|
220,982 |
<p>I have all my entities in a seperate project in my edmx file and I expose them to my client application using a WCF service.</p>
<p>That means I don't have to give my client app a direct link to the project that contains the edmx file. That would be bad because it contines the object to query the database with.</p>
<p>But only the entities that my WCF service uses can be accessed from my client app. So for example because I have the following code in my service:</p>
<pre><code>public MyClass GetMyClass()
{
return new MyClass();
}
</code></pre>
<p>.. I can use access MyClass in my client app with something like:</p>
<pre><code>myServiceInstance.MyClass cls = new myServiceInstance.MyClass()
</code></pre>
<p>What about if I have an entity called MyClass2 in my edmx file that I want to use in my client app! How to I instansiate it without giving my client a direct link to my edmx file project or making a usless method in my service layer that returns MyClass2</p>
<p>What are other people doing?</p>
<p>Thanks a lot </p>
|
[
{
"answer_id": 220992,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>If the WCF service doesn't use it, what would you want it for? A WCF service (itself) is purely for data transport - the \"mex\" approach for metadata doesn't share code, so your MyClass2 would be impotent. If you want, you can use assembly sharing at the client, but I <em>really</em> don't recommend this in this case; EF objects at the client is a mess... (plus it won't work on the lightweight frameworks like Silverlight, Client Profile, Compact Framework, etc)</p>\n\n<p>Another option is <a href=\"http://msdn.microsoft.com/en-us/data/bb931106.aspx\" rel=\"nofollow noreferrer\">ADO.NET Data Services</a>; this works over WCF, but gives you a more LINQ-friendly API than the regular WCF approach - and any domain objects that your model exposes should be available on the client data-context.</p>\n"
},
{
"answer_id": 221089,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 2,
"selected": false,
"text": "<p>We created a <strong>separate project</strong> with Domain Transfer Object Classes that served as Data Contracts for our various <strong>internal</strong> WCF services. We then shared the contracts project with those internal services. We had one data service; those methods would translate these domain objects to/from entity objects before/after storing/retrieving. Meanwhile, the external services made use of the standard proxies generated from XSD and WSDL files, and translated to/from the shared domain transfer model.</p>\n\n<p>We had to do this because <strong>the object context is not (yet) portable over WCF</strong>, unfortunately.</p>\n\n<p>Some considerations for your situation:</p>\n\n<ol>\n<li>If your client app is <strong>external</strong> to your system, it should not know anything about your EDMX or its classes. It should only know about your WSDL and XSD. </li>\n<li>If your client app is <strong>internal</strong>, then it is no use trying to share the entity classes in EF v1 because it is not supported properly, yet. You need to transfer more than just the classes/objects - you need the context too, which maintains change tracking, and it cannot be done via WCF directly right now.</li>\n</ol>\n"
},
{
"answer_id": 221690,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to do it the \"proper\" way, you should be creating special classes for your messages that are going across the wire, rather than trying to reuse business entities or data objects as messages. The value in this is that you are then free to change your business entities and data objects without worrying about the contract you have exposed to consumers changing. Every change to your service is a bit more deliberate since it happens independently of changes to data and business logic.</p>\n\n<p>Another way to handle this is simply to use svcutil (or \"Add service reference...\" though svcutil works better for multiple service endpoints) to generate all the classes that the client will be using instead of adding a reference to the server project. That way, the only classes your client will ever see are the ones exposed by the service.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/220982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have all my entities in a seperate project in my edmx file and I expose them to my client application using a WCF service.
That means I don't have to give my client app a direct link to the project that contains the edmx file. That would be bad because it contines the object to query the database with.
But only the entities that my WCF service uses can be accessed from my client app. So for example because I have the following code in my service:
```
public MyClass GetMyClass()
{
return new MyClass();
}
```
.. I can use access MyClass in my client app with something like:
```
myServiceInstance.MyClass cls = new myServiceInstance.MyClass()
```
What about if I have an entity called MyClass2 in my edmx file that I want to use in my client app! How to I instansiate it without giving my client a direct link to my edmx file project or making a usless method in my service layer that returns MyClass2
What are other people doing?
Thanks a lot
|
If the WCF service doesn't use it, what would you want it for? A WCF service (itself) is purely for data transport - the "mex" approach for metadata doesn't share code, so your MyClass2 would be impotent. If you want, you can use assembly sharing at the client, but I *really* don't recommend this in this case; EF objects at the client is a mess... (plus it won't work on the lightweight frameworks like Silverlight, Client Profile, Compact Framework, etc)
Another option is [ADO.NET Data Services](http://msdn.microsoft.com/en-us/data/bb931106.aspx); this works over WCF, but gives you a more LINQ-friendly API than the regular WCF approach - and any domain objects that your model exposes should be available on the client data-context.
|
221,001 |
<p>I want to convert from char representing a hexadecimal value (in upper or lower case) to byte, like</p>
<pre><code>'0'->0, '1' -> 1, 'A' -> 10, 'a' -> 10, 'f' -> 15 etc...
</code></pre>
<p>I will be calling this method extremely often, so performance is important. Is there a faster way than to use a pre-initialized <code>HashMap<Character,Byte></code> to get the value from?</p>
<p><strong>Answer</strong></p>
<p>It seems like <s>it's a tossup between using a switch-case and Jon Skeet's direct computing solution - the switch-case solution seems to edge out ever so slightly, though.</s> Greg's array method wins out. Here are the performance results (in ms) for 200,000,000 runs of the various methods:</p>
<pre><code>Character.getNumericValue:
8360
Character.digit:
8453
HashMap<Character,Byte>:
15109
Greg's Array Method:
6656
JonSkeet's Direct Method:
7344
Switch:
7281
</code></pre>
<p>Thanks guys!</p>
<p><strong>Benchmark method code</strong></p>
<p>Here ya go, JonSkeet, you old competitor. ;-)</p>
<pre><code>public class ScratchPad {
private static final int NUMBER_OF_RUNS = 200000000;
static byte res;
static HashMap<Character, Byte> map = new HashMap<Character, Byte>() {{
put( Character.valueOf( '0' ), Byte.valueOf( (byte )0 ));
put( Character.valueOf( '1' ), Byte.valueOf( (byte )1 ));
put( Character.valueOf( '2' ), Byte.valueOf( (byte )2 ));
put( Character.valueOf( '3' ), Byte.valueOf( (byte )3 ));
put( Character.valueOf( '4' ), Byte.valueOf( (byte )4 ));
put( Character.valueOf( '5' ), Byte.valueOf( (byte )5 ));
put( Character.valueOf( '6' ), Byte.valueOf( (byte )6 ));
put( Character.valueOf( '7' ), Byte.valueOf( (byte )7 ));
put( Character.valueOf( '8' ), Byte.valueOf( (byte )8 ));
put( Character.valueOf( '9' ), Byte.valueOf( (byte )9 ));
put( Character.valueOf( 'a' ), Byte.valueOf( (byte )10 ));
put( Character.valueOf( 'b' ), Byte.valueOf( (byte )11 ));
put( Character.valueOf( 'c' ), Byte.valueOf( (byte )12 ));
put( Character.valueOf( 'd' ), Byte.valueOf( (byte )13 ));
put( Character.valueOf( 'e' ), Byte.valueOf( (byte )14 ));
put( Character.valueOf( 'f' ), Byte.valueOf( (byte )15 ));
put( Character.valueOf( 'A' ), Byte.valueOf( (byte )10 ));
put( Character.valueOf( 'B' ), Byte.valueOf( (byte )11 ));
put( Character.valueOf( 'C' ), Byte.valueOf( (byte )12 ));
put( Character.valueOf( 'D' ), Byte.valueOf( (byte )13 ));
put( Character.valueOf( 'E' ), Byte.valueOf( (byte )14 ));
put( Character.valueOf( 'F' ), Byte.valueOf( (byte )15 ));
}};
static int[] charValues = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10, 11, 12, 13,14,15};
static char[] cs = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','A','B','C','D','E','F'};
public static void main(String args[]) throws Exception {
long time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getNumericValue( i );
}
System.out.println( "Character.getNumericValue:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getDigit( i );
}
System.out.println( "Character.digit:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
try {
res = getValueFromArray( i );
} catch (IllegalArgumentException e) {
}
}
System.out.println( "Array:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getValueFromHashMap( i );
}
System.out.println( "HashMap<Character,Byte>:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
char c = cs[i%cs.length];
res = getValueFromComputeMethod( c );
}
System.out.println( "JonSkeet's Direct Method:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getValueFromSwitch( i );
}
System.out.println( "Switch:" );
System.out.println( System.currentTimeMillis()-time );
}
private static byte getValueFromSwitch( int i ) {
byte res;
char ch = cs[i%cs.length];
switch( ch ) {
case '0':
res = 0;
break;
case '1':
res = 1;
break;
case '2':
res = 2;
break;
case '3':
res = 3;
break;
case '4':
res = 4;
break;
case '5':
res = 5;
break;
case '6':
res = 6;
break;
case '7':
res = 7;
break;
case '8':
res = 8;
break;
case '9':
res = 9;
break;
case 'a':
case 'A':
res = 10;
break;
case 'b':
case 'B':
res = 11;
break;
case 'c':
case 'C':
res = 12;
break;
case 'd':
case 'D':
res = 13;
break;
case 'e':
case 'E':
res = 14;
break;
case 'f':
case 'F':
res = 15;
break;
default:
throw new RuntimeException("unknown hex character: " + ch );
}
return res;
}
private static byte getValueFromComputeMethod( char c ) {
byte result = 0;
if (c >= '0' && c <= '9')
{
result = (byte)(c - '0');
}
if (c >= 'a' && c <= 'f')
{
result = (byte)(c - 'a' + 10);
}
if (c >= 'A' && c <= 'F')
{
result = (byte)(c - 'A' + 10);
}
return result;
}
private static byte getValueFromHashMap( int i ) {
return map.get( Character.valueOf( cs[i%cs.length] ) ).byteValue();
}
private static byte getValueFromArray( int i ) {
char c = cs[i%cs.length];
if (c < '0' || c > 'f') {
throw new IllegalArgumentException();
}
byte result = (byte)charValues[c-'0'];
if (res < 0) {
throw new IllegalArgumentException();
}
return result;
}
private static byte getDigit( int i ) {
return (byte)Character.digit( cs[i%cs.length], 16 );
}
private static byte getNumericValue( int i ) {
return (byte)Character.getNumericValue( cs[i%cs.length] );
}
}
</code></pre>
|
[
{
"answer_id": 221012,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>A hash table would be relatively slow. This is pretty quick:</p>\n\n<pre><code>if (c >= '0' && c <= '9')\n{\n return c - '0';\n}\nif (c >= 'a' && c <= 'f')\n{\n return c - 'a' + 10;\n}\nif (c >= 'A' && c <= 'F')\n{\n return c - 'A' + 10;\n}\nthrow new IllegalArgumentException();\n</code></pre>\n\n<p>Another option would be to try a switch/case statement. An array might be okay if it's in cache, but a miss could be expensive.</p>\n"
},
{
"answer_id": 221020,
"author": "Keeg",
"author_id": 21059,
"author_profile": "https://Stackoverflow.com/users/21059",
"pm_score": 2,
"selected": false,
"text": "<p>Character.getNumericValue(char) is another way:</p>\n\n<pre><code>char c = 'a';\nSystem.out.println(c + \"->\" + Character.getNumericValue(c));\n</code></pre>\n\n<p>Prints 'a->10' like you want for instance. Someone else would have to comment on the efficiency of a static metod call vs a HashMap lookup, or you could check it out for yourself. It seems cleaner/more readable to me though.</p>\n"
},
{
"answer_id": 221024,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>A preinitialised array would be faster than a HashMap. Something like this:</p>\n\n<pre><code>int CharValues['f'-'0'+1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, ... -1, 10, 11, 12, ...};\n\nif (c < '0' || c > 'f') {\n throw new IllegalArgumentException();\n}\nint n = CharValues[c-'0'];\nif (n < 0) {\n throw new IllegalArgumentException();\n}\n// n contains the digit value\n</code></pre>\n\n<p>You should benchmark this method against other methods (such as <a href=\"https://stackoverflow.com/questions/221001/performance-question-fastest-way-to-convert-hexadecimal-char-to-its-number-valu#221012\">Jon Skeet's</a> direct method) to determine which will be the fastest for your application.</p>\n"
},
{
"answer_id": 221071,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 2,
"selected": false,
"text": "<p>simple, but slow:</p>\n\n<pre><code>int i = Integer.parseInt(String.ValueOf(c), 16);\n</code></pre>\n\n<p>faster:</p>\n\n<pre><code>int i = Character.digit(c, 16);\n</code></pre>\n\n<p>I wont use any special code for \"performance issues\". If you really often use this, the JIT will create compiled code and execution will become fast. Keep your code clean. You may have a try and write a performace test comparing the execution time from the code above and any special implementation - i bet you wont get significant improvements.</p>\n"
},
{
"answer_id": 221073,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 2,
"selected": false,
"text": "<p>Using an array should be fastest.</p>\n\n<p>An array could be of size 16, 16^2, 16^3, 16^4 etc..</p>\n\n<p>Converting the number in larger groups than one would give a performance increase.</p>\n\n<p>There will be a sweet spot where it is most worthwhile, possibly 4 digits (64k table).</p>\n"
},
{
"answer_id": 221111,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think you can beat a direct array lookup.</p>\n\n<pre><code>static final int[] precalc = new int['f'+1];\nstatic {\n for (char c='0'; c<='9'; c++) precalc[c] = c-'0';\n for (char c='A'; c<='F'; c++) precalc[c] = c-'A';\n for (char c='a'; c<='f'; c++) precalc[c] = c-'a';\n}\n\nSystem.out.println(precalc['f']);\n</code></pre>\n"
},
{
"answer_id": 221134,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my tweaked version of Greg's code. On my box it's <em>marginally</em> faster - but probably within the noise. It avoids the lower bound check, and doesn't need to do any subtraction. Creating a 64K array and avoiding <em>either</em> bound check appeared to slow things down - but again, with timing like this it's virtually impossible to be sure what's real and what's noise.</p>\n\n<pre><code>public class HexParser\n{\n private static final byte VALUES = new int['f'];\n\n // Easier to get right for bozos like me (Jon) than\n // a hard-coded array :)\n static\n {\n for (int i=0; i < VALUES.length; i++)\n {\n VALUES[i] = (byte) -1;\n }\n for (int i='0'; i <= '9'; i++)\n {\n VALUES[i] = (byte) i-'0';\n }\n for (int i='A'; i <= 'F'; i++)\n {\n VALUES[i] = (byte) (i-'A'+10);\n }\n for (int i='a'; i <= 'f'; i++)\n {\n VALUES[i] = (byte) (i-'a'+10);\n }\n }\n\n public static byte parseHexChar(char c)\n {\n if (c > 'f')\n {\n throw new IllegalArgumentException();\n }\n byte ret = VALUES[c];\n if (ret == -1)\n {\n throw new IllegalArgumentException();\n }\n return ret;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 379653,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 2,
"selected": false,
"text": "<pre><code>int CharValues[256] = \n{\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,0,1,2,3,4,5,6,7,8,9,16,16,16,16,16,16,16,\n16,10,11,12,13,14,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,10,11,12,13,14,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\n16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16\n}\n\nint n = CharValues[c];\n\nif (n == 16)\n throw new IllegalArgumentException();\n\n// n contains the digit value\n</code></pre>\n"
},
{
"answer_id": 798803,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 3,
"selected": false,
"text": "<p>I don't recall seeing this method before, but Mikko Rantanen pointed this equation out in a comment on the question, <a href=\"https://stackoverflow.com/questions/795027/code-golf-hex-to-raw-binary-conversion\">Code golf - hex to (raw) binary conversion</a></p>\n\n<pre><code>(char | 32) % 39 - 9\n</code></pre>\n\n<p>I don't know what it would benchmark as (perhaps someone can add it to the benchmark above and run it, but I'm guessing the % kills the performance) - but it's a neat, simple one-liner for single character hexadecimal to decimal conversion. Handles 0-9, A-F, a-f.</p>\n"
},
{
"answer_id": 799734,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 2,
"selected": false,
"text": "<p>It worth noting that you are realing timing the % operation in most of your tests. This operation takes about the same amount of time as some of the other options.</p>\n\n<pre><code>private static byte lookUpTest(int i) {\n return (byte) cs[i%cs.length];\n}\n</code></pre>\n"
},
{
"answer_id": 17894129,
"author": "mauricio_martins",
"author_id": 2517201,
"author_profile": "https://Stackoverflow.com/users/2517201",
"pm_score": 2,
"selected": false,
"text": "<p>Dude, I'm microcontroller programmer and in this tiny world, speed really matters. The fastest way to convert an 'ASCII' digit to byte (from 'A' to 0x0A) is using this small piece of code</p>\n\n<pre><code>c|=0x20;\nreturn c<='9'? c+0xD0 : c+0xA9;\n</code></pre>\n\n<p>The magic of this command is simple, if you look the ascii table you'll find numbers starting with 0x3_, and letters at columns 0x4_ and 0x6_ respectively. \n1) if you \"or\" the incoming char (variable \"c\") with 0x20, you'll be never changing numbers... but for letters you'll be converting uppercase to lowercase. Since we are looking for only A..F(a..f) values... I don't care others.\n2) now the magic. To avoid subtractions, I use additive operators. the 0xD0 is the same of -0x30, and 0xA9 is the same of -'a'+10; </p>\n\n<p>the branch instruction generated by the comparison is pretty simple and didn't take the overhead of table lookups and neither \"mod\" or other operators!</p>\n\n<p>Enjoy... </p>\n"
},
{
"answer_id": 17894227,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 1,
"selected": false,
"text": "<p>A table of 16-bit values where you could look up two digits at a time should be quicker than the 8-bit-value arrays suggested in other answers. You would be iterating the data twice as quickly, accessing the array half as often, and accessing shorts instead of bytes, all of which gives the CPU less to do and more to do it with.</p>\n\n<p>The 8-bit values would be precomputed as <code>x[Integer.toHexString(i).charAt[0]] = i</code> for <code>0 <= i < 256</code>. Then you would just lookup <code>x[c]</code> for each char <code>c</code> in the hex string. You would probably want to duplicate the entries for both upper-case and lower-case variants of each hex value.</p>\n\n<p>A table of 32-bit values should be even quicker, depending on how much space you can afford.</p>\n"
},
{
"answer_id": 56837705,
"author": "Florian F",
"author_id": 3450840,
"author_profile": "https://Stackoverflow.com/users/3450840",
"pm_score": 1,
"selected": false,
"text": "<p>According to my timings the following outperforms Jon Skeet's already pretty efficient method.</p>\n\n<p>The idea is to take advantage of the test on range 'A'..'F' to also discard one of the ranges '0'..'9' or 'a'..'f'.</p>\n\n<pre><code>public static int hex2Dig2(char c) {\n if (c < 'A') {\n if (c >= '0' && c <= '9')\n return c - '0';\n } else if (c > 'F') {\n if (c >= 'a' && c <= 'f')\n return c - 'a' + 10;\n } else {\n return c - 'A' + 10;\n }\n return -1; // or throw exception\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
I want to convert from char representing a hexadecimal value (in upper or lower case) to byte, like
```
'0'->0, '1' -> 1, 'A' -> 10, 'a' -> 10, 'f' -> 15 etc...
```
I will be calling this method extremely often, so performance is important. Is there a faster way than to use a pre-initialized `HashMap<Character,Byte>` to get the value from?
**Answer**
It seems like ~~it's a tossup between using a switch-case and Jon Skeet's direct computing solution - the switch-case solution seems to edge out ever so slightly, though.~~ Greg's array method wins out. Here are the performance results (in ms) for 200,000,000 runs of the various methods:
```
Character.getNumericValue:
8360
Character.digit:
8453
HashMap<Character,Byte>:
15109
Greg's Array Method:
6656
JonSkeet's Direct Method:
7344
Switch:
7281
```
Thanks guys!
**Benchmark method code**
Here ya go, JonSkeet, you old competitor. ;-)
```
public class ScratchPad {
private static final int NUMBER_OF_RUNS = 200000000;
static byte res;
static HashMap<Character, Byte> map = new HashMap<Character, Byte>() {{
put( Character.valueOf( '0' ), Byte.valueOf( (byte )0 ));
put( Character.valueOf( '1' ), Byte.valueOf( (byte )1 ));
put( Character.valueOf( '2' ), Byte.valueOf( (byte )2 ));
put( Character.valueOf( '3' ), Byte.valueOf( (byte )3 ));
put( Character.valueOf( '4' ), Byte.valueOf( (byte )4 ));
put( Character.valueOf( '5' ), Byte.valueOf( (byte )5 ));
put( Character.valueOf( '6' ), Byte.valueOf( (byte )6 ));
put( Character.valueOf( '7' ), Byte.valueOf( (byte )7 ));
put( Character.valueOf( '8' ), Byte.valueOf( (byte )8 ));
put( Character.valueOf( '9' ), Byte.valueOf( (byte )9 ));
put( Character.valueOf( 'a' ), Byte.valueOf( (byte )10 ));
put( Character.valueOf( 'b' ), Byte.valueOf( (byte )11 ));
put( Character.valueOf( 'c' ), Byte.valueOf( (byte )12 ));
put( Character.valueOf( 'd' ), Byte.valueOf( (byte )13 ));
put( Character.valueOf( 'e' ), Byte.valueOf( (byte )14 ));
put( Character.valueOf( 'f' ), Byte.valueOf( (byte )15 ));
put( Character.valueOf( 'A' ), Byte.valueOf( (byte )10 ));
put( Character.valueOf( 'B' ), Byte.valueOf( (byte )11 ));
put( Character.valueOf( 'C' ), Byte.valueOf( (byte )12 ));
put( Character.valueOf( 'D' ), Byte.valueOf( (byte )13 ));
put( Character.valueOf( 'E' ), Byte.valueOf( (byte )14 ));
put( Character.valueOf( 'F' ), Byte.valueOf( (byte )15 ));
}};
static int[] charValues = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10, 11, 12, 13,14,15};
static char[] cs = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','A','B','C','D','E','F'};
public static void main(String args[]) throws Exception {
long time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getNumericValue( i );
}
System.out.println( "Character.getNumericValue:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getDigit( i );
}
System.out.println( "Character.digit:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
try {
res = getValueFromArray( i );
} catch (IllegalArgumentException e) {
}
}
System.out.println( "Array:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getValueFromHashMap( i );
}
System.out.println( "HashMap<Character,Byte>:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
char c = cs[i%cs.length];
res = getValueFromComputeMethod( c );
}
System.out.println( "JonSkeet's Direct Method:" );
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < NUMBER_OF_RUNS; i++ ) {
res = getValueFromSwitch( i );
}
System.out.println( "Switch:" );
System.out.println( System.currentTimeMillis()-time );
}
private static byte getValueFromSwitch( int i ) {
byte res;
char ch = cs[i%cs.length];
switch( ch ) {
case '0':
res = 0;
break;
case '1':
res = 1;
break;
case '2':
res = 2;
break;
case '3':
res = 3;
break;
case '4':
res = 4;
break;
case '5':
res = 5;
break;
case '6':
res = 6;
break;
case '7':
res = 7;
break;
case '8':
res = 8;
break;
case '9':
res = 9;
break;
case 'a':
case 'A':
res = 10;
break;
case 'b':
case 'B':
res = 11;
break;
case 'c':
case 'C':
res = 12;
break;
case 'd':
case 'D':
res = 13;
break;
case 'e':
case 'E':
res = 14;
break;
case 'f':
case 'F':
res = 15;
break;
default:
throw new RuntimeException("unknown hex character: " + ch );
}
return res;
}
private static byte getValueFromComputeMethod( char c ) {
byte result = 0;
if (c >= '0' && c <= '9')
{
result = (byte)(c - '0');
}
if (c >= 'a' && c <= 'f')
{
result = (byte)(c - 'a' + 10);
}
if (c >= 'A' && c <= 'F')
{
result = (byte)(c - 'A' + 10);
}
return result;
}
private static byte getValueFromHashMap( int i ) {
return map.get( Character.valueOf( cs[i%cs.length] ) ).byteValue();
}
private static byte getValueFromArray( int i ) {
char c = cs[i%cs.length];
if (c < '0' || c > 'f') {
throw new IllegalArgumentException();
}
byte result = (byte)charValues[c-'0'];
if (res < 0) {
throw new IllegalArgumentException();
}
return result;
}
private static byte getDigit( int i ) {
return (byte)Character.digit( cs[i%cs.length], 16 );
}
private static byte getNumericValue( int i ) {
return (byte)Character.getNumericValue( cs[i%cs.length] );
}
}
```
|
A preinitialised array would be faster than a HashMap. Something like this:
```
int CharValues['f'-'0'+1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, ... -1, 10, 11, 12, ...};
if (c < '0' || c > 'f') {
throw new IllegalArgumentException();
}
int n = CharValues[c-'0'];
if (n < 0) {
throw new IllegalArgumentException();
}
// n contains the digit value
```
You should benchmark this method against other methods (such as [Jon Skeet's](https://stackoverflow.com/questions/221001/performance-question-fastest-way-to-convert-hexadecimal-char-to-its-number-valu#221012) direct method) to determine which will be the fastest for your application.
|
221,002 |
<p>I'm implementing an audit log on a database, so everything has a CreatedAt and a RemovedAt column. Now I want to be able to list all revisions of an object graph but the best way I can think of for this is to use unions. I need to get every unique CreatedAt and RemovedAt id.</p>
<p>If I'm getting a list of countries with provinces the union looks like this:</p>
<pre><code>SELECT c.CreatedAt AS RevisionId from Countries as c where localId=@Country
UNION
SELECT p.CreatedAt AS RevisionId from Provinces as p
INNER JOIN Countries as c ON p.CountryId=c.LocalId AND c.LocalId = @Country
UNION
SELECT c.RemovedAt AS RevisionId from Countries as c where localId=@Country
UNION
SELECT p.RemovedAt AS RevisionId from Provinces as p
INNER JOIN Countries as c ON p.CountryId=c.LocalId AND c.LocalId = @Country
</code></pre>
<p>For more complicated queries this could get quite complicated and possibly perform very poorly so I wanted to see if anyone could think of a better approach. This is in MSSQL Server.</p>
<p>I need them all in a single list because this is being used in a from clause and the real data comes from joining on this.</p>
|
[
{
"answer_id": 221114,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 1,
"selected": false,
"text": "<p>An alternative would be to create an audit log that might look like this:</p>\n\n<pre><code>AuditLog table\n EntityName varchar(2000),\n Action varchar(255),\n EntityId int,\n OccuranceDate datetime\n</code></pre>\n\n<p>where EntityName is the name of the table (eg: Contries, Provinces), the Action is the audit action (eg: Created, Removed etc) and the EntityId is the primary key of the modified row in the original table.</p>\n\n<p>The table would need to be kept synchronized on each action performed to the tables. There are a couple of ways to do this:</p>\n\n<p>1) Make triggers on each table that will add rows to AuditTable<br>\n2) From your application add rows in AuditTable each time a change is made to the repectivetables</p>\n\n<p>Using this solution is very simple to get a list of logs in audit.</p>\n\n<p>If you need to get columns from original table is also possible using joins like this:</p>\n\n<pre><code>select *\nfrom \n Contries C \n join AuditLog L on C.Id = L.EntityId and EntityName = 'Contries'\n</code></pre>\n"
},
{
"answer_id": 222340,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably do it with a cross join and coalesce, but the union is probably still better from a performance standpoint. You can try testing each though.</p>\n\n<pre><code>SELECT\n COALESCE(C.CreatedAt, P.CreatedAt)\nFROM\n dbo.Countries C\nFULL OUTER JOIN dbo.Provinces P ON\n 1 = 0\nWHERE\n C.LocalID = @Country OR\n P.LocalID = @Country\n</code></pre>\n"
},
{
"answer_id": 279770,
"author": "Borzio",
"author_id": 36215,
"author_profile": "https://Stackoverflow.com/users/36215",
"pm_score": 2,
"selected": true,
"text": "<p>You have most likely already implemented your solution, but to address a few issues; I would suggest considering Aleris's solution, or some derivative thereof. <br/></p>\n\n<p><li> In your tables, you have a \"removed at\" field -- well, if that field were active (populated), technically the data shouldn't be there -- or perhaps your implementation has it flagged for deletion, which will break the logging once it <em>is</em> removed.<br/>\n<li> What happens when you have multiple updates during a reporting period -- the previous log entries would be overwritten.<br/>\n<li> Having a separate log allows for archival of the log information and allows you to set a different log analysis cycle from your update/edit cycles.<br/>\n<li>Add whatever \"linking\" fields required to enable you to get back to your original source data <em>OR</em> make the descriptions sufficiently verbose.</p>\n\n<p>The fields contained in your log are up to you but Aleris's solution is direct. I may create an action table and change the field type from varchar to int, as a link into the action table -- forcing the developers to some standardized actions. </p>\n\n<p>Hope it helps.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407256/"
] |
I'm implementing an audit log on a database, so everything has a CreatedAt and a RemovedAt column. Now I want to be able to list all revisions of an object graph but the best way I can think of for this is to use unions. I need to get every unique CreatedAt and RemovedAt id.
If I'm getting a list of countries with provinces the union looks like this:
```
SELECT c.CreatedAt AS RevisionId from Countries as c where localId=@Country
UNION
SELECT p.CreatedAt AS RevisionId from Provinces as p
INNER JOIN Countries as c ON p.CountryId=c.LocalId AND c.LocalId = @Country
UNION
SELECT c.RemovedAt AS RevisionId from Countries as c where localId=@Country
UNION
SELECT p.RemovedAt AS RevisionId from Provinces as p
INNER JOIN Countries as c ON p.CountryId=c.LocalId AND c.LocalId = @Country
```
For more complicated queries this could get quite complicated and possibly perform very poorly so I wanted to see if anyone could think of a better approach. This is in MSSQL Server.
I need them all in a single list because this is being used in a from clause and the real data comes from joining on this.
|
You have most likely already implemented your solution, but to address a few issues; I would suggest considering Aleris's solution, or some derivative thereof.
- In your tables, you have a "removed at" field -- well, if that field were active (populated), technically the data shouldn't be there -- or perhaps your implementation has it flagged for deletion, which will break the logging once it *is* removed.
- What happens when you have multiple updates during a reporting period -- the previous log entries would be overwritten.
- Having a separate log allows for archival of the log information and allows you to set a different log analysis cycle from your update/edit cycles.
- Add whatever "linking" fields required to enable you to get back to your original source data *OR* make the descriptions sufficiently verbose.
The fields contained in your log are up to you but Aleris's solution is direct. I may create an action table and change the field type from varchar to int, as a link into the action table -- forcing the developers to some standardized actions.
Hope it helps.
|
221,006 |
<p>So from what little I understand about packaging for Macs, I see that the actual program that launches is the one defined under the CFBundleExecutable key in Info.plist.</p>
<pre><code><key>CFBundleExecutable</key>
<string>JavaApplicationStub</string>
</code></pre>
<p>Now, my app doesnt work if /APP/Content/MacOS/JavaApplicationStub is not chmodded +x (It just fails silently without doing anything, which is a pain!).
Fair enough, its not executable I guess. But its a big problem if you are copying the app from somewhere that dosent support +x properties on files; such as windows, fat32 USB keys, CDROMs, websites, zip files, etc...</p>
<p>What can I do in these instances to make the app able to run? Manually setting the execute bit is not an option.</p>
<p>There's got to be people who run Mac apps off CD, at the very least!</p>
|
[
{
"answer_id": 221114,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 1,
"selected": false,
"text": "<p>An alternative would be to create an audit log that might look like this:</p>\n\n<pre><code>AuditLog table\n EntityName varchar(2000),\n Action varchar(255),\n EntityId int,\n OccuranceDate datetime\n</code></pre>\n\n<p>where EntityName is the name of the table (eg: Contries, Provinces), the Action is the audit action (eg: Created, Removed etc) and the EntityId is the primary key of the modified row in the original table.</p>\n\n<p>The table would need to be kept synchronized on each action performed to the tables. There are a couple of ways to do this:</p>\n\n<p>1) Make triggers on each table that will add rows to AuditTable<br>\n2) From your application add rows in AuditTable each time a change is made to the repectivetables</p>\n\n<p>Using this solution is very simple to get a list of logs in audit.</p>\n\n<p>If you need to get columns from original table is also possible using joins like this:</p>\n\n<pre><code>select *\nfrom \n Contries C \n join AuditLog L on C.Id = L.EntityId and EntityName = 'Contries'\n</code></pre>\n"
},
{
"answer_id": 222340,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably do it with a cross join and coalesce, but the union is probably still better from a performance standpoint. You can try testing each though.</p>\n\n<pre><code>SELECT\n COALESCE(C.CreatedAt, P.CreatedAt)\nFROM\n dbo.Countries C\nFULL OUTER JOIN dbo.Provinces P ON\n 1 = 0\nWHERE\n C.LocalID = @Country OR\n P.LocalID = @Country\n</code></pre>\n"
},
{
"answer_id": 279770,
"author": "Borzio",
"author_id": 36215,
"author_profile": "https://Stackoverflow.com/users/36215",
"pm_score": 2,
"selected": true,
"text": "<p>You have most likely already implemented your solution, but to address a few issues; I would suggest considering Aleris's solution, or some derivative thereof. <br/></p>\n\n<p><li> In your tables, you have a \"removed at\" field -- well, if that field were active (populated), technically the data shouldn't be there -- or perhaps your implementation has it flagged for deletion, which will break the logging once it <em>is</em> removed.<br/>\n<li> What happens when you have multiple updates during a reporting period -- the previous log entries would be overwritten.<br/>\n<li> Having a separate log allows for archival of the log information and allows you to set a different log analysis cycle from your update/edit cycles.<br/>\n<li>Add whatever \"linking\" fields required to enable you to get back to your original source data <em>OR</em> make the descriptions sufficiently verbose.</p>\n\n<p>The fields contained in your log are up to you but Aleris's solution is direct. I may create an action table and change the field type from varchar to int, as a link into the action table -- forcing the developers to some standardized actions. </p>\n\n<p>Hope it helps.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925/"
] |
So from what little I understand about packaging for Macs, I see that the actual program that launches is the one defined under the CFBundleExecutable key in Info.plist.
```
<key>CFBundleExecutable</key>
<string>JavaApplicationStub</string>
```
Now, my app doesnt work if /APP/Content/MacOS/JavaApplicationStub is not chmodded +x (It just fails silently without doing anything, which is a pain!).
Fair enough, its not executable I guess. But its a big problem if you are copying the app from somewhere that dosent support +x properties on files; such as windows, fat32 USB keys, CDROMs, websites, zip files, etc...
What can I do in these instances to make the app able to run? Manually setting the execute bit is not an option.
There's got to be people who run Mac apps off CD, at the very least!
|
You have most likely already implemented your solution, but to address a few issues; I would suggest considering Aleris's solution, or some derivative thereof.
- In your tables, you have a "removed at" field -- well, if that field were active (populated), technically the data shouldn't be there -- or perhaps your implementation has it flagged for deletion, which will break the logging once it *is* removed.
- What happens when you have multiple updates during a reporting period -- the previous log entries would be overwritten.
- Having a separate log allows for archival of the log information and allows you to set a different log analysis cycle from your update/edit cycles.
- Add whatever "linking" fields required to enable you to get back to your original source data *OR* make the descriptions sufficiently verbose.
The fields contained in your log are up to you but Aleris's solution is direct. I may create an action table and change the field type from varchar to int, as a link into the action table -- forcing the developers to some standardized actions.
Hope it helps.
|
221,025 |
<p>In this sentence:</p>
<pre><code>myCommand.ExecuteReader(CommandBehavior.CloseConnection)
</code></pre>
<p>does it close connection in case of exception?</p>
|
[
{
"answer_id": 221033,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "<p>There are plenty of ways that the command can go wrong.</p>\n\n<p>Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.</p>\n\n<p>If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.</p>\n\n<p>In case of an exception, I wouldn't trust it to close the connection.</p>\n"
},
{
"answer_id": 221034,
"author": "Danny Frencham",
"author_id": 29830,
"author_profile": "https://Stackoverflow.com/users/29830",
"pm_score": -1,
"selected": false,
"text": "<p>It depends where the exception occurs!</p>\n\n<p>If you structure your try catch correctly, it will be fine.</p>\n\n<p>For example:</p>\n\n<pre><code>SqlCommand myCommand = new SqlCommand();\n\ntry\n{\n myCommand.dostuff();\n}\ncatch(Exception ex)\n{\n // display error message\n}\nfinally\n{\n myCommand.ExecuteReader(CommandBehavior.CloseConnection);\n}\n</code></pre>\n\n<p>If the line: myCommand.ExecuteReader(CommandBehavior.CloseConnection) fails (perhaps the database has gone down?) then the connection cannot be closed programmatically.</p>\n"
},
{
"answer_id": 221045,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 3,
"selected": false,
"text": "<p>The safest way to do a \"normal\" query is</p>\n\n<pre><code>using (var conn = new SqlConnection(\"...\"))\n{\n conn.Open();\n using (var cmd = conn.CreateCommand())\n {\n cmd.CommandText = \"...\";\n using (var reader = cmd.ExecuteReader())\n {\n while (reader.Read())\n {\n // ...\n }\n }\n }\n}\n</code></pre>\n\n<p>Exceptions can be caught outside this code.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29600/"
] |
In this sentence:
```
myCommand.ExecuteReader(CommandBehavior.CloseConnection)
```
does it close connection in case of exception?
|
There are plenty of ways that the command can go wrong.
Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.
If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.
In case of an exception, I wouldn't trust it to close the connection.
|
221,031 |
<p>I have a Java service which now will execute in a batch mode. Multi threaded support is added to the service so for every batch request a thread pool will be dedicated to execute the batch. The question is how do I test this? I have functional tests that pass under the threaded version of the service but, somehow, I feel there must be an idiom for testing this. </p>
|
[
{
"answer_id": 221057,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "<p>There really isn't a \"good\" way to do this. The best thing I can suggest would be TestNG, which allows you to annotate your test methods and cause them to be executed in <em>n</em> threads concurrently. For example:</p>\n\n<pre><code>@Test(invocationCount=10, threadPool=10)\npublic void testSomethingConcurrently() {\n ...\n}\n</code></pre>\n\n<p>My TestNG knowledge is rusty at best, but AFAIK that should invoke the <code>testSomethingConcurrently</code> method 10 times concurrently. This is a nice and declarative way to run multi-threaded tests against your code.</p>\n\n<p>You can of course do something similar in JUnit by spawning threads manually in a loop, but that's insanely ugly and difficult to work with. I had to do this once for a project I was working on; those tests were a nightmare to deal with since their failures weren't always repeatable.</p>\n\n<p>Concurrency testing is difficult and prone to frustration, due to its non-deterministic nature. This is part of why there is such a big push these days to use better concurrency abstractions, ones which are easier to \"reason about\" and convince one's self of correctness.</p>\n"
},
{
"answer_id": 221191,
"author": "jassuncao",
"author_id": 1009,
"author_profile": "https://Stackoverflow.com/users/1009",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Daniel, concurrency testing is indeed very difficult.</p>\n\n<p>I don't have a solution for concurrency testing, but I will tell you what I do when I want to test code involving multi-threading.\nMost of my testing is done using JUnit and JMock. Since JMock doesn't work well with multiple threads, I use a extension to JMock that provides synchronous versions of Executor and ScheduledExecutorService. These allow me to test code targeted to be run by multiple threads in a single thread, where I'm also able to control the execution flow. As I said before, this doesn't test concurrency. It only checks the behavior of my code in a single threaded way, but it reduces the amount of errors I get when I switch to the multi thread executors.</p>\n\n<p>Anyway I recommend the use of the new Java concurrency API. It makes things a lot more easy.</p>\n"
},
{
"answer_id": 221388,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 1,
"selected": false,
"text": "<p>Usually the things that bring down multithreaded applications are issues of timing. I suspect that to be able to perform unit testing on the full multithreaded environment would require huge changes to the code base to do that.</p>\n\n<p>What you may well be able to do, though, is to test the implementation of the thread pool in isolation.</p>\n\n<p>By substituting the body of the threads with test code you should be able to construct your pathological conditions of locking and resource usage.</p>\n\n<p>Then, unit test the functional elements in a single threaded environment, where you can ignore timing.</p>\n\n<p>While this isn't perfect it does guarantee repeatability which is of great importance for your unit testing. (as alluded to in Daniel Spiewak's answer)</p>\n"
},
{
"answer_id": 15952591,
"author": "Vinod",
"author_id": 2270969,
"author_profile": "https://Stackoverflow.com/users/2270969",
"pm_score": 1,
"selected": false,
"text": "<p>I used</p>\n\n<pre><code> @Test(threadPoolSize = 100, invocationCount = 100)\n @DataProvider(parallel = true)\n</code></pre>\n\n<p>executed 100 threads in parallel 100 times.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28501/"
] |
I have a Java service which now will execute in a batch mode. Multi threaded support is added to the service so for every batch request a thread pool will be dedicated to execute the batch. The question is how do I test this? I have functional tests that pass under the threaded version of the service but, somehow, I feel there must be an idiom for testing this.
|
There really isn't a "good" way to do this. The best thing I can suggest would be TestNG, which allows you to annotate your test methods and cause them to be executed in *n* threads concurrently. For example:
```
@Test(invocationCount=10, threadPool=10)
public void testSomethingConcurrently() {
...
}
```
My TestNG knowledge is rusty at best, but AFAIK that should invoke the `testSomethingConcurrently` method 10 times concurrently. This is a nice and declarative way to run multi-threaded tests against your code.
You can of course do something similar in JUnit by spawning threads manually in a loop, but that's insanely ugly and difficult to work with. I had to do this once for a project I was working on; those tests were a nightmare to deal with since their failures weren't always repeatable.
Concurrency testing is difficult and prone to frustration, due to its non-deterministic nature. This is part of why there is such a big push these days to use better concurrency abstractions, ones which are easier to "reason about" and convince one's self of correctness.
|
221,043 |
<p>I have div containing a list of flash objects. The list is long so I've set the div height to 400 and overflow to auto. </p>
<p>This works fine on FF but on IE6 only the first 5 flash objects that are visible work. The rest of the flash objects that are initially outside the viewable area are empty when I scroll down. The swfs are loaded ok because I don't get the "movie not loaded". They also seem to be embedded correctly they are just empty ie. the content is never drawn.</p>
<p>Any ideas on how to fix this?</p>
<p>ps. The html elements involved are mainly floating in case that has an impact on this. The flash objects are embedded using the popular swfObject.</p>
<p>EDIT: It seems that the bug only occurs with the flash plugin "WIN 8,0,24,0" </p>
<p>Since I cant post a link I'll summarize the relevant code here:</p>
<pre><code><div style="overflow:auto; height:400px; float:left;">
<div id="item_1" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
...
<div id="item_7" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
</div>
</code></pre>
<p>EDIT:
After trying to recreate this problem in a separate page I found that the bug is some how related to the flash objects being hidden initially. My container div has "display:none; visibility:hidden" when page is loaded. Later on the style is changed via javascript to visible. If I load the page so that everything is visible from the start all is fine.</p>
|
[
{
"answer_id": 221153,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 2,
"selected": false,
"text": "<p>You should probably create a VIEW which limits the records and then apply the proper rights on the view. </p>\n"
},
{
"answer_id": 221168,
"author": "Danny Frencham",
"author_id": 29830,
"author_profile": "https://Stackoverflow.com/users/29830",
"pm_score": 2,
"selected": false,
"text": "<p>You could create a VIEW, or you could create select stored procedures and only assign rights to those.</p>\n\n<p>The VIEW is the way to go for a simple security model - if it is complex, go with the stored procedure(s).</p>\n"
},
{
"answer_id": 226606,
"author": "pkario",
"author_id": 28207,
"author_profile": "https://Stackoverflow.com/users/28207",
"pm_score": 0,
"selected": false,
"text": "<p><p>I have my first draft. It goes like that:\n<p>The app is a Project Management/Issue Tracking/Event Management/Collaboration Web app.\n<p>I created a Role \"External User\". By default a user in that role </p>\n\n<ul>\n<li>can SELECT FROM Persons \n<li>can SELECT FROM Units (organizational units-companies-depts etc)\n<li>can SELECT Projects assigned to him\n<li>can SELECT Tasks assigned to him\n<li>can not SELECT any other Projects & Tasks\n</ul>\n\n<p><p>The administrator can create a user group \"External Partner\" and assign to that some Projects and Products (with Issues)\n<p>The members of this group can SELECT the assigned Objects.</p>\n\n<p><p>It is a complicated solution, but the only one that solves my customers problem (they don't want external partners to have access to all their project database).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22673/"
] |
I have div containing a list of flash objects. The list is long so I've set the div height to 400 and overflow to auto.
This works fine on FF but on IE6 only the first 5 flash objects that are visible work. The rest of the flash objects that are initially outside the viewable area are empty when I scroll down. The swfs are loaded ok because I don't get the "movie not loaded". They also seem to be embedded correctly they are just empty ie. the content is never drawn.
Any ideas on how to fix this?
ps. The html elements involved are mainly floating in case that has an impact on this. The flash objects are embedded using the popular swfObject.
EDIT: It seems that the bug only occurs with the flash plugin "WIN 8,0,24,0"
Since I cant post a link I'll summarize the relevant code here:
```
<div style="overflow:auto; height:400px; float:left;">
<div id="item_1" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
...
<div id="item_7" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
</div>
```
EDIT:
After trying to recreate this problem in a separate page I found that the bug is some how related to the flash objects being hidden initially. My container div has "display:none; visibility:hidden" when page is loaded. Later on the style is changed via javascript to visible. If I load the page so that everything is visible from the start all is fine.
|
You should probably create a VIEW which limits the records and then apply the proper rights on the view.
|
221,052 |
<p>Could anyone provide any example of NAnt script for C++ project build automation?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 221107,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 0,
"selected": false,
"text": "<p>If the project is in Visual Studio then you can use the <code><Solution></code> task, I think. That's the simplest/ugliest way of doing it.</p>\n\n<p><strong>edit:</strong> Just realised that SO filtered out my little XML tag there. </p>\n"
},
{
"answer_id": 222560,
"author": "Mike Marshall",
"author_id": 29798,
"author_profile": "https://Stackoverflow.com/users/29798",
"pm_score": 3,
"selected": true,
"text": "<p>If you're talking Microsoft Visual C++ then I think you get the most control by shelling out msbuild.exe from the nant script and passing it your solution file on the command line. This is supported in Visual Studio 2005/.Net Framework 2.0 and above. e.g.:</p>\n\n<pre><code><property name=\"msbuild.dir\" value=\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\" />\n\n...\n\n<exec program=\"${msbuild.dir}\\MSBuild.exe\"\n commandline=\"/p:Configuration=Release .\\MySolution.sln\" \n/>\n</code></pre>\n\n<p>It will build everything in your solution regardless of language (c#, VB, C++, etc)</p>\n\n<p>Mike</p>\n"
},
{
"answer_id": 261452,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 0,
"selected": false,
"text": "<p>I was recently looking for this kind of information, and found this blog entry about it:\n<a href=\"http://seclib.blogspot.com/2005/05/building-native-c-projects-with-nant.html\" rel=\"nofollow noreferrer\">http://seclib.blogspot.com/2005/05/building-native-c-projects-with-nant.html</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
Could anyone provide any example of NAnt script for C++ project build automation?
Thanks!
|
If you're talking Microsoft Visual C++ then I think you get the most control by shelling out msbuild.exe from the nant script and passing it your solution file on the command line. This is supported in Visual Studio 2005/.Net Framework 2.0 and above. e.g.:
```
<property name="msbuild.dir" value="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" />
...
<exec program="${msbuild.dir}\MSBuild.exe"
commandline="/p:Configuration=Release .\MySolution.sln"
/>
```
It will build everything in your solution regardless of language (c#, VB, C++, etc)
Mike
|
221,063 |
<p>How can i find out this information?</p>
<hr>
<p>Ie, </p>
<p>I can install boost 1.35 with a command like</p>
<pre><code>sudo port install boost
</code></pre>
<p>only to get boost 1.36 via port i would do something like this? </p>
<pre><code>sudo port install boost-1.36
</code></pre>
<p>Hope that clears up my question</p>
|
[
{
"answer_id": 221107,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 0,
"selected": false,
"text": "<p>If the project is in Visual Studio then you can use the <code><Solution></code> task, I think. That's the simplest/ugliest way of doing it.</p>\n\n<p><strong>edit:</strong> Just realised that SO filtered out my little XML tag there. </p>\n"
},
{
"answer_id": 222560,
"author": "Mike Marshall",
"author_id": 29798,
"author_profile": "https://Stackoverflow.com/users/29798",
"pm_score": 3,
"selected": true,
"text": "<p>If you're talking Microsoft Visual C++ then I think you get the most control by shelling out msbuild.exe from the nant script and passing it your solution file on the command line. This is supported in Visual Studio 2005/.Net Framework 2.0 and above. e.g.:</p>\n\n<pre><code><property name=\"msbuild.dir\" value=\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\" />\n\n...\n\n<exec program=\"${msbuild.dir}\\MSBuild.exe\"\n commandline=\"/p:Configuration=Release .\\MySolution.sln\" \n/>\n</code></pre>\n\n<p>It will build everything in your solution regardless of language (c#, VB, C++, etc)</p>\n\n<p>Mike</p>\n"
},
{
"answer_id": 261452,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 0,
"selected": false,
"text": "<p>I was recently looking for this kind of information, and found this blog entry about it:\n<a href=\"http://seclib.blogspot.com/2005/05/building-native-c-projects-with-nant.html\" rel=\"nofollow noreferrer\">http://seclib.blogspot.com/2005/05/building-native-c-projects-with-nant.html</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
How can i find out this information?
---
Ie,
I can install boost 1.35 with a command like
```
sudo port install boost
```
only to get boost 1.36 via port i would do something like this?
```
sudo port install boost-1.36
```
Hope that clears up my question
|
If you're talking Microsoft Visual C++ then I think you get the most control by shelling out msbuild.exe from the nant script and passing it your solution file on the command line. This is supported in Visual Studio 2005/.Net Framework 2.0 and above. e.g.:
```
<property name="msbuild.dir" value="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" />
...
<exec program="${msbuild.dir}\MSBuild.exe"
commandline="/p:Configuration=Release .\MySolution.sln"
/>
```
It will build everything in your solution regardless of language (c#, VB, C++, etc)
Mike
|
221,079 |
<p>I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it.</p>
<p>I have a pojo LookupTable which contains a list of Columns:</p>
<pre><code>public class LookupTable {
private long id;
// More properties go here...
private List<Column> columns;
public void addColumn(Column column) {
this.columns.add(column);
}
// More methods go here...
}
</code></pre>
<p>In my hibernate configuration I have:</p>
<pre><code><class name="LookupTable" table="ARR_LOOKUP_TABLE">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
<bag name="columns" cascade="all,delete-orphan" access="field">
<key column="LOOKUP_TABLE" not-null="true"/>
<one-to-many class="Column"/>
</bag>
</class>
<class name="Column" table="ARR_LOOKUP_COLUMN">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
</class>
</code></pre>
<p>In my Spring config file I have:</p>
<pre><code><tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="managers" expression="execution(public * com.foo.*Manager.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="managers"/>
</aop:config>
</code></pre>
<p>And finally the code where it all fails within my manager class (com.foo.LookupTableManager):</p>
<pre><code>public void addColumnToTable(Column column, long tableId) {
LookupTable lookupTable = this.lookupTableDao.findById(tableId);
lookupTable.addColumn(column);
this.lookupTableDao.saveOrUpdate(lookupTable);
}
</code></pre>
<p>The variable lookupTableDao here refers to a simple DAO class which extends HibernateDaoSupport.</p>
<p>The error I get is:</p>
<pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.foo.AbstractDao.saveOrUpdate(AbstractDao.java:29)
at com.foo.LookupTableManager.addColumnToTable(LookupTableManager.java:338)
... etc ...
</code></pre>
<p>OK, I understand the basic message I'm getting. But what I don't understand is where I get the second session.... Can anyone help me with this?</p>
<p>I'm using Hibernate 3.2.6.ga, Spring 2.5.5 and Tomcat 6.0</p>
|
[
{
"answer_id": 221110,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": "<p>My guess is that the <code>lookupTableDao.findById</code> call is getting your object in one session, but the <code>lookupTableDao.saveOrUpdate</code> is a different one - how do you get the <code>Session</code> object, via Spring?</p>\n\n<p>Where is the <code>Column</code> object coming from - is that already on the DB or new?</p>\n"
},
{
"answer_id": 221176,
"author": "Jaap Coomans",
"author_id": 26066,
"author_profile": "https://Stackoverflow.com/users/26066",
"pm_score": 4,
"selected": true,
"text": "<p>Turns out I didn't have a transaction at all. I used almost the same transaction configuration in one of my other config files. </p>\n\n<p>The pointcut over there was also called \"managers\", so my advisor here was referencing the pointcut in the other file.</p>\n\n<p><em>Renaming the pointcut solved my problem.</em></p>\n"
},
{
"answer_id": 3267209,
"author": "Umar",
"author_id": 394125,
"author_profile": "https://Stackoverflow.com/users/394125",
"pm_score": 2,
"selected": false,
"text": "<p>The problem was with the Open Session In view filter mapping.\nIt was creating a session on getSession\nAnd other on save.</p>\n\n<p>You can change only singleSession as false\ndefault its true</p>\n"
},
{
"answer_id": 7704473,
"author": "Mark Bakker",
"author_id": 626698,
"author_profile": "https://Stackoverflow.com/users/626698",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently using merge will probably fix the problem</p>\n\n<pre><code>myInstance = (myInstanceClass) Session.merge(myInstance);\n</code></pre>\n"
},
{
"answer_id": 8086160,
"author": "Claes Mogren",
"author_id": 4992,
"author_profile": "https://Stackoverflow.com/users/4992",
"pm_score": 0,
"selected": false,
"text": "<p>If you only want a transaction over a part of your code you can use something like this:</p>\n\n<pre><code>import org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\n</code></pre>\n\n<p>and in the class:</p>\n\n<pre><code>@Autowired private SessionFactory sessionFactory;\n</code></pre>\n\n<p>Later, around the code that should do things in the same transaction:</p>\n\n<pre><code>Session session = sessionFactory.openSession();\nTransaction tx = session.beginTransaction();\n\nStuff stuff = getStuff();\nmanipulate(stuff);\nsend(stuff);\nsave(stuff);\n\ntx.commit();\n</code></pre>\n\n<p>I use this inside a loop in some long-running batch jobs.</p>\n"
},
{
"answer_id": 10071182,
"author": "Raul Rene",
"author_id": 1300817,
"author_profile": "https://Stackoverflow.com/users/1300817",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem with my following code:\nI wanted to update a certain entity Store. I was retrieving it from this method:</p>\n\n<pre><code>@Override\npublic Store getStoreByStoreId(final long storeId) {\n getHibernateTemplate().execute(new HibernateCallback<Store>() {\n @Override\n public StoredoInHibernate(Session session) throws HibernateException, SQLException {\n return (Store) session.createCriteria(Store.class)\n .add(Restrictions.eq(Store.PROP_ID, storeId))\n .uniqueResult();\n }\n });\n}\n</code></pre>\n\n<p>Then, I was updating the store in the following method:</p>\n\n<pre><code>@Override\npublic void updateStoreByStoreId(final long storeId) {\n getHibernateTemplate().execute(new HibernateCallback<Void>() {\n @Override\n public Void doInHibernate(Session session) throws HibernateException, SQLException {\n Store toBeUpdated = getStoreByStoreId(storeId);\n\n if (toBeUpdated != null){\n // ..change values for certain fields\n session.update(toBeUpdated);\n }\n return null;\n }\n });\n} \n</code></pre>\n\n<p>It turns out I got the \"Illegal attempt ...\" error because the first session from the get method was not closing, and I was trying to update with the other session the store. The solution for me was to move the call for retrieving the store to be updated in the update method.</p>\n\n<pre><code>@Override\npublic void updateStoreByStoreId(final long storeId) {\n getHibernateTemplate().execute(new HibernateCallback<Void>() {\n @Override\n public Void doInHibernate(Session session) throws HibernateException, SQLException {\n Store toBeUpdated = (Store) session.createCriteria(Store.class)\n .add(Restrictions.eq(Store.PROP_ID, storeId))\n .uniqueResult();\n\n if (toBeUpdated != null){\n // ..change values for certain fields\n session.update(toBeUpdated );\n }\n return null;\n }\n });\n} \n</code></pre>\n"
},
{
"answer_id": 46373926,
"author": "Piyush",
"author_id": 8658475,
"author_profile": "https://Stackoverflow.com/users/8658475",
"pm_score": 0,
"selected": false,
"text": "<p>I was using windows server IIS and just changing the AppPool Managed Pipeline mode from Integrated to Classic solved my issue.</p>\n\n<p>Thanks</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26066/"
] |
I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it.
I have a pojo LookupTable which contains a list of Columns:
```
public class LookupTable {
private long id;
// More properties go here...
private List<Column> columns;
public void addColumn(Column column) {
this.columns.add(column);
}
// More methods go here...
}
```
In my hibernate configuration I have:
```
<class name="LookupTable" table="ARR_LOOKUP_TABLE">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
<bag name="columns" cascade="all,delete-orphan" access="field">
<key column="LOOKUP_TABLE" not-null="true"/>
<one-to-many class="Column"/>
</bag>
</class>
<class name="Column" table="ARR_LOOKUP_COLUMN">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
</class>
```
In my Spring config file I have:
```
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="managers" expression="execution(public * com.foo.*Manager.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="managers"/>
</aop:config>
```
And finally the code where it all fails within my manager class (com.foo.LookupTableManager):
```
public void addColumnToTable(Column column, long tableId) {
LookupTable lookupTable = this.lookupTableDao.findById(tableId);
lookupTable.addColumn(column);
this.lookupTableDao.saveOrUpdate(lookupTable);
}
```
The variable lookupTableDao here refers to a simple DAO class which extends HibernateDaoSupport.
The error I get is:
```
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.foo.AbstractDao.saveOrUpdate(AbstractDao.java:29)
at com.foo.LookupTableManager.addColumnToTable(LookupTableManager.java:338)
... etc ...
```
OK, I understand the basic message I'm getting. But what I don't understand is where I get the second session.... Can anyone help me with this?
I'm using Hibernate 3.2.6.ga, Spring 2.5.5 and Tomcat 6.0
|
Turns out I didn't have a transaction at all. I used almost the same transaction configuration in one of my other config files.
The pointcut over there was also called "managers", so my advisor here was referencing the pointcut in the other file.
*Renaming the pointcut solved my problem.*
|
221,126 |
<p>Has anyone managed to get PDFCreator running on an ASP.NET 2.0 website ?</p>
<p>On my development machine with Visual Studio webserver, it works just fine after following this procedure :</p>
<ul>
<li>create a com interop dll with tlbimp</li>
<li>reference this dll</li>
<li>write some code to use it</li>
</ul>
<p>However, when I deploy it to our test server, it fails miserably with this error :</p>
<pre><code>Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005.
</code></pre>
<p>And I can't find this component in DCOMCNFG.msc.</p>
<p>Our server configuration : </p>
<ul>
<li>Windows 2003</li>
<li>Asp.net 2.0</li>
<li>MS Office XP</li>
<li>PDFCreator 0.9.0</li>
</ul>
|
[
{
"answer_id": 281122,
"author": "Craig Lebakken",
"author_id": 33130,
"author_profile": "https://Stackoverflow.com/users/33130",
"pm_score": 2,
"selected": false,
"text": "<p>The following Microsoft Knowledgebase article describes the problem and a solution:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/q184291/\" rel=\"nofollow noreferrer\">COM objects fail to print when called from ASP</a></p>\n"
},
{
"answer_id": 326468,
"author": "mapache",
"author_id": 41422,
"author_profile": "https://Stackoverflow.com/users/41422",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is that IIS process (and so ASP.Net processes) run as the SYSTEM account, wich does not have any printers set up.</p>\n\n<p>You have two options:</p>\n\n<p>1 - Set up the printers for the system account using the <a href=\"http://support.microsoft.com/kb/184291/en-us\" rel=\"nofollow noreferrer\">article</a> provided by Craig Lebakken</p>\n\n<p>2 - Impersonate the ASP.Net site to use an account wich has the printers set up</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971/"
] |
Has anyone managed to get PDFCreator running on an ASP.NET 2.0 website ?
On my development machine with Visual Studio webserver, it works just fine after following this procedure :
* create a com interop dll with tlbimp
* reference this dll
* write some code to use it
However, when I deploy it to our test server, it fails miserably with this error :
```
Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {082391C9-8188-4364-B4FD-66A1524B2097} failed due to the following error: 80070005.
```
And I can't find this component in DCOMCNFG.msc.
Our server configuration :
* Windows 2003
* Asp.net 2.0
* MS Office XP
* PDFCreator 0.9.0
|
The following Microsoft Knowledgebase article describes the problem and a solution:
[COM objects fail to print when called from ASP](http://support.microsoft.com/kb/q184291/)
|
221,154 |
<p>The number is bigger than <code>int</code> & <code>long</code> but can be accomodated in <code>Decimal</code>. But the normal <code>ToString</code> or <code>Convert</code> methods don't work on <code>Decimal</code>.</p>
|
[
{
"answer_id": 221158,
"author": "James",
"author_id": 5625,
"author_profile": "https://Stackoverflow.com/users/5625",
"pm_score": 2,
"selected": false,
"text": "<p>Do it manually!</p>\n\n<p><a href=\"http://www.permadi.com/tutorial/numDecToHex/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/numDecToHex/</a></p>\n"
},
{
"answer_id": 221166,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>I've got to agree with James - do it manually - but don't use base-16. Use base 2^32, and print 8 hex digits at a time.</p>\n"
},
{
"answer_id": 221174,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>I guess one option would be to keep taking chunks off it, and converting individual chunks? A bit of mod/division etc, converting individual fragments...</p>\n\n<p>So: what hex value do you expect?</p>\n\n<p>Here's two approaches... one uses the binary structure of decimal; one does it manually. In reality, you might want to have a test: <em>if</em> bits[3] is zero, do it the quick way, <em>otherwise</em> do it manually.</p>\n\n<pre><code> decimal d = 588063595292424954445828M;\n int[] bits = decimal.GetBits(d);\n if (bits[3] != 0) throw new InvalidOperationException(\"Only +ve integers supported!\");\n string s = Convert.ToString(bits[2], 16).PadLeft(8,'0') // high\n + Convert.ToString(bits[1], 16).PadLeft(8, '0') // middle\n + Convert.ToString(bits[0], 16).PadLeft(8, '0'); // low\n Console.WriteLine(s);\n\n /* or Jon's much tidier: string.Format(\"{0:x8}{1:x8}{2:x8}\",\n (uint)bits[2], (uint)bits[1], (uint)bits[0]); */\n\n const decimal chunk = (decimal)(1 << 16);\n StringBuilder sb = new StringBuilder();\n while (d > 0)\n {\n int fragment = (int) (d % chunk);\n sb.Insert(0, Convert.ToString(fragment, 16).PadLeft(4, '0'));\n d -= fragment;\n d /= chunk;\n }\n Console.WriteLine(sb);\n</code></pre>\n"
},
{
"answer_id": 221209,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)</p>\n\n<pre><code>static string ConvertToHex(decimal d)\n{\n int[] bits = decimal.GetBits(d);\n if (bits[3] != 0) // Sign and exponent\n {\n throw new ArgumentException();\n }\n return string.Format(\"{0:x8}{1:x8}{2:x8}\",\n (uint)bits[2], (uint)bits[1], (uint)bits[0]);\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The number is bigger than `int` & `long` but can be accomodated in `Decimal`. But the normal `ToString` or `Convert` methods don't work on `Decimal`.
|
I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)
```
static string ConvertToHex(decimal d)
{
int[] bits = decimal.GetBits(d);
if (bits[3] != 0) // Sign and exponent
{
throw new ArgumentException();
}
return string.Format("{0:x8}{1:x8}{2:x8}",
(uint)bits[2], (uint)bits[1], (uint)bits[0]);
}
```
|
221,160 |
<p><code>termios.h</code> defines:</p>
<pre><code>#define TIOCM_OUT1 0x2000
#define TIOCM_OUT2 0x4000
</code></pre>
<p>But what are the flags good for?</p>
|
[
{
"answer_id": 221158,
"author": "James",
"author_id": 5625,
"author_profile": "https://Stackoverflow.com/users/5625",
"pm_score": 2,
"selected": false,
"text": "<p>Do it manually!</p>\n\n<p><a href=\"http://www.permadi.com/tutorial/numDecToHex/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/numDecToHex/</a></p>\n"
},
{
"answer_id": 221166,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>I've got to agree with James - do it manually - but don't use base-16. Use base 2^32, and print 8 hex digits at a time.</p>\n"
},
{
"answer_id": 221174,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>I guess one option would be to keep taking chunks off it, and converting individual chunks? A bit of mod/division etc, converting individual fragments...</p>\n\n<p>So: what hex value do you expect?</p>\n\n<p>Here's two approaches... one uses the binary structure of decimal; one does it manually. In reality, you might want to have a test: <em>if</em> bits[3] is zero, do it the quick way, <em>otherwise</em> do it manually.</p>\n\n<pre><code> decimal d = 588063595292424954445828M;\n int[] bits = decimal.GetBits(d);\n if (bits[3] != 0) throw new InvalidOperationException(\"Only +ve integers supported!\");\n string s = Convert.ToString(bits[2], 16).PadLeft(8,'0') // high\n + Convert.ToString(bits[1], 16).PadLeft(8, '0') // middle\n + Convert.ToString(bits[0], 16).PadLeft(8, '0'); // low\n Console.WriteLine(s);\n\n /* or Jon's much tidier: string.Format(\"{0:x8}{1:x8}{2:x8}\",\n (uint)bits[2], (uint)bits[1], (uint)bits[0]); */\n\n const decimal chunk = (decimal)(1 << 16);\n StringBuilder sb = new StringBuilder();\n while (d > 0)\n {\n int fragment = (int) (d % chunk);\n sb.Insert(0, Convert.ToString(fragment, 16).PadLeft(4, '0'));\n d -= fragment;\n d /= chunk;\n }\n Console.WriteLine(sb);\n</code></pre>\n"
},
{
"answer_id": 221209,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)</p>\n\n<pre><code>static string ConvertToHex(decimal d)\n{\n int[] bits = decimal.GetBits(d);\n if (bits[3] != 0) // Sign and exponent\n {\n throw new ArgumentException();\n }\n return string.Format(\"{0:x8}{1:x8}{2:x8}\",\n (uint)bits[2], (uint)bits[1], (uint)bits[0]);\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
`termios.h` defines:
```
#define TIOCM_OUT1 0x2000
#define TIOCM_OUT2 0x4000
```
But what are the flags good for?
|
I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)
```
static string ConvertToHex(decimal d)
{
int[] bits = decimal.GetBits(d);
if (bits[3] != 0) // Sign and exponent
{
throw new ArgumentException();
}
return string.Format("{0:x8}{1:x8}{2:x8}",
(uint)bits[2], (uint)bits[1], (uint)bits[0]);
}
```
|
221,165 |
<p>I'm building a database that will store information on a range of objects (such as scientific papers, specimens, DNA sequences, etc.) that all have a presence online and can be identified by a URL, or an identifier such as a <a href="http://www.doi.org/" rel="noreferrer" title="DOI">DOI</a>. Using these GUIDs as the primary key for the object seems a reasonable idea, and I've followed <a href="http://delicious.com/" rel="noreferrer" title="delicious">delicious</a> and <a href="http://www.connotea.org" rel="noreferrer" title="Connotea">Connotea</a> in using the md5 hash of the GUID. You'll see the md5 hash in your browser status bar if you mouse over the edit or delete buttons in a delicious or Connotea book mark. For example, the bookmark for <a href="http://stackoverflow/" rel="noreferrer">http://stackoverflow/</a> is </p>
<pre><code>http://delicious.com/url/e4a42d992025b928a586b8bdc36ad38d
</code></pre>
<p>where e4a42d992025b928a586b8bdc36ad38d ais the md5 hash of <a href="http://stackoverflow/" rel="noreferrer">http://stackoverflow/</a>.</p>
<p>Does anybody have views on the pros and cons of this approach?</p>
<p>For me an advantage of this approach (as opposed to using an auto incrementing primary key generated by the database itself) is that I have to do a lot of links between objects, and by using md5 hashes I can store these links externally in a file (say, as the result of data mining/scraping), then import them in bulk into the database. In the same way, if the database has to be rebuilt from scratch, the URLs to the objects won't change because they use the md5 hash.</p>
<p>I'd welcome any thoughts on whether this sounds sensible, or whether there other (better?) ways of doing this.</p>
|
[
{
"answer_id": 221173,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe this document is something you want to read:</p>\n\n<p><a href=\"http://www.hpl.hp.com/techreports/2002/HPL-2002-216.pdf\" rel=\"nofollow noreferrer\">http://www.hpl.hp.com/techreports/2002/HPL-2002-216.pdf</a></p>\n"
},
{
"answer_id": 221196,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Often lots of different urls point to the same page.\n<a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a>\nexample.com\n<a href=\"http://www.example.com/\" rel=\"nofollow noreferrer\">http://www.example.com/</a>\n<a href=\"http://example.com/index.html\" rel=\"nofollow noreferrer\">http://example.com/index.html</a>\n<a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a>.\n<a href=\"https://example.com/\" rel=\"nofollow noreferrer\">https://example.com/</a>\n\netc.</p>\n\n<p>This might or might not be a problem for you.</p>\n"
},
{
"answer_id": 221229,
"author": "rdmpage",
"author_id": 9684,
"author_profile": "https://Stackoverflow.com/users/9684",
"pm_score": 3,
"selected": false,
"text": "<p>After browsing stackoverfow a little more I found an earlier question <a href=\"https://stackoverflow.com/questions/45399/advantages-and-disadvantages-of-guid-uuid-database-keys\">Advantages and disadvantages of GUID / UUID database keys</a> which covers much of this ground.</p>\n"
},
{
"answer_id": 221249,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple strings can produce the same md5 hash. Primary keys must be unique. So using the hash as the primary key is not good. Better is to use the GUID directly.</p>\n\n<p>Is a GUID suitable for use in a URL. Sure. Here's a GUID (actually, a UUID) I jsut created using Java: 1ccb9467-e326-4fed-b9a7-7edcba52be84</p>\n\n<p>The url could be:</p>\n\n<pre><code>http://example.com/view?id=1ccb9467-e326-4fed-b9a7-7edcba52be84\n</code></pre>\n\n<p>It's longish but perfectly usable and achieves what you describe.</p>\n"
},
{
"answer_id": 288615,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "<p>It's perfectly fine. </p>\n\n<p>Accidental collision of MD5 is impossible in all practical scenarios (to get a 50% chance of collision you'd have to hash 6 <em>billion</em> URLs <em>per second</em>, every second, for 100 years). </p>\n\n<p>It's such an improbable chance that you're trillion times more likely to get your data messed up due to an undetected hardware failure than due to an actual collision.</p>\n\n<p>Even though there is a known collision attack against MD5, intentional malicious collisions are currently impossible against hashed URLs.</p>\n\n<ul>\n<li><p>The type of collision you'd need to intentionally collide with a hash of another URL is called a <strong>pre-image</strong> attack. There are no known pre-image attacks against MD5. As of 2017 there's no research that comes even close to feasibility, so even a determined well-funded attacker can't compute a URL that would hash to a hash of any existing URL in your database.</p></li>\n<li><p>The only known collision attack against MD5 is not useful for attacking URL-like keys. It works by generating a pair of binary blobs that collide <em>only with each other</em>. The blobs will be relatively long, contain NUL and other unprintable bytes, so they're extremely unlikely to resemble anything like a URL.</p></li>\n</ul>\n"
},
{
"answer_id": 1221847,
"author": "MaHuJa",
"author_id": 147749,
"author_profile": "https://Stackoverflow.com/users/147749",
"pm_score": 0,
"selected": false,
"text": "<p>MD5 is considered deprecated - at least for cryptographic purposes, but I would suggest only using md5 for backwards compatibility with existing stuff. You should have a good reason to go with md5 when we do have other hash algos out there that aren't (at least yet) broken.</p>\n\n<p>Problems I see with the approach:</p>\n\n<ul>\n<li>Duplicate objects, because the url identifier is different \n(As arend mentioned)</li>\n<li>URLs changing</li>\n</ul>\n\n<p>The latter being the one that might be important - this could be done as simply as a remove and an add. That is, if these ids are never visible/storable outside the database. (Like as a component of a URL.)</p>\n\n<p>I guess these won't be a problem for DOIs.</p>\n\n<hr>\n\n<p>How would it work with a non-autonumber integer id setup, but where the offline inserter agent creates the numbers? (Can use a dedicated range of numbers, maybe?) \nMight have a problem with duplication should two users independently add the same url?</p>\n"
},
{
"answer_id": 35665875,
"author": "Prabhu",
"author_id": 2445025,
"author_profile": "https://Stackoverflow.com/users/2445025",
"pm_score": -1,
"selected": false,
"text": "<p>md5 hash is almost unique, but is not totally unique unique so don't use it as primary key. It is depreciated for cryptographic use. There is less chance of key collision, but if you have pretty big database with billions of rows, there is still some chance of collision. If you insist using hash as primary key use other better hash. You cannot use non unique values for Primary Key.\nIf you have pretty big table, don't use it. If you have small table, you might use it, but not recommended.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9684/"
] |
I'm building a database that will store information on a range of objects (such as scientific papers, specimens, DNA sequences, etc.) that all have a presence online and can be identified by a URL, or an identifier such as a [DOI](http://www.doi.org/ "DOI"). Using these GUIDs as the primary key for the object seems a reasonable idea, and I've followed [delicious](http://delicious.com/ "delicious") and [Connotea](http://www.connotea.org "Connotea") in using the md5 hash of the GUID. You'll see the md5 hash in your browser status bar if you mouse over the edit or delete buttons in a delicious or Connotea book mark. For example, the bookmark for <http://stackoverflow/> is
```
http://delicious.com/url/e4a42d992025b928a586b8bdc36ad38d
```
where e4a42d992025b928a586b8bdc36ad38d ais the md5 hash of <http://stackoverflow/>.
Does anybody have views on the pros and cons of this approach?
For me an advantage of this approach (as opposed to using an auto incrementing primary key generated by the database itself) is that I have to do a lot of links between objects, and by using md5 hashes I can store these links externally in a file (say, as the result of data mining/scraping), then import them in bulk into the database. In the same way, if the database has to be rebuilt from scratch, the URLs to the objects won't change because they use the md5 hash.
I'd welcome any thoughts on whether this sounds sensible, or whether there other (better?) ways of doing this.
|
It's perfectly fine.
Accidental collision of MD5 is impossible in all practical scenarios (to get a 50% chance of collision you'd have to hash 6 *billion* URLs *per second*, every second, for 100 years).
It's such an improbable chance that you're trillion times more likely to get your data messed up due to an undetected hardware failure than due to an actual collision.
Even though there is a known collision attack against MD5, intentional malicious collisions are currently impossible against hashed URLs.
* The type of collision you'd need to intentionally collide with a hash of another URL is called a **pre-image** attack. There are no known pre-image attacks against MD5. As of 2017 there's no research that comes even close to feasibility, so even a determined well-funded attacker can't compute a URL that would hash to a hash of any existing URL in your database.
* The only known collision attack against MD5 is not useful for attacking URL-like keys. It works by generating a pair of binary blobs that collide *only with each other*. The blobs will be relatively long, contain NUL and other unprintable bytes, so they're extremely unlikely to resemble anything like a URL.
|
221,170 |
<p>How do I declare a private function in Fortran?</p>
|
[
{
"answer_id": 221175,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>I've never written a line of FORTRAN, but <a href=\"http://coding.derkeiler.com/Archive/Fortran/comp.lang.fortran/2004-01/1100.html\" rel=\"nofollow noreferrer\">this thread about \"Private module procedures\"</a> seems to be topical, at least I hope so. Seems to contain answers, at least.</p>\n\n<hr>\n\n<p><em>jaredor</em> summary:</p>\n\n<blockquote>\n <p>The public/private attribute exists within modules in Fortran 90 and later. Fortran 77 and earlier--you're out of luck.</p>\n</blockquote>\n"
},
{
"answer_id": 222003,
"author": "SumoRunner",
"author_id": 18975,
"author_profile": "https://Stackoverflow.com/users/18975",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Private xxx, yyy, zzz\n\nreal function xxx (v)\n ...\nend function xxx\n\ninteger function yyy()\n ...\nend function yyy\n\nsubroutine zzz ( a,b,c )\n ...\nend subroutine zzz\n\n... \nother stuff that calls them\n...\n</code></pre>\n"
},
{
"answer_id": 222289,
"author": "Tim Whitcomb",
"author_id": 24895,
"author_profile": "https://Stackoverflow.com/users/24895",
"pm_score": 6,
"selected": true,
"text": "<p>This will only work with a Fortran 90 module. In your module declaration, you can specify the access limits for a list of variables and routines using the \"public\" and \"private\" keywords. I usually find it helpful to use the private keyword by itself initially, which specifies that everything within the module is private unless explicitly marked public.</p>\n\n<p>In the code sample below, subroutine_1() and function_1() are accessible from outside the module via the requisite \"use\" statement, but any other variable/subroutine/function will be private.</p>\n\n<pre><code>module so_example\n implicit none\n\n private\n\n public :: subroutine_1\n public :: function_1\n\ncontains\n\n ! Implementation of subroutines and functions goes here \n\nend module so_example\n</code></pre>\n"
},
{
"answer_id": 30926570,
"author": "Zeus",
"author_id": 4167161,
"author_profile": "https://Stackoverflow.com/users/4167161",
"pm_score": 2,
"selected": false,
"text": "<p>If you use modules, here is the syntax:</p>\n\n<pre><code>PUBLIC :: subname-1, funname-2, ...\n\nPRIVATE :: subname-1, funname-2, ...\n</code></pre>\n\n<p>All entities listed in PRIVATE will not be accessible from outside of the module and all entities listed in PUBLIC can be accessed from outside of the module. All the others entities, by default, can be accessed from outside of the module. </p>\n\n<pre><code>MODULE Field\n IMPLICIT NONE\n\n Integer :: Dimen\n\n PUBLIC :: Gravity\n PRIVATE :: Electric, Magnetic\n\nCONTAINS\n\n INTEGER FUNCTION Gravity()\n ..........\n END FUNCTION Gravity\n\n\n REAL FUNCTION Electric()\n ..........\n END FUNCTION\n\n\n REAL FUNCTION Magnetic()\n ..........\n END FUNCTION\n\n ..........\n\nEND MODULE Field\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
How do I declare a private function in Fortran?
|
This will only work with a Fortran 90 module. In your module declaration, you can specify the access limits for a list of variables and routines using the "public" and "private" keywords. I usually find it helpful to use the private keyword by itself initially, which specifies that everything within the module is private unless explicitly marked public.
In the code sample below, subroutine\_1() and function\_1() are accessible from outside the module via the requisite "use" statement, but any other variable/subroutine/function will be private.
```
module so_example
implicit none
private
public :: subroutine_1
public :: function_1
contains
! Implementation of subroutines and functions goes here
end module so_example
```
|
221,178 |
<p>In my Spring MVC based applications i use Freemarker and i like it very much, but it's lacking advantages provided by Composite View pattern. </p>
<p>I'm thinking of trying to use Tiles2 together with Freemarker - does anyone know where do i find a simple example of SpringMVC together with Tiles2+Freemarker?</p>
|
[
{
"answer_id": 224746,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 2,
"selected": false,
"text": "<p>nevermind, i've solved it. i just had to specify freemarker templates in tiles definitions file</p>\n\n<pre><code><definition name=\"template\" template=\"/WEB-INF/ftl/main.ftl\">\n</code></pre>\n\n<p>and add freemarker servlet/maping to web.xml</p>\n\n<pre><code><servlet>\n <servlet-name>freemarker</servlet-name>\n <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>\n\n <!-- FreemarkerServlet settings: -->\n <init-param>\n <param-name>TemplatePath</param-name>\n <param-value>/</param-value>\n </init-param>\n <init-param>\n <param-name>NoCache</param-name>\n <param-value>true</param-value>\n </init-param>\n <init-param>\n <param-name>ContentType</param-name>\n <param-value>text/html</param-value>\n </init-param>\n\n <!-- FreeMarker settings: -->\n <init-param>\n <param-name>template_update_delay</param-name>\n <param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->\n </init-param>\n <init-param>\n <param-name>default_encoding</param-name>\n <param-value>ISO-8859-1</param-value>\n </init-param>\n <init-param>\n <param-name>number_format</param-name>\n <param-value>0.##########</param-value>\n </init-param>\n\n <load-on-startup>5</load-on-startup>\n</servlet> \n\n <servlet-mapping>\n <servlet-name>freemarker</servlet-name>\n <url-pattern>*.ftl</url-pattern>\n </servlet-mapping>\n</code></pre>\n\n<p>in spring configuration specify tiles as my primary view engine</p>\n\n<pre><code><bean id=\"tilesConfigurer\" class=\"org.springframework.web.servlet.view.tiles2.TilesConfigurer\">\n <property name=\"definitions\">\n <list>\n <value>/WEB-INF/defs/definitions.xml</value>\n </list>\n </property>\n</bean>\n<bean id=\"viewResolver\" class=\"org.springframework.web.servlet.view.UrlBasedViewResolver\">\n <property name=\"viewClass\" value=\"org.springframework.web.servlet.view.tiles2.TilesView\"/>\n</bean>\n</code></pre>\n"
},
{
"answer_id": 224750,
"author": "Andrew Swan",
"author_id": 10433,
"author_profile": "https://Stackoverflow.com/users/10433",
"pm_score": 1,
"selected": false,
"text": "<p>Another product you could use instead of Tiles is <a href=\"http://www.opensymphony.com/sitemesh/\" rel=\"nofollow noreferrer\">SiteMesh</a>, which I've used in some apps. It's worth checking out.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24443/"
] |
In my Spring MVC based applications i use Freemarker and i like it very much, but it's lacking advantages provided by Composite View pattern.
I'm thinking of trying to use Tiles2 together with Freemarker - does anyone know where do i find a simple example of SpringMVC together with Tiles2+Freemarker?
|
nevermind, i've solved it. i just had to specify freemarker templates in tiles definitions file
```
<definition name="template" template="/WEB-INF/ftl/main.ftl">
```
and add freemarker servlet/maping to web.xml
```
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html</param-value>
</init-param>
<!-- FreeMarker settings: -->
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>ISO-8859-1</param-value>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
```
in spring configuration specify tiles as my primary view engine
```
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/definitions.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
```
|
221,181 |
<p>How can I access Ethernet statistics from C/C++ code like <strong>netstat -e</strong>?</p>
<pre><code>Interface Statistics
Received Sent
Bytes 21010071 15425579
Unicast packets 95512 94166
Non-unicast packets 12510 7
Discards 0 0
Errors 0 3
Unknown protocols 0
</code></pre>
|
[
{
"answer_id": 221223,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>Szia,</p>\n\n<p>from <a href=\"http://en.wikipedia.org/wiki/Netstat\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Netstat</a></p>\n\n<blockquote>\n <p>On the Windows platform, netstat\n information can be retrieved by\n calling the GetTcpTable and\n GetUdpTable functions in the IP Helper\n API, or IPHLPAPI.DLL. Information\n returned includes local and remote IP\n addresses, local and remote ports, and\n (for GetTcpTable) TCP status codes. In\n addition to the command-line\n netstat.exe tool that ships with\n Windows, there are GUI-based netstat\n programs available.\n On the Windows platform, this command\n is available only if the Internet\n Protocol (TCP/IP) protocol is\n installed as a component in the\n properties of a network adapter in\n Network Connections.</p>\n</blockquote>\n\n<p>MFC sample at CodeProject: <a href=\"http://www.codeproject.com/KB/applications/wnetstat.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/applications/wnetstat.aspx</a></p>\n"
},
{
"answer_id": 221237,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>The WMI will provide those readings:</p>\n\n<pre><code>SELECT * FROM Win32_PerfFormattedData_Tcpip_IP\nSELECT * FROM Win32_PerfFormattedData_Tcpip_TCP\nSELECT * FROM Win32_PerfFormattedData_Tcpip_UDP\nSELECT * FROM Win32_PerfFormattedData_Tcpip_ICMP\nSELECT * FROM Win32_PerfFormattedData_Tcpip_Networkinterface\n</code></pre>\n\n<p>These classes are available on Windows XP or newer. You may have to resign to the matching \"Win32_PerfRawData\" classes on Windows 2000, and do a little bit more of math before you can display the output.</p>\n\n<p>Find <a href=\"http://msdn.microsoft.com/en-us/library/aa394084(VS.85).aspx\" rel=\"noreferrer\">documentation on all of them</a> in the MSDN.</p>\n"
},
{
"answer_id": 221242,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 1,
"selected": false,
"text": "<p>You might find a feasable <a href=\"http://msdn.microsoft.com/en-us/library/aa392738(VS.85).aspx\" rel=\"nofollow noreferrer\">WMI performance counter</a>, e.g. <a href=\"http://msdn.microsoft.com/en-us/library/aa394340(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32_PerfRawData_Tcpip_NetworkInterface</a>.</p>\n"
},
{
"answer_id": 221247,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": true,
"text": "<p>A good place to start for network statistics would be the <a href=\"http://msdn.microsoft.com/en-us/library/aa365959(VS.85).aspx\" rel=\"nofollow noreferrer\">GetIpStatistics</a> call in the Windows IPHelper functions.</p>\n\n<p>There are a couple of other approaches that are possibly more portable:-</p>\n\n<ul>\n<li>SNMP. Requires SNMP to be enabled on the computer, but can obviously be used to retrieve statistics for remote computers also.</li>\n<li>Pipe the output of 'netstat' into your application, and unpick the values from the text.</li>\n</ul>\n"
},
{
"answer_id": 222425,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>See Google Groups, original netstats source code has been posted many times (win32 api)</p>\n"
},
{
"answer_id": 222530,
"author": "Denes Tarjan",
"author_id": 17617,
"author_profile": "https://Stackoverflow.com/users/17617",
"pm_score": 2,
"selected": false,
"text": "<p>Let me answer to myself, as I asked the same on another forum.</p>\n\n<p>WMI is good, but it's easier to use IpHlpApi instead:</p>\n\n<pre><code>#include <winsock2.h>\n#include <iphlpapi.h>\n\nint main(int argc, char *argv[])\n{\n\nPMIB_IFTABLE pIfTable;\nMIB_IFROW ifRow;\nPMIB_IFROW pIfRow = &ifRow;\nDWORD dwSize = 0;\n\n// first call returns the buffer size needed\nDWORD retv = GetIfTable(pIfTable, &dwSize, true);\nif (retv != ERROR_INSUFFICIENT_BUFFER)\n WriteErrorAndExit(retv);\npIfTable = (MIB_IFTABLE*)malloc(dwSize);\n\nretv = GetIfTable(pIfTable, &dwSize, true);\nif (retv != NO_ERROR)\n WriteErrorAndExit(retv);\n\n// Get index\n int i,j;\n printf(\"\\tNum Entries: %ld\\n\\n\", pIfTable->dwNumEntries);\n for (i = 0; i < (int) pIfTable->dwNumEntries; i++)\n {\n pIfRow = (MIB_IFROW *) & pIfTable->table[i];\n printf(\"\\tIndex[%d]:\\t %ld\\n\", i, pIfRow->dwIndex);\n printf(\"\\tInterfaceName[%d]:\\t %ws\", i, pIfRow->wszName);\n printf(\"\\n\");\n printf(\"\\tDescription[%d]:\\t \", i);\n for (j = 0; j < (int) pIfRow->dwDescrLen; j++)\n printf(\"%c\", pIfRow->bDescr[j]);\n printf(\"\\n\");\n ...\n</code></pre>\n"
},
{
"answer_id": 17976589,
"author": "Laisvis Lingvevicius",
"author_id": 2639020,
"author_profile": "https://Stackoverflow.com/users/2639020",
"pm_score": 0,
"selected": false,
"text": "<p>As above answers suggest, WMI performance counters contains some data. Just be aware that in later versions of windows the perf counters are broken down in v4 vs v6 so the queries are:</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_IPv4</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_TCPv4</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_UDPv4</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_ICMP</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_IPv6</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_TCPv6</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_UDPv6</p>\n\n<p>SELECT * FROM Win32_PerfFormattedData_Tcpip_ICMPv6</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17617/"
] |
How can I access Ethernet statistics from C/C++ code like **netstat -e**?
```
Interface Statistics
Received Sent
Bytes 21010071 15425579
Unicast packets 95512 94166
Non-unicast packets 12510 7
Discards 0 0
Errors 0 3
Unknown protocols 0
```
|
A good place to start for network statistics would be the [GetIpStatistics](http://msdn.microsoft.com/en-us/library/aa365959(VS.85).aspx) call in the Windows IPHelper functions.
There are a couple of other approaches that are possibly more portable:-
* SNMP. Requires SNMP to be enabled on the computer, but can obviously be used to retrieve statistics for remote computers also.
* Pipe the output of 'netstat' into your application, and unpick the values from the text.
|
221,185 |
<p>How can I compile/run C or C++ code in a Unix console or a Mac terminal?</p>
|
[
{
"answer_id": 221189,
"author": "P-A",
"author_id": 4975,
"author_profile": "https://Stackoverflow.com/users/4975",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming the current directory is not in the path, the syntax is <code>./[name of the program]</code>.</p>\n\n<p>For example <code>./a.out</code></p>\n"
},
{
"answer_id": 221193,
"author": "Andrey Neverov",
"author_id": 6698,
"author_profile": "https://Stackoverflow.com/users/6698",
"pm_score": 7,
"selected": false,
"text": "<pre class=\"lang-none prettyprint-override\"><code>gcc main.cpp -o main.out\n./main.out\n</code></pre>\n"
},
{
"answer_id": 221204,
"author": "Nazgob",
"author_id": 3579,
"author_profile": "https://Stackoverflow.com/users/3579",
"pm_score": 3,
"selected": false,
"text": "<p>Add the following to get the best warnings, and you will not regret it. If you can, compile using WISE (<em>warning is error</em>).</p>\n<pre><code>- Wall -pedantic -Weffc++ -Werror\n</code></pre>\n"
},
{
"answer_id": 221222,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Use a <code>makefile</code>. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.</p>\n<p>Read the <a href=\"http://www.gnu.org/software/make/manual/make.html\" rel=\"nofollow noreferrer\"><code>make</code> manual</a>. It seems quite long at first glance, but most sections you can just skim over. All in all, it took me a few hours and made me much more productive.</p>\n"
},
{
"answer_id": 221257,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 9,
"selected": true,
"text": "<p>If it is a simple single-source program,</p>\n<pre class=\"lang-none prettyprint-override\"><code>make foo\n</code></pre>\n<p>where the source file is <em>foo.c</em>, <em>foo.cpp</em>, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.</p>\n<p>Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in <code>$PATH</code> to find executables, and most often that does not include the current directory (<code>.</code>).</p>\n<p>So to run the built executable <code>foo</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>./foo\n</code></pre>\n"
},
{
"answer_id": 224784,
"author": "orj",
"author_id": 20480,
"author_profile": "https://Stackoverflow.com/users/20480",
"pm_score": 4,
"selected": false,
"text": "<p>All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.</p>\n\n<p>You can display this path in the terminal with this command:</p>\n\n<blockquote>\n <p>echo $PATH</p>\n</blockquote>\n\n<p>On Mac OS X (by default) this will display the following colon separated search path:</p>\n\n<blockquote>\n <p>/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin</p>\n</blockquote>\n\n<p>So any executable in the listed directories can by run just by typing in their name. For example:</p>\n\n<blockquote>\n <p>cat mytextfile.txt</p>\n</blockquote>\n\n<p>This runs <code>/bin/cat</code> and displays mytextfile.txt to the terminal.</p>\n\n<p>To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:</p>\n\n<blockquote>\n <p>/Users/oliver/MyProgram</p>\n</blockquote>\n\n<p>If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if <code>MyProgram</code> was in the directory <code>/Users/oliver/MyProject</code> I and I was in my home directory I can qualify the executable name like this, and have it execute:</p>\n\n<blockquote>\n <p>MyProject/MyProgram</p>\n</blockquote>\n\n<p>Or say I was in the directory <code>/Users/oliver/MyProject2</code> and I wanted to execute <code>/Users/oliver/MyProject/MyProgram</code> I can use a relative path like this, to execute it:</p>\n\n<blockquote>\n <p>../MyProject/MyProgram</p>\n</blockquote>\n\n<p>Similarly if I am in the same directory as <code>MyProgram</code> I need to use a \"current directory\" relative path. The current directory you are in is the period character followed by a slash. For example:</p>\n\n<blockquote>\n <p>./MyProgram</p>\n</blockquote>\n\n<p>To determine which directory you are currently in use the <code>pwd</code> command.</p>\n\n<p>If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a \"bin\" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.</p>\n\n<p>This can be does easily by either creating or editing the existing <code>.bash_profile</code> file in your home directory and adding the lines:</p>\n\n<pre><code>#!/bin/sh\nexport PATH=$PATH:~/bin\n</code></pre>\n\n<p>Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in <code>~/bin</code> to be used in preference to system executables your should reorder the export statement as follows:</p>\n\n<pre><code>export PATH=~/bin:$PATH\n</code></pre>\n"
},
{
"answer_id": 5108608,
"author": "Komengem",
"author_id": 619010,
"author_profile": "https://Stackoverflow.com/users/619010",
"pm_score": 6,
"selected": false,
"text": "<p>This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in <strong>Terminal.app</strong>.</p>\n<pre><code>g++ -o lab21 iterative.cpp\n</code></pre>\n<p><code>-o</code> is the letter O, not zero</p>\n<p><code>lab21</code> will be your executable file</p>\n<p><code>iterative.cpp</code> is your C++ file</p>\n<p>After you run that command, type the following in the terminal to run your program:</p>\n<pre><code>./lab21\n</code></pre>\n"
},
{
"answer_id": 8608367,
"author": "Srini Kadamati",
"author_id": 963203,
"author_profile": "https://Stackoverflow.com/users/963203",
"pm_score": 2,
"selected": false,
"text": "<p>I found this link with directions:</p>\n<p><a href=\"http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/\" rel=\"nofollow noreferrer\">http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/</a></p>\n<p>Basically you do:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc hello.c\n./a.out (or with the output file of the first command)\n</code></pre>\n"
},
{
"answer_id": 13714437,
"author": "nerdwaller",
"author_id": 1584762,
"author_profile": "https://Stackoverflow.com/users/1584762",
"pm_score": 4,
"selected": false,
"text": "<p>Do all of this in "Terminal".</p>\n<p>To use the G++ compiler, you need to do this:</p>\n<ol>\n<li><p>Navigate to the directory in which you stored the *.cpp file.</p>\n<p><code>cd ~/programs/myprograms/</code>\n(the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)</p>\n</li>\n<li><p>Compile it</p>\n<p><code>g++ input.cpp -o output.bin</code> (<em>output.bin</em> can be anything with any extension, really. Extension .bin is just common on Unix.)</p>\n<p>There should be <em>nothing</em> returned if it was successful, and that is <strong>okay</strong>. Generally you get returns on failures.</p>\n<p>However, if you type <code>ls</code>, you will see the list of files in the same directory. For example, you would see the other folders, <em>input.cpp</em> and <em>output.bin</em></p>\n</li>\n<li><p>From inside the directory, now execute it with <code>./outbut.bin</code></p>\n</li>\n</ol>\n"
},
{
"answer_id": 24994658,
"author": "Victor Augusto",
"author_id": 1214729,
"author_profile": "https://Stackoverflow.com/users/1214729",
"pm_score": 5,
"selected": false,
"text": "<p>Two steps for me:</p>\n<p>First:</p>\n<pre class=\"lang-none prettyprint-override\"><code>make foo\n</code></pre>\n<p>Then:</p>\n<pre class=\"lang-none prettyprint-override\"><code>./foo\n</code></pre>\n"
},
{
"answer_id": 27935706,
"author": "markthethomas",
"author_id": 3314701,
"author_profile": "https://Stackoverflow.com/users/3314701",
"pm_score": 3,
"selected": false,
"text": "<p>A compact way to go about doing that could be:</p>\n<pre class=\"lang-none prettyprint-override\"><code>make foo && ./$_\n</code></pre>\n<p>It is nice to have a one-liner so you can just rerun your executable again easily.</p>\n"
},
{
"answer_id": 39094485,
"author": "Himanshu Mahajan",
"author_id": 1624283,
"author_profile": "https://Stackoverflow.com/users/1624283",
"pm_score": 0,
"selected": false,
"text": "<p>Running a .C file using the terminal is a two-step process.\nThe first step is to type gcc in the terminal and drop the .C file to the terminal, and then press <kbd>Enter</kbd>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc /Desktop/test.c\n</code></pre>\n<p>In the second step, run the following command:</p>\n<pre class=\"lang-none prettyprint-override\"><code>~/a.out\n</code></pre>\n"
},
{
"answer_id": 49772790,
"author": "Yogesh Nogia",
"author_id": 5954881,
"author_profile": "https://Stackoverflow.com/users/5954881",
"pm_score": 3,
"selected": false,
"text": "<p>To compile C or C++ programs, there is a common command:</p>\n<ol>\n<li><p><code>make filename</code></p>\n</li>\n<li><p><code>./filename</code></p>\n</li>\n</ol>\n<p><em>make</em> will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the <code>gcc</code> compiler to build C programs and <code>g++</code> for C++.</p>\n<p>For C:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc filename.c\n\n./a.out\n</code></pre>\n<p>For C++:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ filename.cpp\n\n./a.out\n</code></pre>\n"
},
{
"answer_id": 52665020,
"author": "Shiv Prakash",
"author_id": 7514765,
"author_profile": "https://Stackoverflow.com/users/7514765",
"pm_score": 2,
"selected": false,
"text": "<p>Just enter in the directory in which your .c/.cpp file is.</p>\n<p>For compiling and running C code.</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc filename.c\n./a.out filename.c\n</code></pre>\n<p>For compiling and running C++ code.</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ filename.cpp\n./a.out filename.cpp\n</code></pre>\n"
},
{
"answer_id": 56603676,
"author": "Alper",
"author_id": 8054623,
"author_profile": "https://Stackoverflow.com/users/8054623",
"pm_score": 2,
"selected": false,
"text": "<p>In order to compile and run C++ source code from a Mac terminal, one needs to do the following:</p>\n<ol>\n<li>If the path of .cpp file is somePath/fileName.cpp, first go the directory with path somePath</li>\n<li>To compile <em>fileName.cpp</em>, type <code>c++ fileName.cpp -o fileName</code></li>\n<li>To run the program, type <code>./fileName</code></li>\n</ol>\n"
},
{
"answer_id": 62215466,
"author": "Teena nath Paul",
"author_id": 1676585,
"author_profile": "https://Stackoverflow.com/users/1676585",
"pm_score": 0,
"selected": false,
"text": "<p>For running C++ files, run the below command, <em>assuming</em> the file name is "main.cpp".</p>\n<ol>\n<li><p>Compile to make an object file from C++ file.</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -c main.cpp -o main.o\n</code></pre>\n</li>\n<li><p>Since <code>#include <conio.h></code> is not supported on macOS, we should use its alternative which is supported on Mac. That is <code>#include <curses.h></code>. Now the object file needs to be converted to an executable file. To use file <em>curses.h</em>, we have to use library <code>-lcurses</code>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -o main main.o -lcurses\n</code></pre>\n</li>\n<li><p>Now run the executable.</p>\n<pre class=\"lang-none prettyprint-override\"><code>./main\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 65272226,
"author": "Shubham Saurav",
"author_id": 7688676,
"author_profile": "https://Stackoverflow.com/users/7688676",
"pm_score": 0,
"selected": false,
"text": "<p>You need to go into the folder where you have saved your file.\nTo compile the code: <code>gcc fileName</code>\nYou can also use the <code>g++ fileName</code>\nThis will compile your code and create a binary.\nNow look for the binary in the same folder and run it.</p>\n"
},
{
"answer_id": 67008542,
"author": "Ashish Kumar",
"author_id": 10830020,
"author_profile": "https://Stackoverflow.com/users/10830020",
"pm_score": 3,
"selected": false,
"text": "<p>Step 1 - create a cpp file using the command</p>\n<pre class=\"lang-none prettyprint-override\"><code>touch test.cpp\n</code></pre>\n<p>Step 2 - Run this command</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ test.cpp\n</code></pre>\n<p>Step 3 - Run your cpp file</p>\n<pre class=\"lang-none prettyprint-override\"><code>./a.out\n</code></pre>\n"
},
{
"answer_id": 71043011,
"author": "Raj BigData",
"author_id": 7222806,
"author_profile": "https://Stackoverflow.com/users/7222806",
"pm_score": 2,
"selected": false,
"text": "<p>I am on a new <a href=\"https://en.wikipedia.org/wiki/MacBook_Pro\" rel=\"nofollow noreferrer\">MacBook Pro</a> with the <a href=\"https://en.wikipedia.org/wiki/Apple_M1_Pro_and_M1_Max\" rel=\"nofollow noreferrer\">Apple M1 Pro</a> chip. I have my <a href=\"https://en.wikipedia.org/wiki/Xcode\" rel=\"nofollow noreferrer\">Xcode</a> installed - both IDE and command line tools. This is how it worked for me:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ one.cpp -o one\n\n./one\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4975/"
] |
How can I compile/run C or C++ code in a Unix console or a Mac terminal?
|
If it is a simple single-source program,
```none
make foo
```
where the source file is *foo.c*, *foo.cpp*, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.
Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in `$PATH` to find executables, and most often that does not include the current directory (`.`).
So to run the built executable `foo`:
```none
./foo
```
|
221,192 |
<p>I have a page, with some code in js and jQuery and it works very well. But unfortunately, all my site is very very old, and uses frames. So when I loaded my page inside a frame, <code>$(document).ready()</code> doesn't fire up.</p>
<p>My frameset looks like:</p>
<pre><code><frameset rows="79,*" frameBorder="1" frameSpacing="1" bordercolor="#5996BF" noresize>
<frame name="header" src="Operations.aspx?main='Info.aspx'" marginwidth="0" marginheight="0" scrolling="no" noresize frameborder="0">
<frame name="main" src="Info.aspx" marginwidth="0" marginheight="0" scrolling="auto" noresize frameborder="0">
</frameset>
</code></pre>
<p>My page is loaded into the <code>main</code> frame. What should I do?</p>
|
[
{
"answer_id": 221234,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": -1,
"selected": false,
"text": "<p>There is no reason for <code>$(document).ready()</code> not to be called.\nBe sure your page contains an include to <code>jquery.js</code>. Try to do a simple test with an empty HTML page and just an alert to see if there is another problem.</p>\n\n<p>If you are trying to use this inside the HTML page that contains the frame's definition, keep in mind that there is no document there, you will have to use the </p>\n"
},
{
"answer_id": 221401,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried to put the jQuery code inside the Info.aspx page?</p>\n"
},
{
"answer_id": 221441,
"author": "matma",
"author_id": 29880,
"author_profile": "https://Stackoverflow.com/users/29880",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if it is the best solution, but when I remove <code>$(document).ready()</code> and keep its body, everything works perfectly.</p>\n"
},
{
"answer_id": 224340,
"author": "Richard B",
"author_id": 30214,
"author_profile": "https://Stackoverflow.com/users/30214",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what you're trying to do, but I have an even older classic asp app that operates out of frames, and I just recently added jQuery functionality and it is working great. The $(document).ready() works fine within a frame, but if you wish to reference the DOM in another frame, you'll have to use the Frame's onload event to let you know when the frame's DOM is loaded. Admittedly, I used iFrames, but the concept should be the same.</p>\n"
},
{
"answer_id": 323141,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to fire the <code>onload</code> event for your frames, then follow these steps:</p>\n\n<ol>\n<li><p>Assign an <code>id</code> and <code>name</code> to each <code><frame></code> tag. Make sure both <code>id</code> and <code>name</code> attributes value is same.</p></li>\n<li><p>Use the following code to fire the <code>onload</code> event of the frame:</p>\n\n<pre><code>$(\"frameName\").ready(function() { \n // Write your frame onload code here\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 488935,
"author": "zachleat",
"author_id": 16711,
"author_profile": "https://Stackoverflow.com/users/16711",
"pm_score": 2,
"selected": false,
"text": "<p>I assume this is a similar problem I was having with DOMContentLoaded in an iframe.</p>\n\n<p>I wrote <a href=\"http://www.zachleat.com/web/2008/12/04/domcontentloaded-inconsistencies/\" rel=\"nofollow noreferrer\">a blog post about it</a>.</p>\n"
},
{
"answer_id": 3064350,
"author": "jenming",
"author_id": 369654,
"author_profile": "https://Stackoverflow.com/users/369654",
"pm_score": 3,
"selected": false,
"text": "<p>I have tried the method mentioned in another comment:</p>\n\n<pre><code>$(\"#frameName\").ready(function() {\n // Write you frame on load javascript code here\n} );\n</code></pre>\n\n<p>and it did not work for me. </p>\n\n<p>this did:</p>\n\n<pre><code>$(\"#frameName\").load( function() {\n //code goes here\n} );\n</code></pre>\n\n<p>Even though the event does not fire as quickly - it waits until images and css have loaded also.</p>\n"
},
{
"answer_id": 9082075,
"author": "brobert7",
"author_id": 1075723,
"author_profile": "https://Stackoverflow.com/users/1075723",
"pm_score": 2,
"selected": false,
"text": "<p>The following also worked for me:</p>\n\n<pre><code><script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js\"></script>\n<script>\n$(window.parent.frames[0].document).ready(function() {\n // Do stuff\n});\n</script>\n</code></pre>\n\n<p>The [0] indicates that it is the first frame in the document, [1] would be the second frame, and so on. This is particularly nice if you do not have control over the mark-up, and it is still utilizing document ready.</p>\n"
},
{
"answer_id": 10943864,
"author": "Jochen",
"author_id": 1443796,
"author_profile": "https://Stackoverflow.com/users/1443796",
"pm_score": 1,
"selected": false,
"text": "<p>I have worked a long time with this post... here is my solution.</p>\n\n<p>test.html</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n<head>\n <script src=\"http://code.jquery.com/jquery-latest.js\"></script>\n\n <script> \n document.write('<frameset><frame name=\"frame_content\" id=\"frame_content\"></frame></frameset>');\n\n $('#frame_content').attr('src', 'test2.html');\n $('#frame_content').load(function()\n {\n if('${\"#header\"}' != '') {\n $(\"#header\", frame_content.document).remove();\n }\n });\n if($('#frame_content').complete) $('#frame_content').trigger(\"load\");\n </script>\n\n</head>\n</html>\n</code></pre>\n\n<p>test2.html</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n\n <head>\n </head>\n\n <body>\n <div id=\"header\">You will never see me, cause I have been removed!</div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 11322965,
"author": "elfan",
"author_id": 1500595,
"author_profile": "https://Stackoverflow.com/users/1500595",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old topic. But to help some of you who reach this page, here is my solution:</p>\n\n<pre><code>$($(\"#frameName\")[0].contentWindow.document).ready(function() {\n // Write you frame onready code here\n});\n</code></pre>\n"
},
{
"answer_id": 27140768,
"author": "Edward Olamisan",
"author_id": 556649,
"author_profile": "https://Stackoverflow.com/users/556649",
"pm_score": 0,
"selected": false,
"text": "<p>No need to modify the markup. Just fix the selector. It should be: </p>\n\n<pre><code>$(\"frame[name='main']\").ready(function(){..}); \n</code></pre>\n\n<p>not </p>\n\n<pre><code>$(\"#frameName\").ready(function(){..}); \n</code></pre>\n\n<p>Note: it seems the jQuery ready event fires multiple times. Make sure that is OK with your logic.</p>\n"
},
{
"answer_id": 35680918,
"author": "newstockie",
"author_id": 4890961,
"author_profile": "https://Stackoverflow.com/users/4890961",
"pm_score": 0,
"selected": false,
"text": "<p>This answer may be late, but this reply may help someone like me... </p>\n\n<p>This can be done via native Javascript code - </p>\n\n<pre><code>ifrm2 = var ifrm2 = document.getElementById('frm2');\nif (ifrm2.contentDocument.readyState == 'complete') {\n //here goes the code after frame fully loaded\n}\n\n //id = frm2 is the id of iframe in my page\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29880/"
] |
I have a page, with some code in js and jQuery and it works very well. But unfortunately, all my site is very very old, and uses frames. So when I loaded my page inside a frame, `$(document).ready()` doesn't fire up.
My frameset looks like:
```
<frameset rows="79,*" frameBorder="1" frameSpacing="1" bordercolor="#5996BF" noresize>
<frame name="header" src="Operations.aspx?main='Info.aspx'" marginwidth="0" marginheight="0" scrolling="no" noresize frameborder="0">
<frame name="main" src="Info.aspx" marginwidth="0" marginheight="0" scrolling="auto" noresize frameborder="0">
</frameset>
```
My page is loaded into the `main` frame. What should I do?
|
I have tried the method mentioned in another comment:
```
$("#frameName").ready(function() {
// Write you frame on load javascript code here
} );
```
and it did not work for me.
this did:
```
$("#frameName").load( function() {
//code goes here
} );
```
Even though the event does not fire as quickly - it waits until images and css have loaded also.
|
221,194 |
<p>I have table employee like,
<br>
employee
(
emp_id int primary key,
emp_name varchar(50),
mngr_id int)</p>
<p>and here mngr_id would either null or contain valid emp_id. This way it form the hierarchy of employees in the organization.</p>
<p>In order to traverse the entire hierarchy I had to write the recursive stored procedure. (in Oracle it's easy by using CONNECT BY .. START WITH)</p>
<p>So the question is that what is the performance impact of such stored procedure given that the level of hierarchy would not go beyond 10 levels !</p>
<p>Is there any other way to achieve the same ?</p>
|
[
{
"answer_id": 221205,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding the last question: There are a few nice options at <a href=\"https://stackoverflow.com/questions/192220/what-is-the-most-efficientelegant-way-to-parse-a-flat-table-into-a-tree\">\"What is the most efficient/elegant way to parse a flat table into a tree?\"</a></p>\n\n<p>You should also consider caching the result of the recursion in an intermediate table. If you change that only on update to your hierarchy table, the recursion performance hit will be negligible.</p>\n\n<p>EDIT:\nPersonally I would do the recursion in the presentation layer of my app, for example on the web server. This provides greater flexibility compared to what can be achieved in SQL, and you can also use session or application level caching. (Using a pre-constructed DB table that is kept up to date with a trigger never leaves you with an outdated cache, though.)</p>\n"
},
{
"answer_id": 3316922,
"author": "Stooshie",
"author_id": 400089,
"author_profile": "https://Stackoverflow.com/users/400089",
"pm_score": 0,
"selected": false,
"text": "<p>Tomalak: \" ... I would do the recursion in the presentation layer of my app ... \"</p>\n\n<p>This would mean every time the recursion happened another call is sent to the database server from the presentation layer. That would be incredibly slow.</p>\n"
},
{
"answer_id": 3318497,
"author": "Jon Black",
"author_id": 298016,
"author_profile": "https://Stackoverflow.com/users/298016",
"pm_score": 2,
"selected": false,
"text": "<p>a fairly simple iterative adjacency list db server side solution: <a href=\"http://pastie.org/1056977\" rel=\"nofollow noreferrer\">http://pastie.org/1056977</a></p>\n\n<pre><code>delimiter ;\n\ndrop procedure if exists employee_hier;\n\ndelimiter #\n\ncreate procedure employee_hier\n(\nin p_emp_id smallint unsigned\n)\nbegin\n\ndeclare p_done tinyint unsigned default(0);\ndeclare p_depth smallint unsigned default(0);\n\ncreate temporary table hier(\n boss_id smallint unsigned, \n emp_id smallint unsigned, \n depth smallint unsigned\n)engine = memory;\n\ninsert into hier values (null, p_emp_id, p_depth);\n\n/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */\n\ncreate temporary table emps engine=memory select * from hier;\n\nwhile p_done <> 1 do\n\n if exists( select 1 from employee e inner join hier on e.boss_id = hier.emp_id and hier.depth = p_depth) then\n\n insert into hier select e.boss_id, e.emp_id, p_depth + 1 \n from employee e inner join emps on e.boss_id = emps.emp_id and emps.depth = p_depth;\n\n set p_depth = p_depth + 1; \n\n truncate table emps;\n insert into emps select * from hier where depth = p_depth;\n\n else\n set p_done = 1;\n end if;\n\nend while;\n\nselect \n e.emp_id,\n e.name as emp_name,\n b.emp_id as boss_emp_id,\n b.name as boss_name,\n hier.depth\nfrom \n hier\ninner join employee e on hier.emp_id = e.emp_id\ninner join employee b on hier.boss_id = b.emp_id;\n\ndrop temporary table if exists hier;\ndrop temporary table if exists emps;\n\nend #\n\ndelimiter ;\n\n\ncall employee_hier(1);\ncall employee_hier(3);\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] |
I have table employee like,
employee
(
emp\_id int primary key,
emp\_name varchar(50),
mngr\_id int)
and here mngr\_id would either null or contain valid emp\_id. This way it form the hierarchy of employees in the organization.
In order to traverse the entire hierarchy I had to write the recursive stored procedure. (in Oracle it's easy by using CONNECT BY .. START WITH)
So the question is that what is the performance impact of such stored procedure given that the level of hierarchy would not go beyond 10 levels !
Is there any other way to achieve the same ?
|
a fairly simple iterative adjacency list db server side solution: <http://pastie.org/1056977>
```
delimiter ;
drop procedure if exists employee_hier;
delimiter #
create procedure employee_hier
(
in p_emp_id smallint unsigned
)
begin
declare p_done tinyint unsigned default(0);
declare p_depth smallint unsigned default(0);
create temporary table hier(
boss_id smallint unsigned,
emp_id smallint unsigned,
depth smallint unsigned
)engine = memory;
insert into hier values (null, p_emp_id, p_depth);
/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */
create temporary table emps engine=memory select * from hier;
while p_done <> 1 do
if exists( select 1 from employee e inner join hier on e.boss_id = hier.emp_id and hier.depth = p_depth) then
insert into hier select e.boss_id, e.emp_id, p_depth + 1
from employee e inner join emps on e.boss_id = emps.emp_id and emps.depth = p_depth;
set p_depth = p_depth + 1;
truncate table emps;
insert into emps select * from hier where depth = p_depth;
else
set p_done = 1;
end if;
end while;
select
e.emp_id,
e.name as emp_name,
b.emp_id as boss_emp_id,
b.name as boss_name,
hier.depth
from
hier
inner join employee e on hier.emp_id = e.emp_id
inner join employee b on hier.boss_id = b.emp_id;
drop temporary table if exists hier;
drop temporary table if exists emps;
end #
delimiter ;
call employee_hier(1);
call employee_hier(3);
```
|
221,224 |
<p>Consider the following code snippet</p>
<pre><code>private void ProcessFile(string fullPath) {
XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath);
while (rdr.Read()) {
//Do something
}
return;
}
</code></pre>
<p>Now, this functions fine when passed a path like:</p>
<p>"C:\Work Files\Technical Information\Dummy.xml"</p>
<p>But throws an error when passed</p>
<p>"C:\Work Files\#Technical Information\Dummy.xml"</p>
<p>Note that all folders and files specified exist and that the hash character is a valid character for paths. The error details are:</p>
<p><p>System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Work Files\'.
<br> at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
<br> at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
<br> at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
<br> at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
<br> at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
<br> at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
<br> at System.Threading.CompressedStack.runTryCode(Object userData)
<br> at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
<br> at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
<br> at System.Xml.XmlTextReaderImpl.OpenUrl()
<br> at System.Xml.XmlTextReaderImpl.Read()
<br> at System.Xml.XmlTextReader.Read()</p>
<p><p>Anybody know what's going on?</p>
|
[
{
"answer_id": 221243,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "<p>Try omitting the <code>file:///</code> protocol prefix. It works for me without one. I believe .NET will truncate any part after the <code>#</code> if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the <code>#</code> character isn't processed by the server but rather by the client in other scenarios (e.g. web browsers).</p>\n"
},
{
"answer_id": 221248,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use </p>\n\n<p>XmlTextReader rdr = new XmlTextReader(fullPath);</p>\n"
},
{
"answer_id": 221251,
"author": "Carl",
"author_id": 951280,
"author_profile": "https://Stackoverflow.com/users/951280",
"pm_score": 2,
"selected": false,
"text": "<p>Adding to Konrad's answer, if you are using the file:// protocol, you need to use %23 for # then it works fine</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389021/"
] |
Consider the following code snippet
```
private void ProcessFile(string fullPath) {
XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath);
while (rdr.Read()) {
//Do something
}
return;
}
```
Now, this functions fine when passed a path like:
"C:\Work Files\Technical Information\Dummy.xml"
But throws an error when passed
"C:\Work Files\#Technical Information\Dummy.xml"
Note that all folders and files specified exist and that the hash character is a valid character for paths. The error details are:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Work Files\'.
at System.IO.\_\_Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY\_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
Anybody know what's going on?
|
Try omitting the `file:///` protocol prefix. It works for me without one. I believe .NET will truncate any part after the `#` if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the `#` character isn't processed by the server but rather by the client in other scenarios (e.g. web browsers).
|
221,254 |
<p>In Visual Studio, when you compile foo.idl, MIDL generates the proxy information in foo_p.c.</p>
<p>Unfortunately, for Win32 and x64 files, it uses the same filename. For Win32, the file starts with:</p>
<pre><code>#if !defined(_M_IA64) && !defined(_M_AMD64)
</code></pre>
<p>For x64, the file starts with:</p>
<pre><code>#if defined(_M_AMD64)
</code></pre>
<p>When you build for Win32 and then immediately build for x64, it doesn't replace the foo_p.c file, meaning that the project fails to link.</p>
<p>I tried having a pre-build event that deletes the foo_p.c file if it's for the wrong architecture, but VS doesn't even bother to run that step.</p>
<p>How should I get it so that I can build one configuration and then the other?</p>
|
[
{
"answer_id": 221319,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 3,
"selected": true,
"text": "<p>You could modify the compiler settings for your IDL file to specify a different file name for the output proxy file according to the target platform. (Select Properties on the IDL file, then Configuration Properties / MIDL / Output).</p>\n\n<ul>\n<li>For Win32 builds, use <code>foo_p_w32.c</code></li>\n<li>For x64 builds, use <code>foo_p_x64.c</code></li>\n</ul>\n\n<p>Then, in your Win32 project settings, exclude the file <code>foo_p_x64.c</code> and vice versa for the x64 project.</p>\n\n<p>You need to do the same for the _i.c file, otherwise Visual Studio doesn't seem to rebuild the IDL at all.</p>\n"
},
{
"answer_id": 4918170,
"author": "dexblack",
"author_id": 534513,
"author_profile": "https://Stackoverflow.com/users/534513",
"pm_score": 0,
"selected": false,
"text": "<p>Here are the configuration changes we use to allow automated builds to work cleanly</p>\n\n<p>Change</p>\n\n<pre><code><Tool\nName=\"VCMIDLTool\"\nTypeLibraryName=\"$(ProjectName).tlb\"\nOutputDirectory=\"$(SolutionDir)$(PlatformName)\"\nHeaderFileName=\"$(ProjectName)_h.h\"\nDLLDataFileName=\"$(ProjectName)_dlldata.c\"\n/>\n</code></pre>\n\n<p>To</p>\n\n<pre><code><Tool\n Name=\"VCMIDLTool\"\n TypeLibraryName=\"$(InputName).tlb\"\n OutputDirectory=\"$(SolutionDir)$(PlatformName)\"\n HeaderFileName=\"$(InputName)_i.h\"\n DLLDataFileName=\"$(InputName)_dlldata.c\"\n InterfaceIdentifierFileName=\"$(InputName)_i.c\"\n ProxyFileName=\"$(InputName)_p.c\"\n/>\n</code></pre>\n\n<p>and add <strong>$(SolutionDir)$(PlatformName)</strong> to your C++ Additional Include Directories</p>\n\n<p>e.g.</p>\n\n<pre><code><Tool Name=\"VCCLCompilerTool\" ...\nAdditionalIncludeDirectories=\"...;&quot;$(SolutionDir)$(PlatformName);&quot;\"\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
In Visual Studio, when you compile foo.idl, MIDL generates the proxy information in foo\_p.c.
Unfortunately, for Win32 and x64 files, it uses the same filename. For Win32, the file starts with:
```
#if !defined(_M_IA64) && !defined(_M_AMD64)
```
For x64, the file starts with:
```
#if defined(_M_AMD64)
```
When you build for Win32 and then immediately build for x64, it doesn't replace the foo\_p.c file, meaning that the project fails to link.
I tried having a pre-build event that deletes the foo\_p.c file if it's for the wrong architecture, but VS doesn't even bother to run that step.
How should I get it so that I can build one configuration and then the other?
|
You could modify the compiler settings for your IDL file to specify a different file name for the output proxy file according to the target platform. (Select Properties on the IDL file, then Configuration Properties / MIDL / Output).
* For Win32 builds, use `foo_p_w32.c`
* For x64 builds, use `foo_p_x64.c`
Then, in your Win32 project settings, exclude the file `foo_p_x64.c` and vice versa for the x64 project.
You need to do the same for the \_i.c file, otherwise Visual Studio doesn't seem to rebuild the IDL at all.
|
221,267 |
<p>What is the simplest way of copying symbolic links on the Mac?</p>
<p>A python or perl solution would be preferred, but any solution would be a help.</p>
<p>I am copying frameworks for an installation package, and need the links to be maintained</p>
|
[
{
"answer_id": 221305,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "<p>In python you can use <a href=\"http://docs.python.org/library/os.html#os.readlink\" rel=\"nofollow noreferrer\">os.readlink</a> and <a href=\"http://docs.python.org/library/os.html#os.symlink\" rel=\"nofollow noreferrer\">os.symlink</a> to perform this action. You should check if what you operate on is actually a symbolic link with <a href=\"http://docs.python.org/library/os.html#os.lstat\" rel=\"nofollow noreferrer\">os.lstat</a> and <a href=\"http://docs.python.org/library/stat.html#stat.S_ISLNK\" rel=\"nofollow noreferrer\">stat.S_ISLNK</a></p>\n\n<pre><code>import os, stat\nif stat.S_ISLNK(os.lstat('foo').st_mode):\n src = os.readlink('source')\n os.symlink(src, 'destination')\n</code></pre>\n\n<p>You could do it with the <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/cp.1.html\" rel=\"nofollow noreferrer\">-R option of cp</a>. This works because cp by default does not follow symbolic links but barks at copying non-files without specifying -R which means recursion.</p>\n\n<pre><code>cp -R source destination\n</code></pre>\n\n<p>In python that would be with the <a href=\"http://docs.python.org/library/subprocess.html#subprocess.call\" rel=\"nofollow noreferrer\">subprocess.call</a></p>\n\n<pre><code>from subprocess import call\ncall(['cp', '-R', 'source', 'destination'])\n</code></pre>\n\n<p>Note that a <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/Articles/Aliases.html\" rel=\"nofollow noreferrer\">macosx alias</a> is not a symbolic link and therefore symbolic link specific treatment will fail on it.</p>\n"
},
{
"answer_id": 221306,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 0,
"selected": false,
"text": "<p>As you tagged python, i asume you mean something like copytree(src, dst[, symlinks]). Real symlinks (created by ln -s) will be copied as on any unix system. But if you create an alias with the finder, you wont get a symlink, but an alias. The MacOS offers two types of links: unix type symlinks and aliases (see <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/Articles/Aliases.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/Articles/Aliases.html</a>). These aliases are not treated as links by many tools - neither copytree as i know.</p>\n"
},
{
"answer_id": 221316,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 7,
"selected": true,
"text": "<p>As David mentioned, OS X is missing the handy -a option that gnu cp has.</p>\n\n<p>However, if you use -R to do a recursive copy, then it will copy symlinks by default, so</p>\n\n<pre><code>cp -R source destination\n</code></pre>\n\n<p>ought to work.</p>\n"
},
{
"answer_id": 42466294,
"author": "n1000",
"author_id": 2075003,
"author_profile": "https://Stackoverflow.com/users/2075003",
"pm_score": 4,
"selected": false,
"text": "<p>The solution of <em>@brian d foy</em> used to be correct. Newer versions of macOS do support</p>\n\n<pre><code>cp -a\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259/"
] |
What is the simplest way of copying symbolic links on the Mac?
A python or perl solution would be preferred, but any solution would be a help.
I am copying frameworks for an installation package, and need the links to be maintained
|
As David mentioned, OS X is missing the handy -a option that gnu cp has.
However, if you use -R to do a recursive copy, then it will copy symlinks by default, so
```
cp -R source destination
```
ought to work.
|
221,273 |
<p>I've been given a prototype/mockup of a grid written in html and javascript (via ExtJS) that I now need to implement within an ASP.net web application. Does anyone have any pointers as to how to pass data to the grid (to a GroupingStore, specifically). </p>
<p>I'd rather not have a proliferation of web services or helper pages returning XML/JSON so if there's a way to use Client callbacks or Page Methods (Can't you tell I'm not particularly familiar with either - buzzword bingo!) or somesuch, that would be preferred.</p>
<p>Please, no recommendations that I use jQuery, the built-in ASP.net grid, or any other UI framework. The use of the ExtJS grid has been mandated by the powers that be, so that's the grid I'm using, for better or worse :)</p>
|
[
{
"answer_id": 221286,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 2,
"selected": false,
"text": "<p>I believe a service that simply returns json structures for your pages is the best option, nicely abstracted and reusable across the application rather than page methods.</p>\n"
},
{
"answer_id": 221360,
"author": "tobinharris",
"author_id": 1136215,
"author_profile": "https://Stackoverflow.com/users/1136215",
"pm_score": 2,
"selected": true,
"text": "<p>Here's a low tech solution. It doesn't require use of web services or any other additional technologies.</p>\n\n<p><strong>Step 1</strong></p>\n\n<p>Have an ASPX page that takes one paramter, and invoked like this:</p>\n\n<pre><code>http://mysite.com/query.aspx?sql=select * from orders where status = 'open'\n</code></pre>\n\n<p><strong>Step 2</strong></p>\n\n<p>In the code behind, do something like this</p>\n\n<pre><code>void Page_Load(object sender, EventArgs e)\n{\n Response.ContentType=\"text/json\"; \n DataTable contents = ExecuteDataTable(Request[\"sql\"]);\n Response.Write( JRockSerialize( contents ) );\n Response.End();\n}\n</code></pre>\n\n<p>You can use <a href=\"http://jayrock.berlios.de/\" rel=\"nofollow noreferrer\">JRock</a> for serializing a data table to JSON. \nIMHO this gives the cleanest JSON. </p>\n\n<p>So that's getting <code>DataTable</code> to JSON sorted...</p>\n\n<p><em>WARNING: This is obviously a simplistic example. You shouldn't pass SQL on the query string as it is not secure (your could use named queries and parameters instead).</em></p>\n\n<p><strong>Step 3</strong></p>\n\n<p>In your ExtJS code, create a grid with Json datastore as shown in this <a href=\"http://www.extjs.com/deploy/dev/examples/grid/binding.html\" rel=\"nofollow noreferrer\">Ext example</a>. Set the data store <code>url:</code> to that of your query.aspx page with appropriate query string parameters. </p>\n\n<p>You'll also need to set the columns up for the grid, again shown in the ExtJs example.</p>\n\n<p><strong>Alternatively...</strong></p>\n\n<p>I was really impressed when I looked at the <a href=\"http://www.coolite.com/\" rel=\"nofollow noreferrer\">Coolite samples</a> recently. They are an ExtJS partner and provide a good ASP.NET & ExtJS experience. And no, I don't work for them :) I haven't tried their grid, but it might be painless (at a price).</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] |
I've been given a prototype/mockup of a grid written in html and javascript (via ExtJS) that I now need to implement within an ASP.net web application. Does anyone have any pointers as to how to pass data to the grid (to a GroupingStore, specifically).
I'd rather not have a proliferation of web services or helper pages returning XML/JSON so if there's a way to use Client callbacks or Page Methods (Can't you tell I'm not particularly familiar with either - buzzword bingo!) or somesuch, that would be preferred.
Please, no recommendations that I use jQuery, the built-in ASP.net grid, or any other UI framework. The use of the ExtJS grid has been mandated by the powers that be, so that's the grid I'm using, for better or worse :)
|
Here's a low tech solution. It doesn't require use of web services or any other additional technologies.
**Step 1**
Have an ASPX page that takes one paramter, and invoked like this:
```
http://mysite.com/query.aspx?sql=select * from orders where status = 'open'
```
**Step 2**
In the code behind, do something like this
```
void Page_Load(object sender, EventArgs e)
{
Response.ContentType="text/json";
DataTable contents = ExecuteDataTable(Request["sql"]);
Response.Write( JRockSerialize( contents ) );
Response.End();
}
```
You can use [JRock](http://jayrock.berlios.de/) for serializing a data table to JSON.
IMHO this gives the cleanest JSON.
So that's getting `DataTable` to JSON sorted...
*WARNING: This is obviously a simplistic example. You shouldn't pass SQL on the query string as it is not secure (your could use named queries and parameters instead).*
**Step 3**
In your ExtJS code, create a grid with Json datastore as shown in this [Ext example](http://www.extjs.com/deploy/dev/examples/grid/binding.html). Set the data store `url:` to that of your query.aspx page with appropriate query string parameters.
You'll also need to set the columns up for the grid, again shown in the ExtJs example.
**Alternatively...**
I was really impressed when I looked at the [Coolite samples](http://www.coolite.com/) recently. They are an ExtJS partner and provide a good ASP.NET & ExtJS experience. And no, I don't work for them :) I haven't tried their grid, but it might be painless (at a price).
|
221,277 |
<p>I'm trying to do XHTML DOM parsing with JTidy, and it seems to be rather counterintuitive task. In particular, there's a method to parse HTML:</p>
<pre><code>Node Tidy.parse(Reader, Writer)
</code></pre>
<p>And to get the <body /> of that Node, I assume, I should use</p>
<pre><code>Node Node.findBody(TagTable)
</code></pre>
<p>Where should I get an instance of that TagTable? (Constructor is protected, and I haven't found a factory to produce it.)</p>
<p>I use JTidy 8.0-SNAPSHOT.</p>
|
[
{
"answer_id": 221327,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the <code>parseDOM</code> method instead, which would give you a <code>org.w3c.dom.Document</code> back:</p>\n\n<pre><code>Document document = Tidy.parseDOM(reader, writer);\nNode body = document.getElementsByTagName(\"body\").item(0);\n</code></pre>\n"
},
{
"answer_id": 221402,
"author": "ansgri",
"author_id": 1764,
"author_profile": "https://Stackoverflow.com/users/1764",
"pm_score": 4,
"selected": true,
"text": "<p>I found there's <em>much</em> simpler method to extract the body:</p>\n\n<pre>\ntidy = new Tidy();\ntidy.setXHTML(true);\n<b>tidy.setPrintBodyOnly(true);</b>\n</pre>\n\n<p>And then use tidy on the Reader-Writer pair.</p>\n\n<p>Simple as it should be.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764/"
] |
I'm trying to do XHTML DOM parsing with JTidy, and it seems to be rather counterintuitive task. In particular, there's a method to parse HTML:
```
Node Tidy.parse(Reader, Writer)
```
And to get the <body /> of that Node, I assume, I should use
```
Node Node.findBody(TagTable)
```
Where should I get an instance of that TagTable? (Constructor is protected, and I haven't found a factory to produce it.)
I use JTidy 8.0-SNAPSHOT.
|
I found there's *much* simpler method to extract the body:
```
tidy = new Tidy();
tidy.setXHTML(true);
**tidy.setPrintBodyOnly(true);**
```
And then use tidy on the Reader-Writer pair.
Simple as it should be.
|
221,283 |
<p>I like to keep my shell sessions named with useful titles as I work, this helps me keep track of what I'm using each of the many tabs for.</p>
<p>Currently to rename a session I double click its name on the tabbed part of the console - is there any command that I can use to do this from within the shell? It would save me a bit of time.</p>
<p>thanks in advance</p>
<p>edit :-
I am using KDE's Konsole shell.</p>
|
[
{
"answer_id": 221289,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The article <a href=\"http://www.faqs.org/docs/Linux-mini/Xterm-Title.html\" rel=\"nofollow noreferrer\">How to change the title of an xterm</a> should help.</p>\n"
},
{
"answer_id": 221290,
"author": "GodEater",
"author_id": 6756,
"author_profile": "https://Stackoverflow.com/users/6756",
"pm_score": 1,
"selected": false,
"text": "<p>The answer to this really depends on the terminal program you're using. </p>\n\n<p>However, I'll just assume it's sensible, and emulates an xterm enough that it respects xterm escape codes - in which case, you probably want to look here : <a href=\"http://www.faqs.org/docs/Linux-mini/Xterm-Title.html#s3\" rel=\"nofollow noreferrer\">http://www.faqs.org/docs/Linux-mini/Xterm-Title.html#s3</a></p>\n\n<p>Note: unwind's example below requires echo to be called like this \"echo -ne\", otherwise the '\\' characters are echoed literally.</p>\n"
},
{
"answer_id": 221293,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://www.faqs.org/docs/Linux-mini/Xterm-Title.html\" rel=\"nofollow noreferrer\">this page</a>, you should be able to use something like this:</p>\n\n<pre><code>echo -n \"\\033]0;New Window Title\\007\"\n</code></pre>\n\n<p>I'm not in Linux at the moment, so this is untested. I do know that it is possible to change the window title under program control, so this seems likely to work.</p>\n"
},
{
"answer_id": 222216,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Currently to rename a session I double click its name on the tabbed part of the console</p>\n</blockquote>\n\n<p>This sounds like you're using KDE's Konsole. Is this true?</p>\n\n<p>If so, in KDE 3:</p>\n\n<pre><code>dcop $KONSOLE_DCOP_SESSION renameSession \"I am renamed!\"\n</code></pre>\n\n<p>In KDE 4, the old DCOP interfaces haven't been ported over to the new D-BUS IPC yet, but you can change the settings for tabnames to follow the window name set by each screen, and set the window name as described by the other answers.</p>\n"
},
{
"answer_id": 6153679,
"author": "Blisterpeanuts",
"author_id": 773265,
"author_profile": "https://Stackoverflow.com/users/773265",
"pm_score": 2,
"selected": false,
"text": "<p>For /usr/bin/konsole\nyou can change the title of a konsole terminal from the menu:\nSettings->Edit Current Profile->Tabs</p>\n\n<p>edit \"Tab title format\" to be whatever you want. After interacting with the shell, the title will reset to what you put.</p>\n\n<p>for /usr/bin/xterm running in xorg-server 2:1.10.1-1ubuntu1</p>\n\n<p>echo -ne \"\\033]0;My Fun X-Terminal\\007\"</p>\n"
},
{
"answer_id": 10402391,
"author": "cyber-monk",
"author_id": 468304,
"author_profile": "https://Stackoverflow.com/users/468304",
"pm_score": 1,
"selected": false,
"text": "<p>For the default terminal on Ubuntu (I'm still on 10.04) try <strong>xtitle</strong>. </p>\n\n<pre><code>$> sudo apt-get install xtitle\n ...\n$> xtitle --title wow it worked!\n or simply\n$> xtitle this is great\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22061/"
] |
I like to keep my shell sessions named with useful titles as I work, this helps me keep track of what I'm using each of the many tabs for.
Currently to rename a session I double click its name on the tabbed part of the console - is there any command that I can use to do this from within the shell? It would save me a bit of time.
thanks in advance
edit :-
I am using KDE's Konsole shell.
|
>
> Currently to rename a session I double click its name on the tabbed part of the console
>
>
>
This sounds like you're using KDE's Konsole. Is this true?
If so, in KDE 3:
```
dcop $KONSOLE_DCOP_SESSION renameSession "I am renamed!"
```
In KDE 4, the old DCOP interfaces haven't been ported over to the new D-BUS IPC yet, but you can change the settings for tabnames to follow the window name set by each screen, and set the window name as described by the other answers.
|
221,294 |
<p>I want a single number that represents the current date and time, like a <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix timestamp</a>.</p>
|
[
{
"answer_id": 221297,
"author": "daveb",
"author_id": 11858,
"author_profile": "https://Stackoverflow.com/users/11858",
"pm_score": 13,
"selected": true,
"text": "<h3>Timestamp in milliseconds</h3>\n<p>To get the number of milliseconds since <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"noreferrer\">Unix epoch</a>, call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\" rel=\"noreferrer\"><code>Date.now</code></a>:</p>\n<pre><code>Date.now()\n</code></pre>\n<p>Alternatively, use the unary operator <code>+</code> to call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf\" rel=\"noreferrer\"><code>Date.prototype.valueOf</code></a>:</p>\n<pre><code>+ new Date()\n</code></pre>\n<p>Alternatively, call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf\" rel=\"noreferrer\"><code>valueOf</code></a> directly:</p>\n<pre><code>new Date().valueOf()\n</code></pre>\n<p>To support IE8 and earlier (see <a href=\"http://kangax.github.io/compat-table/es5/#Date.now\" rel=\"noreferrer\">compatibility table</a>), create a <em>shim</em> for <code>Date.now</code>:</p>\n<pre><code>if (!Date.now) {\n Date.now = function() { return new Date().getTime(); }\n}\n</code></pre>\n<p>Alternatively, call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime\" rel=\"noreferrer\"><code>getTime</code></a> directly:</p>\n<pre><code>new Date().getTime()\n</code></pre>\n<hr />\n<h3>Timestamp in seconds</h3>\n<p>To get the number of seconds since <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"noreferrer\">Unix epoch</a>, i.e. <em>Unix timestamp</em>:</p>\n<pre><code>Math.floor(Date.now() / 1000)\n</code></pre>\n<p>Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations <a href=\"https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number\">1</a>, <a href=\"https://stackoverflow.com/a/11446757/1519836\">2</a>):</p>\n<pre><code>Date.now() / 1000 | 0\n</code></pre>\n<hr />\n<h3>Timestamp in milliseconds (higher resolution)</h3>\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Performance/now\" rel=\"noreferrer\"><code>performance.now</code></a>:</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>var isPerformanceSupported = (\n window.performance &&\n window.performance.now &&\n window.performance.timing &&\n window.performance.timing.navigationStart\n);\n\nvar timeStampInMs = (\n isPerformanceSupported ?\n window.performance.now() +\n window.performance.timing.navigationStart :\n Date.now()\n);\n\nconsole.log(timeStampInMs, Date.now());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 221357,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 7,
"selected": false,
"text": "<pre><code>var time = Date.now || function() {\n return +new Date;\n};\n\ntime();\n</code></pre>\n"
},
{
"answer_id": 221771,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 7,
"selected": false,
"text": "<pre><code>var timestamp = Number(new Date()); // current time as number\n</code></pre>\n"
},
{
"answer_id": 807980,
"author": "Tom Viner",
"author_id": 15890,
"author_profile": "https://Stackoverflow.com/users/15890",
"pm_score": 6,
"selected": false,
"text": "<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>console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 1714649,
"author": "Kiragaz",
"author_id": 208609,
"author_profile": "https://Stackoverflow.com/users/208609",
"pm_score": -1,
"selected": false,
"text": "<pre><code>time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);\n</code></pre>\n"
},
{
"answer_id": 5036460,
"author": "xer0x",
"author_id": 47604,
"author_profile": "https://Stackoverflow.com/users/47604",
"pm_score": 9,
"selected": false,
"text": "<p>I like this, because it is small:</p>\n\n<pre><code>+new Date\n</code></pre>\n\n<p>I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better: </p>\n\n<pre><code>Date.now()\n</code></pre>\n"
},
{
"answer_id": 5971324,
"author": "Daithí",
"author_id": 288644,
"author_profile": "https://Stackoverflow.com/users/288644",
"pm_score": 8,
"selected": false,
"text": "<p>JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.</p>\n\n<p>This will give you a Unix timestamp (in seconds):</p>\n\n<pre><code>var unix = Math.round(+new Date()/1000);\n</code></pre>\n\n<p>This will give you the milliseconds since the epoch (not Unix timestamp):</p>\n\n<pre><code>var milliseconds = new Date().getTime();\n</code></pre>\n"
},
{
"answer_id": 10428184,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime\"><code>Date.getTime()</code></a> method can be used with a little tweak:</p>\n\n<blockquote>\n <p>The value returned by the getTime method is the number of milliseconds\n since 1 January 1970 00:00:00 UTC.</p>\n</blockquote>\n\n<p>Divide the result by 1000 to get the Unix timestamp, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor\"><code>floor</code></a> if necessary:</p>\n\n<pre><code>(new Date).getTime() / 1000\n</code></pre>\n\n<hr>\n\n<p><sup>The <code>Date.valueOf()</code> method is functionally equivalent to <code>Date.getTime()</code>, which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.</sup></p>\n"
},
{
"answer_id": 11446757,
"author": "GottZ",
"author_id": 1519836,
"author_profile": "https://Stackoverflow.com/users/1519836",
"pm_score": 7,
"selected": false,
"text": "<p><em><strong>I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear</strong></em></p>\n<hr />\n<p><strong>Quick and dirty solution:</strong></p>\n<pre><code>Date.now() /1000 |0\n</code></pre>\n<blockquote>\n<p><em><strong>Warning</strong>: it <strong>might</strong> break in 2038 and return negative numbers if you do the <code>|0</code> magic. Use <code>Math.floor()</code> instead by that time</em></p>\n</blockquote>\n<p><strong><code>Math.floor()</code> solution:</strong></p>\n<pre><code>Math.floor(Date.now() /1000);\n</code></pre>\n<hr />\n<p><strong>Some nerdy alternative by <a href=\"//stackoverflow.com/users/283863\">Derek 朕會功夫</a> taken from the comments below this answer:</strong></p>\n<pre><code>new Date/1e3|0\n</code></pre>\n<hr />\n<p><strong>Polyfill to get <code>Date.now()</code> working:</strong></p>\n<p>To get it working in IE you could do this (Polyfill from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\" rel=\"noreferrer\">MDN</a>):</p>\n<pre><code>if (!Date.now) {\n Date.now = function now() {\n return new Date().getTime();\n };\n}\n</code></pre>\n<hr />\n<p><strong>If you do not care about the year / day of week / daylight saving time you need to remember this for dates after 2038:</strong></p>\n<p>Bitwise operations will cause usage of 32 Bit Integers instead of 64 Bit Floating Point.</p>\n<p>You will need to properly use it as:</p>\n<pre><code>Math.floor(Date.now() / 1000)\n</code></pre>\n<hr />\n<p>If you just want to know the relative time from the point of when the code was run through first you could use something like this:</p>\n<pre><code>const relativeTime = (() => {\n const start = Date.now();\n return () => Date.now() - start;\n})();\n</code></pre>\n<hr />\n<p><strong>In case you are using jQuery you could use <code>$.now()</code> as described in <a href=\"http://api.jquery.com/jquery.now/\" rel=\"noreferrer\">jQuery's Docs</a> which makes the polyfill obsolete since <code>$.now()</code> internally does the same thing: <code>(new Date).getTime()</code></strong></p>\n<p>If you are just happy about jQuery's version, consider upvoting <a href=\"//stackoverflow.com/a/15434736/1519836\"><strong>this</strong></a> answer since I did not find it myself.</p>\n<hr />\n<p><strong>Now a tiny explaination of what <code>|0</code> does:</strong></p>\n<p>By providing <code>|</code>, you tell the interpreter to do a binary OR operation.<br />\nBit operations require absolute numbers which turns the decimal result from <code>Date.now() / 1000</code> into an integer.</p>\n<p>During that conversion, decimals are removed, resulting in a similar result to what using <code>Math.floor()</code> would output.</p>\n<blockquote>\n<p><strong>Be warned though:</strong> it will convert a 64 bit double to a 32 bit integer.<br />\nThis will result in information loss when dealing with huge numbers.<br />\nTimestamps will break after 2038 due to 32 bit integer overflow unless Javascript moves to 64 Bit Integers in Strict Mode.</p>\n</blockquote>\n<hr />\n<p><strong>For further information about <code>Date.now</code> follow this link: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\" rel=\"noreferrer\"><code>Date.now()</code> @ MDN</a></strong></p>\n"
},
{
"answer_id": 12536800,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 6,
"selected": false,
"text": "<p>Just to add up, here's a function to return a timestamp string in Javascript. \nExample: 15:06:38 PM</p>\n\n<pre><code>function displayTime() {\n var str = \"\";\n\n var currentTime = new Date()\n var hours = currentTime.getHours()\n var minutes = currentTime.getMinutes()\n var seconds = currentTime.getSeconds()\n\n if (minutes < 10) {\n minutes = \"0\" + minutes\n }\n if (seconds < 10) {\n seconds = \"0\" + seconds\n }\n str += hours + \":\" + minutes + \":\" + seconds + \" \";\n if(hours > 11){\n str += \"PM\"\n } else {\n str += \"AM\"\n }\n return str;\n}\n</code></pre>\n"
},
{
"answer_id": 15434736,
"author": "VisioN",
"author_id": 1249581,
"author_profile": "https://Stackoverflow.com/users/1249581",
"pm_score": 6,
"selected": false,
"text": "<p><em>jQuery</em> provides <a href=\"http://api.jquery.com/jQuery.now/\" rel=\"noreferrer\">its own method</a> to get the timestamp:</p>\n\n<pre><code>var timestamp = $.now();\n</code></pre>\n\n<p><sup>(besides it just implements <code>(new Date).getTime()</code> expression)</sup></p>\n\n<p><strong>REF:</strong> <a href=\"http://api.jquery.com/jQuery.now/\" rel=\"noreferrer\">http://api.jquery.com/jQuery.now/</a></p>\n"
},
{
"answer_id": 16456126,
"author": "SBotirov",
"author_id": 1942750,
"author_profile": "https://Stackoverflow.com/users/1942750",
"pm_score": 4,
"selected": false,
"text": "<p>Any browsers not supported Date.now, you can use this for get current date time:</p>\n\n<pre><code>currentTime = Date.now() || +new Date()\n</code></pre>\n"
},
{
"answer_id": 16666424,
"author": "deepakssn",
"author_id": 1411589,
"author_profile": "https://Stackoverflow.com/users/1411589",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss </p>\n\n<pre><code>function getTimeStamp() {\n var now = new Date();\n return ((now.getMonth() + 1) + '/' +\n (now.getDate()) + '/' +\n now.getFullYear() + \" \" +\n now.getHours() + ':' +\n ((now.getMinutes() < 10)\n ? (\"0\" + now.getMinutes())\n : (now.getMinutes())) + ':' +\n ((now.getSeconds() < 10)\n ? (\"0\" + now.getSeconds())\n : (now.getSeconds())));\n}\n</code></pre>\n"
},
{
"answer_id": 17398791,
"author": "Anoop P S",
"author_id": 1338683,
"author_profile": "https://Stackoverflow.com/users/1338683",
"pm_score": 4,
"selected": false,
"text": "<p>This one has a solution : which converts unixtime stamp to tim in js try this</p>\n\n<pre><code>var a = new Date(UNIX_timestamp*1000);\nvar hour = a.getUTCHours();\nvar min = a.getUTCMinutes();\nvar sec = a.getUTCSeconds();\n</code></pre>\n"
},
{
"answer_id": 19602603,
"author": "Vicky Gonsalves",
"author_id": 1548301,
"author_profile": "https://Stackoverflow.com/users/1548301",
"pm_score": 3,
"selected": false,
"text": "<p>more simpler way:</p>\n\n<pre><code>var timeStamp=event.timestamp || new Date().getTime();\n</code></pre>\n"
},
{
"answer_id": 22756677,
"author": "Belldandu",
"author_id": 3271268,
"author_profile": "https://Stackoverflow.com/users/3271268",
"pm_score": 5,
"selected": false,
"text": "<p>One I haven't seen yet </p>\n\n<pre><code>Math.floor(Date.now() / 1000); // current time in seconds\n</code></pre>\n\n<p>Another one I haven't seen yet is</p>\n\n<pre><code>var _ = require('lodash'); // from here https://lodash.com/docs#now\n_.now();\n</code></pre>\n"
},
{
"answer_id": 23261705,
"author": "DevC",
"author_id": 973699,
"author_profile": "https://Stackoverflow.com/users/973699",
"pm_score": 3,
"selected": false,
"text": "<p>sometime I need it in objects for xmlhttp calls, so I do like this.</p>\n\n<pre><code>timestamp : parseInt(new Date().getTime()/1000, 10)\n</code></pre>\n"
},
{
"answer_id": 23816968,
"author": "Saucier",
"author_id": 2174320,
"author_profile": "https://Stackoverflow.com/users/2174320",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at <a href=\"http://jsfiddle.net/AcLzd/9/\" rel=\"nofollow\">jsfiddle</a>):</p>\n\n<pre><code>var pad = function(int) { return int < 10 ? 0 + int : int; };\nvar timestamp = new Date();\n\n timestamp.day = [\n pad(timestamp.getDate()),\n pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.\n timestamp.getFullYear()\n ];\n\n timestamp.time = [\n pad(timestamp.getHours()),\n pad(timestamp.getMinutes()),\n pad(timestamp.getSeconds())\n ];\n\ntimestamp.now = parseInt(timestamp.day.join(\"\") + timestamp.time.join(\"\"));\nalert(timestamp.now);\n</code></pre>\n"
},
{
"answer_id": 28890441,
"author": "Rimian",
"author_id": 63810,
"author_profile": "https://Stackoverflow.com/users/63810",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://momentjs.com\" rel=\"noreferrer\">Moment.js</a> can abstract away a lot of the pain in dealing with Javascript Dates. </p>\n\n<p>See: <a href=\"http://momentjs.com/docs/#/displaying/unix-timestamp/\" rel=\"noreferrer\">http://momentjs.com/docs/#/displaying/unix-timestamp/</a></p>\n\n<pre><code>moment().unix();\n</code></pre>\n"
},
{
"answer_id": 28983302,
"author": "georgez",
"author_id": 2113279,
"author_profile": "https://Stackoverflow.com/users/2113279",
"pm_score": 4,
"selected": false,
"text": "<p>I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of <a href=\"https://github.com/carhartl/jquery-cookie/blob/master/src/jquery.cookie.js\" rel=\"noreferrer\">JQuery Cookie</a> the other day.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>var date = new Date();\nvar timestamp = +date;\n</code></pre>\n"
},
{
"answer_id": 29287521,
"author": "Eugene",
"author_id": 1062764,
"author_profile": "https://Stackoverflow.com/users/1062764",
"pm_score": 2,
"selected": false,
"text": "<p><code>var my_timestamp = ~~(Date.now()/1000);</code></p>\n"
},
{
"answer_id": 29299909,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The advised, proper way is <code>Number(new Date())</code>, \nin terms of code- readability,</p>\n\n<p>Also, UglifyJS and Google-Closure-Compiler will lower the complexity of the parsed code-logic-tree (relevant if you are using one of them to obscure/minify your code). </p>\n\n<p>for Unix timestamp, which has a lower time resolution, just divide current number with <code>1000</code>, keeping the whole. </p>\n"
},
{
"answer_id": 29341730,
"author": "Muhammad Reda",
"author_id": 863380,
"author_profile": "https://Stackoverflow.com/users/863380",
"pm_score": 4,
"selected": false,
"text": "<p>For <a href=\"https://lodash.com/docs#now\">lodash</a> and <a href=\"http://underscorejs.org/#now\">underscore</a> users, use <code>_.now</code>.</p>\n\n<pre><code>var timestamp = _.now(); // in milliseconds\n</code></pre>\n"
},
{
"answer_id": 29600955,
"author": "jameslouiz",
"author_id": 3562401,
"author_profile": "https://Stackoverflow.com/users/3562401",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var d = new Date();\nconsole.log(d.valueOf()); \n</code></pre>\n"
},
{
"answer_id": 30531157,
"author": "Kevinleary.net",
"author_id": 172870,
"author_profile": "https://Stackoverflow.com/users/172870",
"pm_score": 4,
"selected": false,
"text": "<p>If want a basic way to generate a timestamp in Node.js this works well.</p>\n\n<pre><code>var time = process.hrtime();\nvar timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );\n</code></pre>\n\n<p>Our team is using this to bust cache in a localhost environment. The output is <code>/dist/css/global.css?v=245521377</code> where <code>245521377</code> is the timestamp generated by <code>hrtime()</code>. </p>\n\n<p>Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.</p>\n"
},
{
"answer_id": 31236206,
"author": "iter",
"author_id": 5046452,
"author_profile": "https://Stackoverflow.com/users/5046452",
"pm_score": 5,
"selected": false,
"text": "<p>For a timestamp with microsecond resolution, there's <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Performance/now\" rel=\"noreferrer\"><code>performance.now</code></a>:</p>\n\n<pre><code>function time() { \n return performance.now() + performance.timing.navigationStart;\n}\n</code></pre>\n\n<p>This could for example yield <code>1436140826653.139</code>, while <code>Date.now</code> only gives <code>1436140826653</code>.</p>\n"
},
{
"answer_id": 31401583,
"author": "FullStack",
"author_id": 3694557,
"author_profile": "https://Stackoverflow.com/users/3694557",
"pm_score": 5,
"selected": false,
"text": "<p>I highly recommend using <code>moment.js</code>. To get the number of milliseconds since UNIX epoch, do </p>\n\n<pre><code>moment().valueOf()\n</code></pre>\n\n<p>To get the number of seconds since UNIX epoch, do</p>\n\n<pre><code>moment().unix()\n</code></pre>\n\n<p>You can also convert times like so:</p>\n\n<pre><code>moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()\n</code></pre>\n\n<p>I do that all the time. No pun intended.</p>\n\n<p>To use <code>moment.js</code> in the browser:</p>\n\n<pre><code><script src=\"moment.js\"></script>\n<script>\n moment().valueOf();\n</script>\n</code></pre>\n\n<p>For more details, including other ways of installing and using MomentJS, see their <a href=\"http://momentjs.com/docs/\" rel=\"noreferrer\">docs</a></p>\n"
},
{
"answer_id": 32845874,
"author": "blueberry0xff",
"author_id": 3059453,
"author_profile": "https://Stackoverflow.com/users/3059453",
"pm_score": 4,
"selected": false,
"text": "<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>// The Current Unix Timestamp\r\n// 1443534720 seconds since Jan 01 1970. (UTC)\r\n\r\n// seconds\r\nconsole.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720\r\nconsole.log(Math.floor(Date.now() / 1000)); // 1443534720\r\nconsole.log(Math.floor(new Date().getTime() / 1000)); // 1443534720\r\n\r\n// milliseconds\r\nconsole.log(Math.floor(new Date().valueOf())); // 1443534720087\r\nconsole.log(Math.floor(Date.now())); // 1443534720087\r\nconsole.log(Math.floor(new Date().getTime())); // 1443534720087\r\n\r\n// jQuery\r\n// seconds\r\nconsole.log(Math.floor($.now() / 1000)); // 1443534720\r\n// milliseconds\r\nconsole.log($.now()); // 1443534720087</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 33028757,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 4,
"selected": false,
"text": "<p>This seems to work.</p>\n\n<pre><code>console.log(clock.now);\n// returns 1444356078076\n\nconsole.log(clock.format(clock.now));\n//returns 10/8/2015 21:02:16\n\nconsole.log(clock.format(clock.now + clock.add(10, 'minutes'))); \n//returns 10/8/2015 21:08:18\n\nvar clock = {\n now:Date.now(),\n add:function (qty, units) {\n switch(units.toLowerCase()) {\n case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;\n case 'days' : val = qty * 1000 * 60 * 60 * 24; break;\n case 'hours' : val = qty * 1000 * 60 * 60; break;\n case 'minutes' : val = qty * 1000 * 60; break;\n case 'seconds' : val = qty * 1000; break;\n default : val = undefined; break;\n }\n return val;\n },\n format:function (timestamp){\n var date = new Date(timestamp);\n var year = date.getFullYear();\n var month = date.getMonth() + 1;\n var day = date.getDate();\n var hours = date.getHours();\n var minutes = \"0\" + date.getMinutes();\n var seconds = \"0\" + date.getSeconds();\n // Will display time in xx/xx/xxxx 00:00:00 format\n return formattedTime = month + '/' + \n day + '/' + \n year + ' ' + \n hours + ':' + \n minutes.substr(-2) + \n ':' + seconds.substr(-2);\n }\n};\n</code></pre>\n"
},
{
"answer_id": 33131028,
"author": "Valentin Podkamennyi",
"author_id": 5438323,
"author_profile": "https://Stackoverflow.com/users/5438323",
"pm_score": 5,
"selected": false,
"text": "<p>The code <code>Math.floor(new Date().getTime() / 1000)</code> can be shortened to <code>new Date / 1E3 | 0</code>.</p>\n\n<p>Consider to skip direct <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime\" rel=\"noreferrer\"><code>getTime()</code></a> invocation and use <code>| 0</code> as a replacement for <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/floor\" rel=\"noreferrer\"><code>Math.floor()</code></a> function.\nIt's also good to remember <code>1E3</code> is a shorter equivalent for <code>1000</code> (uppercase E is preferred than lowercase to indicate <code>1E3</code> as a constant).</p>\n\n<p>As a result you get the following:</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-js lang-js prettyprint-override\"><code>var ts = new Date / 1E3 | 0;\r\n\r\nconsole.log(ts);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35087703,
"author": "Joaquinglezsantos",
"author_id": 5325015,
"author_profile": "https://Stackoverflow.com/users/5325015",
"pm_score": 6,
"selected": false,
"text": "<p>In addition to the other options, if you want a dateformat ISO, you can get it directly</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>console.log(new Date().toISOString());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 36027644,
"author": "Jitendra Pawar",
"author_id": 4305683,
"author_profile": "https://Stackoverflow.com/users/4305683",
"pm_score": 5,
"selected": false,
"text": "<p>You can only use </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-js lang-js prettyprint-override\"><code> var timestamp = new Date().getTime();\r\n console.log(timestamp);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>to get the current timestamp. No need to do anything extra.</p>\n"
},
{
"answer_id": 44082035,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Date</strong>, a <strong>native object</strong> in JavaScript is the way we get all data about time.</p>\n\n<p>Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the <strong>server-side</strong>. </p>\n\n<p>Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:</p>\n\n<pre><code>Date.now(); //return 1495255666921\n</code></pre>\n\n<p>In MDN it's mentioned as below:</p>\n\n<blockquote>\n <p>The Date.now() method returns the number of milliseconds elapsed since\n 1 January 1970 00:00:00 UTC.<br>\n Because now() is a static method of Date, you always use it as Date.now().</p>\n</blockquote>\n\n<p>If you using a version below ES5, <code>Date.now();</code> not works and you need to use:</p>\n\n<pre><code>new Date().getTime();\n</code></pre>\n"
},
{
"answer_id": 47810722,
"author": "Olemak",
"author_id": 3278654,
"author_profile": "https://Stackoverflow.com/users/3278654",
"pm_score": 4,
"selected": false,
"text": "<p>As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:</p>\n\n<pre><code>Date.now()\n</code></pre>\n\n<p>If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:</p>\n\n<pre><code>const currentTimestamp = (!Date.now ? +new Date() : Date.now());\n</code></pre>\n\n<p>This will return the milliseconds since epoch time, of course, not seconds.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\" rel=\"noreferrer\" title=\"Date.now on MDN\">MDN Documentation on Date.now</a></p>\n"
},
{
"answer_id": 49526664,
"author": "unknown123",
"author_id": 8590807,
"author_profile": "https://Stackoverflow.com/users/8590807",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function getTimeStamp() {\n var now = new Date();\n return ((now.getMonth() + 1) + '/' +\n (now.getDate()) + '/' +\n now.getFullYear() + \" \" +\n now.getHours() + ':' +\n ((now.getMinutes() < 10)\n ? (\"0\" + now.getMinutes())\n : (now.getMinutes())) + ':' +\n ((now.getSeconds() < 10)\n ? (\"0\" + now.getSeconds())\n : (now.getSeconds())));\n}\n</code></pre>\n"
},
{
"answer_id": 51067600,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 6,
"selected": false,
"text": "<h1>Performance</h1>\n<p>Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0</p>\n<h3>Conclusions</h3>\n<ul>\n<li>Solution <code>Date.now()</code> (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution</li>\n<li>Solution <code>performance.now()</code> (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome</li>\n<li>Solutions C,D,F are quite slow on all browsers</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/lCTrK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lCTrK.png\" alt=\"enter image description here\" /></a></p>\n<h3>Details</h3>\n<p>Results for chrome</p>\n<p><a href=\"https://i.stack.imgur.com/Eaco2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Eaco2.png\" alt=\"enter image description here\" /></a></p>\n<p>You can perform test on your machine <a href=\"https://jsbench.me/f5k9ckm6lh/1\" rel=\"noreferrer\">HERE</a></p>\n<p>Code used in tests is presented in below snippet</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function A() {\n return new Date().getTime();\n}\n\nfunction B() {\n return new Date().valueOf();\n}\n\nfunction C() {\n return +new Date();\n}\n\nfunction D() {\n return new Date()*1;\n}\n\nfunction E() {\n return Date.now();\n}\n\nfunction F() {\n return Number(new Date());\n}\n\nfunction G() {\n // this solution returns time counted from loading the page.\n // (and on Chrome it gives better precission)\n return performance.now(); \n}\n\n\n\n// TEST\n\nlog = (n,f) => console.log(`${n} : ${f()}`);\n\nlog('A',A);\nlog('B',B);\nlog('C',C);\nlog('D',D);\nlog('E',E);\nlog('F',F);\nlog('G',G);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>This snippet only presents code used in external benchmark</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 56202700,
"author": "cenkarioz",
"author_id": 6846195,
"author_profile": "https://Stackoverflow.com/users/6846195",
"pm_score": 4,
"selected": false,
"text": "<p>If it is for logging purposes, you can use <strong>ISOString</strong></p>\n\n<p><code>new Date().toISOString()</code></p>\n\n<blockquote>\n <p>\"2019-05-18T20:02:36.694Z\"</p>\n</blockquote>\n"
},
{
"answer_id": 59043796,
"author": "Ashish",
"author_id": 10943108,
"author_profile": "https://Stackoverflow.com/users/10943108",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Get TimeStamp In JavaScript</strong></p>\n<blockquote>\n<p>In JavaScript, a timestamp is the number of milliseconds that have passed since January 1, 1970.</p>\n<p>If you don't intend to support < IE8, you can use</p>\n</blockquote>\n<pre><code>new Date().getTime(); + new Date(); and Date.now();\n</code></pre>\n<p>to directly get the timestamp without having to create a new Date object.</p>\n<blockquote>\n<p>To return the required timestamp</p>\n</blockquote>\n<pre><code>new Date("11/01/2018").getTime()\n</code></pre>\n"
},
{
"answer_id": 60489900,
"author": "Ganesh",
"author_id": 4060431,
"author_profile": "https://Stackoverflow.com/users/4060431",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>To get time, month, day, year separately this will work</p>\n</blockquote>\n\n<pre><code>var currentTime = new Date();\nvar month = currentTime.getMonth() + 1;\nvar day = currentTime.getDate();\nvar year = currentTime.getFullYear();\n</code></pre>\n"
},
{
"answer_id": 65848448,
"author": "Flash Noob",
"author_id": 12106367,
"author_profile": "https://Stackoverflow.com/users/12106367",
"pm_score": 2,
"selected": false,
"text": "<p>there are many ways to do it.</p>\n<pre><code> Date.now() \n new Date().getTime() \n new Date().valueOf()\n</code></pre>\n<blockquote>\n<p>To get the timestamp in seconds, convert it using:</p>\n</blockquote>\n<pre><code>Math.floor(Date.now() / 1000)\n</code></pre>\n"
},
{
"answer_id": 70266631,
"author": "dazzafact",
"author_id": 1163485,
"author_profile": "https://Stackoverflow.com/users/1163485",
"pm_score": 3,
"selected": false,
"text": "<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>//if you need 10 digits\n alert('timestamp '+ts());\nfunction ts() {\n return parseInt(Date.now()/1000);\n\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 74412005,
"author": "RyadPasha",
"author_id": 9937620,
"author_profile": "https://Stackoverflow.com/users/9937620",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/**\n * Equivalent to PHP's time(), which returns\n * current Unix timestamp.\n *\n * @param {string} unit - Unit of time to return.\n * - Use 's' for seconds and 'ms' for milliseconds.\n * @return {number}\n */\ntime(unit = 's') {\n return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()\n}\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
I want a single number that represents the current date and time, like a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
|
### Timestamp in milliseconds
To get the number of milliseconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time), call [`Date.now`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now):
```
Date.now()
```
Alternatively, use the unary operator `+` to call [`Date.prototype.valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf):
```
+ new Date()
```
Alternatively, call [`valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf) directly:
```
new Date().valueOf()
```
To support IE8 and earlier (see [compatibility table](http://kangax.github.io/compat-table/es5/#Date.now)), create a *shim* for `Date.now`:
```
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
```
Alternatively, call [`getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) directly:
```
new Date().getTime()
```
---
### Timestamp in seconds
To get the number of seconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time), i.e. *Unix timestamp*:
```
Math.floor(Date.now() / 1000)
```
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations [1](https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number), [2](https://stackoverflow.com/a/11446757/1519836)):
```
Date.now() / 1000 | 0
```
---
### Timestamp in milliseconds (higher resolution)
Use [`performance.now`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now):
```js
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
```
|
221,307 |
<p>I've been scanning through all the popular js libraries, but I can't find one that has a width function for a DOM element that actually accounts for quirks mode in Internet Explorer. The issue is that padding and borders don't get counted in the the width when quirks mode is engaged. As far as I can tell this happens when the doctype is left out or the doctype is set to html 3.2.</p>
<p>Obviously I could just set the doctype to something standards compliant, but this script can be embedded anywhere so I don't have control over the doctype.</p>
<p>To break the problem down into smaller parts:</p>
<p>1) How do you detect quirks mode?
2) What's the best way to extract the border and padding from an element to compensate?</p>
<p>Example with prototype:</p>
<pre><code><html>
<head>
</head>
<body>
<div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div>
<script>
alert($('mydiv').getWidth())
</script>
</body>
</html>
</code></pre>
<p>result:</p>
<p>253 (ff)
250 (ie)</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 221405,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 1,
"selected": false,
"text": "<p>The library is probably telling the true. The problem is not that the readings are incorect but that the acutal display is incorect. As an example try:</p>\n\n<pre><code><div id=\"mydiv\" style=\"width: 100px; border-left: 100px black solid;\">&nbsp;</div>\n</code></pre>\n\n<p>then try to change the text inside the div to see what is happening. IE will display various values depending on the text inside while FF will display correctly. IE is trying to fill an 100px + something into a 100px space with various results.</p>\n\n<p>jQuery has two methods for width: .width and .outerWidth. .outerWidth will return the full width of the element. It also has the possiblity to get all the other properties (padding, border etc) like in the example bellow:</p>\n\n<pre><code>$(document).ready(function() {\n alert(\"width=\" + $('#mydiv').width() \n + \" outerWidth=\" + $('#mydiv').outerWidth() \n + \" borderLeftWidth=\" + $('#mydiv').css(\"borderLeftWidth\"))\n});\n</code></pre>\n"
},
{
"answer_id": 221703,
"author": "Jeremy B.",
"author_id": 28567,
"author_profile": "https://Stackoverflow.com/users/28567",
"pm_score": 1,
"selected": false,
"text": "<pre><code>javascript:(function(){\n var mode=document.compatmode,m;if(mode){\n if(mode=='BackCompat')m='quirks';\n else if(mode=='CSS1Compat')m='Standard';\n else m='Almost Standard';\n alert('The page is rendering in '+m+' mode.');\n }\n})();\n</code></pre>\n\n<p>that code will detect the mode for you.</p>\n\n<p>IE will also throw into quirks mode if ANYTHING but doctype is on the first line. Even a blank first line with doctype on the second line will cause quirks mode.</p>\n"
},
{
"answer_id": 221895,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 3,
"selected": true,
"text": "<p>@1</p>\n\n<pre><code>document.compatMode\n</code></pre>\n\n<p>\"CSS1Compat\" means \"<em>standards mode</em>\" and \"BackCompat\" means \"<em>quirks mode</em>\".</p>\n\n<p>@2</p>\n\n<p>offsetWidth property of a HTML elements gives its width on screen, in pixels.</p>\n\n<pre><code><div id=\"mydiv\" style=\"width: 250px; padding-left: 1px; border: 2px black solid\">hello</div>\n\ndocument.getElementById('mydiv').offsetWidth\n//255 (standards) 250 (quirks)\n</code></pre>\n\n<p>A function that compensates the width for IE quirksmode has to check for the rendering mode then add borders and padding to the width;</p>\n\n<pre><code>function compensateWidth( el, targetWidth ){\n\n var removeUnit = function( str ){\n if( str.indexOf('px') ){\n return str.replace('px','') * 1;\n }\n else { //because won't work for other units... one may wish to implement \n return 0;\n }\n }\n if(document.compatMode && document.compatMode==\"BackCompat\"){\n if(targetWidth && el.offsetWidth < targetWidth){\n el.style.width = targetWidth;\n }\n else if (el.currentStyle){\n var borders = removeUnit(el.currentStyle['borderLeftWidth']) + removeUnit(el.currentStyle['borderRightWidth']);\n var paddings = removeUnit(el.currentStyle['paddingLeft']) + removeUnit(el.currentStyle['paddingRight']);\n el.style.width = el.offsetWidth + borders + paddings +'px';\n }\n }\n\n}\n</code></pre>\n\n<p>Now there are two ways to use it:</p>\n\n<pre><code>var div = document.getElementById('mydiv')\n// will try to calculate target width, but won't be able to work with units other than px\ncompensateWidth( div );\n\n//if you know what the width should be in standards mode\ncompensateWidth( div, 254 );\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29899/"
] |
I've been scanning through all the popular js libraries, but I can't find one that has a width function for a DOM element that actually accounts for quirks mode in Internet Explorer. The issue is that padding and borders don't get counted in the the width when quirks mode is engaged. As far as I can tell this happens when the doctype is left out or the doctype is set to html 3.2.
Obviously I could just set the doctype to something standards compliant, but this script can be embedded anywhere so I don't have control over the doctype.
To break the problem down into smaller parts:
1) How do you detect quirks mode?
2) What's the best way to extract the border and padding from an element to compensate?
Example with prototype:
```
<html>
<head>
</head>
<body>
<div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div>
<script>
alert($('mydiv').getWidth())
</script>
</body>
</html>
```
result:
253 (ff)
250 (ie)
Thanks in advance!
|
@1
```
document.compatMode
```
"CSS1Compat" means "*standards mode*" and "BackCompat" means "*quirks mode*".
@2
offsetWidth property of a HTML elements gives its width on screen, in pixels.
```
<div id="mydiv" style="width: 250px; padding-left: 1px; border: 2px black solid">hello</div>
document.getElementById('mydiv').offsetWidth
//255 (standards) 250 (quirks)
```
A function that compensates the width for IE quirksmode has to check for the rendering mode then add borders and padding to the width;
```
function compensateWidth( el, targetWidth ){
var removeUnit = function( str ){
if( str.indexOf('px') ){
return str.replace('px','') * 1;
}
else { //because won't work for other units... one may wish to implement
return 0;
}
}
if(document.compatMode && document.compatMode=="BackCompat"){
if(targetWidth && el.offsetWidth < targetWidth){
el.style.width = targetWidth;
}
else if (el.currentStyle){
var borders = removeUnit(el.currentStyle['borderLeftWidth']) + removeUnit(el.currentStyle['borderRightWidth']);
var paddings = removeUnit(el.currentStyle['paddingLeft']) + removeUnit(el.currentStyle['paddingRight']);
el.style.width = el.offsetWidth + borders + paddings +'px';
}
}
}
```
Now there are two ways to use it:
```
var div = document.getElementById('mydiv')
// will try to calculate target width, but won't be able to work with units other than px
compensateWidth( div );
//if you know what the width should be in standards mode
compensateWidth( div, 254 );
```
|
221,317 |
<p>I've created a custom search page with some defined options in my search scope.</p>
<p>I have a metadata mapped <code>jobtitle</code>, and added the search option to my custom search.</p>
<pre><code><Property name="JobTitle"
ManagedName="title"
ProfileURI="urn:schemas-microsoft-com:sharepoint:portal:profile:Title"/>
</code></pre>
<p>I want to change my managed name to <code>jobtitle</code>, because title doesn't hit the dutch word for jobtitle. I changed the managed name to <code>jobtitle</code>, after applying the changes it wouldn't change the label.</p>
<p>Anyone have an idea?</p>
|
[
{
"answer_id": 223496,
"author": "Nat",
"author_id": 13813,
"author_profile": "https://Stackoverflow.com/users/13813",
"pm_score": 0,
"selected": false,
"text": "<p>Changes to the managed properties will not appear in the search results until the data is re-crawled. I suggest you reset the search index and do a full crawl.</p>\n"
},
{
"answer_id": 227583,
"author": "RedDeckWins",
"author_id": 1646,
"author_profile": "https://Stackoverflow.com/users/1646",
"pm_score": 1,
"selected": false,
"text": "<p>It is a little difficult to know exactly what you're problem is since you are using a custom search page.</p>\n\n<p>I am assuming you created a new Managed property and mapped it to something. Then you added it to the advanced search webpart via editing the <code>xsl/xml</code> (directions <a href=\"http://www.sharepoint-tips.com/2006/07/found-it-how-to-add-properties-to.html\" rel=\"nofollow noreferrer\">here</a>). If you change the name of the property you just added you need to update the webpart as well.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28139/"
] |
I've created a custom search page with some defined options in my search scope.
I have a metadata mapped `jobtitle`, and added the search option to my custom search.
```
<Property name="JobTitle"
ManagedName="title"
ProfileURI="urn:schemas-microsoft-com:sharepoint:portal:profile:Title"/>
```
I want to change my managed name to `jobtitle`, because title doesn't hit the dutch word for jobtitle. I changed the managed name to `jobtitle`, after applying the changes it wouldn't change the label.
Anyone have an idea?
|
It is a little difficult to know exactly what you're problem is since you are using a custom search page.
I am assuming you created a new Managed property and mapped it to something. Then you added it to the advanced search webpart via editing the `xsl/xml` (directions [here](http://www.sharepoint-tips.com/2006/07/found-it-how-to-add-properties-to.html)). If you change the name of the property you just added you need to update the webpart as well.
|
221,320 |
<p>For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?</p>
<pre>
1. somecoolclass.rb
2. some_cool_class.rb
3. some-cool-class.rb
4. SomeCoolClass.rb
</pre>
<p>or some other variation?</p>
<p>I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.</p>
|
[
{
"answer_id": 221391,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 7,
"selected": true,
"text": "<p>With just <a href=\"http://www.ruby-lang.org\" rel=\"noreferrer\">Ruby</a> (i.e. not Rails), naming is only a convention. In <a href=\"http://rubyonrails.org\" rel=\"noreferrer\">Rails</a> the <a href=\"http://itsignals.cascadia.com.au/?p=7\" rel=\"noreferrer\">convention</a> of using underscores is necessary (almost).</p>\n\n<p>I think convention #2 <code>lowercase_and_underscore.rb</code> is more common and looks pretty good, though an article <a href=\"http://rails.learnhub.com/lesson/page/5028-ruby-coding-convention\" rel=\"noreferrer\">Here</a> says <code>lowercasenounderscore.rb</code> is the Ruby convention.</p>\n\n<p><strong>Pick either</strong> which ever convention is more common or which ever one you like more. The most important thing is to <strong>be consistent within a project</strong>.</p>\n"
},
{
"answer_id": 221471,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 3,
"selected": false,
"text": "<p>I would recommend lower case characters with underscores (number 2 in your question). It's true that this naming scheme is the convention in Rails and not necessary in non-Rails projects. However, I would still stick to the Rails convention because most Ruby programmers are probably using Ruby exclusively for Rails anyway.</p>\n"
},
{
"answer_id": 222178,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 3,
"selected": false,
"text": "<p>I personally think the hyphen as word separator makes for maximum readability and typability in general, so I recommend that where possible (in some contexts, a hyphen can't be used, such as in identifiers in most languages). One important thing to bear in mind is that the scheme you pick will have a bearing on the require statement that users will use with your lib, and you want to <strong>avoid having a different gem name than library name</strong>.</p>\n\nBad\n\n<pre><code># gem install my_cool_lib\nrequire 'my-cool-lib'\n\n# gem install MyCoolLib\nrequire 'my_cool_lib'\n</code></pre>\n\nGood\n\n<pre><code># gem install my_cool_lib\nrequire 'my_cool_lib'\n\n# gem install my-cool-lib\nrequire 'my-cool-lib'\n</code></pre>\n\n<p>Unfortunately, a small handful of libraries violate this simple usability rule. Don't be one of those libraries. :)</p>\n"
},
{
"answer_id": 15222302,
"author": "Mike",
"author_id": 57481,
"author_profile": "https://Stackoverflow.com/users/57481",
"pm_score": 3,
"selected": false,
"text": "<pre><code>my-proj\n├── README\n├── lib\n│ └── some_cool_class.rb\n└── test\n └── some_cool_class_test.rb\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?
```
1. somecoolclass.rb
2. some_cool_class.rb
3. some-cool-class.rb
4. SomeCoolClass.rb
```
or some other variation?
I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.
|
With just [Ruby](http://www.ruby-lang.org) (i.e. not Rails), naming is only a convention. In [Rails](http://rubyonrails.org) the [convention](http://itsignals.cascadia.com.au/?p=7) of using underscores is necessary (almost).
I think convention #2 `lowercase_and_underscore.rb` is more common and looks pretty good, though an article [Here](http://rails.learnhub.com/lesson/page/5028-ruby-coding-convention) says `lowercasenounderscore.rb` is the Ruby convention.
**Pick either** which ever convention is more common or which ever one you like more. The most important thing is to **be consistent within a project**.
|
221,339 |
<p><a href="http://github.com/orestis/pysmell/tree/master" rel="noreferrer">PySmell</a> seems like a good starting point.</p>
<p>I think it should be possible, PySmell's <code>idehelper.py</code> does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.</p>
<pre><code>>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
</code></pre>
<p>It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)</p>
<hr>
<p>Progressing! I have the utter-basics of completion in place - barely works, but it's close..</p>
<p>I ran <code>python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS</code></p>
<p>Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"</p>
<pre><code>#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
</code></pre>
<p>Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!</p>
<p>As I said, it's entirely a work-in-progress, so don't use it yet..</p>
<hr>
<p><em>Last update:</em></p>
<p>orestis has integrated this into the PySmell project's code! Any further fiddling will happen <a href="http://github.com/orestis/pysmell/tree/master" rel="noreferrer">on github</a></p>
|
[
{
"answer_id": 221609,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't exactly what you're looking for but it might be able to get you started:</p>\n\n<p><a href=\"http://code.djangoproject.com/wiki/TextMate\" rel=\"nofollow noreferrer\">Using TextMate with Django</a></p>\n\n<p>They appear to be somewhat Django specific but some snippets may assist with your needs. You also may be able to build on top of that with PySmells.</p>\n"
},
{
"answer_id": 223862,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<p>In TextMate PHP has a simple auto-completion in form of hardcoded set of function names. Sounds as ugly as PHP, but in practice it's good enough to be useful.</p>\n"
},
{
"answer_id": 248819,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 4,
"selected": true,
"text": "<p>EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose.</p>\n\n<p>You can grab it here: <a href=\"http://github.com/orestis/pysmell/tree/master\" rel=\"nofollow noreferrer\">http://github.com/orestis/pysmell/tree/master</a> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <a href=\"http://code.google.com/p/pysmell/\" rel=\"nofollow noreferrer\">http://code.google.com/p/pysmell/</a></p>\n\n<p>--</p>\n\n<p>Hi, I'm the developer of PySmell. I also use a Mac, so if you can send me an email (contact info is in the source code) with your progress so far, I can try to integrate it :)</p>\n\n<p>Oh BTW it's called PySmell - no trailing 's' :)</p>\n"
},
{
"answer_id": 428145,
"author": "ohnoes",
"author_id": 53330,
"author_profile": "https://Stackoverflow.com/users/53330",
"pm_score": 1,
"selected": false,
"text": "<p>It's not perfect, but you can give it a try: <a href=\"http://mtod.org/tempy\" rel=\"nofollow noreferrer\">http://mtod.org/tempy</a></p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
[PySmell](http://github.com/orestis/pysmell/tree/master) seems like a good starting point.
I think it should be possible, PySmell's `idehelper.py` does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.
```
>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
```
It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)
---
Progressing! I have the utter-basics of completion in place - barely works, but it's close..
I ran `python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS`
Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"
```
#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
```
Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!
As I said, it's entirely a work-in-progress, so don't use it yet..
---
*Last update:*
orestis has integrated this into the PySmell project's code! Any further fiddling will happen [on github](http://github.com/orestis/pysmell/tree/master)
|
EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose.
You can grab it here: <http://github.com/orestis/pysmell/tree/master> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <http://code.google.com/p/pysmell/>
--
Hi, I'm the developer of PySmell. I also use a Mac, so if you can send me an email (contact info is in the source code) with your progress so far, I can try to integrate it :)
Oh BTW it's called PySmell - no trailing 's' :)
|
221,345 |
<p>I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data...</p>
<pre><code>System.Drawing.Image image = System.Drawing.Image.FromFile("filePath");
</code></pre>
<p>Im quite new to image manipulation but this is fine for getting simple values like width, height, aspect ratio etc but what I cannot work out is how to retrieve the physical file size of the jpg expressed in bytes. Any help would be much appreciated.</p>
<p>Thanks</p>
<p>Final solution including an MD5 hash of the image for later comparison</p>
<pre><code>System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
if (image != null)
{
int width = image.Width;
int height = image.Height;
decimal aspectRatio = width > height ? decimal.divide(width, height) : decimal.divide(height, width);
int fileSize = (int)new System.IO.FileInfo(filePath).Length;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(fileSize))
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] imageBytes = stream.GetBuffer();
System.Security.Cryptography.MD5CryptoServiceProvider provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
Byte[] hash = provider.ComputeHash(imageBytes);
System.Text.StringBuilder hashBuilder = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
hashBuilder.Append(hash[i].ToString("X2"));
}
string md5 = hashBuilder.ToString();
}
image.Dispose();
}
</code></pre>
|
[
{
"answer_id": 221348,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 7,
"selected": true,
"text": "<p>If you get your image directly from file, you can use the following code to get size of original file in bytes. </p>\n\n<pre><code> var fileLength = new FileInfo(filePath).Length; \n</code></pre>\n\n<p>If you get your image from other source, like getting one bitmap and composing it with other image, like adding watermark you will have to calculate size in run-time. You can't just use original file size, because compressing may lead to different size of output data after modification. In this case, you can use MemoryStream to save image to:</p>\n\n<pre><code>long jpegByteSize;\nusing (var ms = new MemoryStream(estimatedLength)) // estimatedLength can be original fileLength\n{\n image.Save(ms, ImageFormat.Jpeg); // save image to stream in Jpeg format\n jpegByteSize = ms.Length;\n }\n</code></pre>\n"
},
{
"answer_id": 221353,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 1,
"selected": false,
"text": "<p><code>System.Drawing.Image</code> won't give you the file length of size. You have to use another library for that. </p>\n\n<pre><code>int len = (new System.IO.FileInfo(sFullPath)).Length;\n</code></pre>\n"
},
{
"answer_id": 221363,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't have the original file, the file size is not clear as it depends on the image format and quality. So what you'd have to do is write the image to a stream (e.g. MemoryStream) and then use the stream's size.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12918/"
] |
I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data...
```
System.Drawing.Image image = System.Drawing.Image.FromFile("filePath");
```
Im quite new to image manipulation but this is fine for getting simple values like width, height, aspect ratio etc but what I cannot work out is how to retrieve the physical file size of the jpg expressed in bytes. Any help would be much appreciated.
Thanks
Final solution including an MD5 hash of the image for later comparison
```
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
if (image != null)
{
int width = image.Width;
int height = image.Height;
decimal aspectRatio = width > height ? decimal.divide(width, height) : decimal.divide(height, width);
int fileSize = (int)new System.IO.FileInfo(filePath).Length;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(fileSize))
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] imageBytes = stream.GetBuffer();
System.Security.Cryptography.MD5CryptoServiceProvider provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
Byte[] hash = provider.ComputeHash(imageBytes);
System.Text.StringBuilder hashBuilder = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
hashBuilder.Append(hash[i].ToString("X2"));
}
string md5 = hashBuilder.ToString();
}
image.Dispose();
}
```
|
If you get your image directly from file, you can use the following code to get size of original file in bytes.
```
var fileLength = new FileInfo(filePath).Length;
```
If you get your image from other source, like getting one bitmap and composing it with other image, like adding watermark you will have to calculate size in run-time. You can't just use original file size, because compressing may lead to different size of output data after modification. In this case, you can use MemoryStream to save image to:
```
long jpegByteSize;
using (var ms = new MemoryStream(estimatedLength)) // estimatedLength can be original fileLength
{
image.Save(ms, ImageFormat.Jpeg); // save image to stream in Jpeg format
jpegByteSize = ms.Length;
}
```
|
221,346 |
<p>What is the arrow operator (<code>-></code>) a synonym for?</p>
|
[
{
"answer_id": 221351,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "<p>The following two expressions are equivalent:</p>\n\n<pre><code>a->b\n\n(*a).b\n</code></pre>\n\n<p>(subject to operator overloading, as Konrad mentions, but that's unusual).</p>\n"
},
{
"answer_id": 221354,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p><code>a->b</code> is generally a synonym for <code>(*a).b</code>. The parenthesises here are necessary because of the binding strength of the operators <code>*</code> and <code>.</code>: <code>*a.b</code> wouldn't work because <code>.</code> binds stronger and is executed first. This is thus equivalent to <code>*(a.b)</code>.</p>\n\n<p>Beware of overloading, though: Since both <code>-></code> and <code>*</code> can be overloaded, their meaning can differ drastically.</p>\n"
},
{
"answer_id": 221359,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 4,
"selected": false,
"text": "<p>I mostly read it right-to-left and call \"in\"</p>\n\n<pre><code>foo->bar->baz = qux->croak\n</code></pre>\n\n<p>becomes:</p>\n\n<p>\"baz in bar in foo becomes croak in qux.\"</p>\n"
},
{
"answer_id": 221367,
"author": "P-A",
"author_id": 4975,
"author_profile": "https://Stackoverflow.com/users/4975",
"pm_score": 6,
"selected": false,
"text": "<p>The C++-language defines the arrow operator (<code>-></code>) as a synonym for dereferencing a pointer and then use the <code>.</code>-operator on that address.</p>\n\n<p>For example:</p>\n\n<p>If you have a an object, <code>anObject</code>, and a pointer, <code>aPointer</code>:</p>\n\n<pre><code>SomeClass anObject = new SomeClass();\nSomeClass *aPointer = &anObject;\n</code></pre>\n\n<p>To be able to use one of the objects methods you dereference the pointer and do a method call on that address:</p>\n\n<pre><code>(*aPointer).method();\n</code></pre>\n\n<p>Which could be written with the arrow operator:</p>\n\n<pre><code>aPointer->method();\n</code></pre>\n\n<p>The main reason of the existents of the arrow operator is that it shortens the typing of a very common task and it also kind of easy to forgot the parentheses around the dereferencing of the pointer. If you forgot the parentheses the .-operator will bind stronger then *-operator and make our example execute as:</p>\n\n<pre><code>*(aPointer.method()); // Not our intention!\n</code></pre>\n\n<p>Some of the other answer have also mention both that C++ operators can be overload and that it is not that common.</p>\n"
},
{
"answer_id": 4113619,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "<p>In C++0x, the operator gets a second meaning, indicating the return type of a function or lambda expression</p>\n\n<pre><code>auto f() -> int; // \"->\" means \"returns ...\"\n</code></pre>\n"
},
{
"answer_id": 55063340,
"author": "Tryb Ghost",
"author_id": 11056439,
"author_profile": "https://Stackoverflow.com/users/11056439",
"pm_score": 2,
"selected": false,
"text": "<p><code>-></code> is used when accessing data which you've got a pointer to. </p>\n\n<p>For example, you could create a pointer ptr to variable of type int intVar like this:</p>\n\n<pre><code>int* prt = &intVar;\n</code></pre>\n\n<p>You could then use a function, such as foo, on it only by dereferencing that pointer - to call the function on the variable which the pointer points to, rather than on the numeric value of the memory location of that variable:</p>\n\n<pre><code>(*ptr).foo();\n</code></pre>\n\n<p>Without the parentheses here, the compiler would understand this as <code>*(ptr.foo())</code> due to operator precedence which isn't what we want.</p>\n\n<p>This is actually just the same as typing</p>\n\n<pre><code>ptr->foo();\n</code></pre>\n\n<p>As the <code>-></code>dereferences that pointer, and so calls the function <code>foo()</code> on the variable which the pointer is pointing to for us.</p>\n\n<p>Similarly, we can use <code>-></code> to access or set a member of a class:</p>\n\n<pre><code>myClass* ptr = &myClassMember;\nptr->myClassVar = 2; \n</code></pre>\n"
},
{
"answer_id": 56032844,
"author": "Zhang",
"author_id": 9250490,
"author_profile": "https://Stackoverflow.com/users/9250490",
"pm_score": 0,
"selected": false,
"text": "<p>You can use -> to define a function.</p>\n\n<pre><code>auto fun() -> int\n{\nreturn 100;\n}\n</code></pre>\n\n<p>It's not a lambda. It's really a function. \"->\" indicates the return type of the function.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4975/"
] |
What is the arrow operator (`->`) a synonym for?
|
The following two expressions are equivalent:
```
a->b
(*a).b
```
(subject to operator overloading, as Konrad mentions, but that's unusual).
|
221,365 |
<p>If I have a folder structure set up like this:</p>
<pre><code>~/Projects
emacs
package1
package1-helpers
package2
package2-helpers
package2-more-helpers
package3
package3-helpers
</code></pre>
<p>How do I add these folders:</p>
<ul>
<li>~/Projects/emacs</li>
<li>~/Projects/emacs/package1</li>
<li>~/Projects/emacs/package2</li>
<li>~/Projects/emacs/package3</li>
</ul>
<p>...to the <code>load-path</code> from my .emacs file?</p>
<p>I basically need a short automated version of this code:</p>
<pre><code>(add-to-list 'load-path "~/Projects/emacs")
(add-to-list 'load-path "~/Projects/emacs/package1")
(add-to-list 'load-path "~/Projects/emacs/package2")
(add-to-list 'load-path "~/Projects/emacs/package3")
</code></pre>
|
[
{
"answer_id": 221449,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 5,
"selected": true,
"text": "<pre><code>(let ((base \"~/Projects/emacs\"))\n (add-to-list 'load-path base)\n (dolist (f (directory-files base))\n (let ((name (concat base \"/\" f)))\n (when (and (file-directory-p name) \n (not (equal f \"..\"))\n (not (equal f \".\")))\n (add-to-list 'load-path name)))))\n</code></pre>\n"
},
{
"answer_id": 222122,
"author": "link0ff",
"author_id": 23952,
"author_profile": "https://Stackoverflow.com/users/23952",
"pm_score": 3,
"selected": false,
"text": "<p>I suggest you to use <a href=\"http://www.panix.com/~tehom/my-code/how-to-use-subdirs-el.txt\" rel=\"noreferrer\">subdirs.el</a></p>\n"
},
{
"answer_id": 702280,
"author": "Nicholas Riley",
"author_id": 6372,
"author_profile": "https://Stackoverflow.com/users/6372",
"pm_score": 3,
"selected": false,
"text": "<p>Here's something I use in my .emacs:</p>\n\n<pre><code>(let* ((my-lisp-dir \"~/.elisp/\")\n (default-directory my-lisp-dir)\n (orig-load-path load-path))\n (setq load-path (cons my-lisp-dir nil))\n (normal-top-level-add-subdirs-to-load-path)\n (nconc load-path orig-load-path))\n</code></pre>\n\n<p>If you look at the description for normal-top-level-add-subdirs-to-load-path, it's somewhat smart about picking which directories to exclude.</p>\n"
},
{
"answer_id": 1515968,
"author": "Sujoy",
"author_id": 67373,
"author_profile": "https://Stackoverflow.com/users/67373",
"pm_score": 2,
"selected": false,
"text": "<p>This is my hacked up version :P</p>\n\n<pre><code>(defun add-to-list-with-subdirs (base exclude-list include-list)\n (dolist (f (directory-files base))\n (let ((name (concat base \"/\" f)))\n (when (and (file-directory-p name)\n (not (member f exclude-list)))\n (add-to-list 'load-path name)\n (when (member f include-list)\n (add-to-list-with-subdirs name exclude-list include-list)))))\n (add-to-list 'load-path base))\n</code></pre>\n\n<p>This will add all first level dirs from base and exclude the ones in exclude-list, while for the dirs in include-list, it will add all the first level dirs of that dir too.</p>\n\n<pre><code>(add-to-list-with-subdirs \"~/.emacs.d\" '(\".\" \"..\" \"backup\") '(\"vendor\" \"my-lisp\"))\n</code></pre>\n"
},
{
"answer_id": 26030360,
"author": "El Queso Grande",
"author_id": 4077571,
"author_profile": "https://Stackoverflow.com/users/4077571",
"pm_score": 1,
"selected": false,
"text": "<p>This function will map over first level sub-folders and files in BASE-PATH and add it to the LOAD-LIST if it's a directory (excluding directories \".\" and \"..\").</p>\n\n<pre><code>(defun add-subdirs-to-load-path (base-path)\n \"Adds first level subfolders to LOAD-PATH.\nBASE-PATH must not end with a '/'\"\n (mapc (lambda (attr)\n (let ((name (car attr))\n (folder-p (cadr attr)))\n (unless (or (not folder-p)\n (equal name \".\")\n (equal name \"..\"))\n (add-to-list 'load-path (concat base-path \"/\" name)))))\n (directory-files-and-attributes base-path)))\n</code></pre>\n"
},
{
"answer_id": 28685837,
"author": "Mirzhan Irkegulov",
"author_id": 596361,
"author_profile": "https://Stackoverflow.com/users/596361",
"pm_score": 1,
"selected": false,
"text": "<p>Install <a href=\"https://github.com/magnars/dash.el\" rel=\"nofollow\"><strong><code>dash</code></strong></a> and <a href=\"https://github.com/rejeep/f.el\" rel=\"nofollow\"><strong><code>f</code></strong></a> third-party libraries. Your needed function is <a href=\"https://github.com/rejeep/f.el#f-directories-path-optional-fn-recursive\" rel=\"nofollow\"><code>f-directories</code></a>:</p>\n\n<pre><code>(f-directories \"~/YOURDIR\") ; return only immediate directories\n(f-directories \"~/YOURDIR\" nil t) ; all directories recursively\n</code></pre>\n\n<p>Then use <a href=\"https://github.com/magnars/dash.el#-each-list-fn\" rel=\"nofollow\"><code>--each</code></a> to add each found directory to <code>load-path</code>. This whole operation works in O(n²), but as <code>load-path</code> is usually super-small, who cares.</p>\n\n<pre><code>(add-to-list 'load-path \"~/YOURDIR\") ; your parent folder itself\n(--each (f-directories \"~/YOURDIR\") (add-to-list 'load-path it))\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712/"
] |
If I have a folder structure set up like this:
```
~/Projects
emacs
package1
package1-helpers
package2
package2-helpers
package2-more-helpers
package3
package3-helpers
```
How do I add these folders:
* ~/Projects/emacs
* ~/Projects/emacs/package1
* ~/Projects/emacs/package2
* ~/Projects/emacs/package3
...to the `load-path` from my .emacs file?
I basically need a short automated version of this code:
```
(add-to-list 'load-path "~/Projects/emacs")
(add-to-list 'load-path "~/Projects/emacs/package1")
(add-to-list 'load-path "~/Projects/emacs/package2")
(add-to-list 'load-path "~/Projects/emacs/package3")
```
|
```
(let ((base "~/Projects/emacs"))
(add-to-list 'load-path base)
(dolist (f (directory-files base))
(let ((name (concat base "/" f)))
(when (and (file-directory-p name)
(not (equal f ".."))
(not (equal f ".")))
(add-to-list 'load-path name)))))
```
|
221,370 |
<p>Is there an easy way with LINQ to flatten an XML file?</p>
<p>I can see a number of ways with XSLT but wondered what the best option with LINQ would be?</p>
<p>I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this </p>
<p>nodeA </p>
<p>--nodeA1 </p>
<p>--nodeA2 </p>
<p>NodeB </p>
<p>I want to end up with </p>
<p>nodeA </p>
<p>nodeA1</p>
<p>nodeA2 </p>
<p>NodeB</p>
|
[
{
"answer_id": 221377,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "<p>OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string xml = @\"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>\";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nXmlDocument clone = new XmlDocument();\nXmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement(\"xml\"));\nforeach(XmlElement el in doc.SelectNodes(\"//*\")) {\n root.AppendChild(clone.ImportNode(el, false));\n}\nConsole.WriteLine(clone.OuterXml);\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code><xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>\n</code></pre>\n\n<hr>\n\n<p>[was]\nCare to define \"flatten\" in this context? i.e. \"before\" and \"after\"?\nXDocument has Descendants() and DescendantNodes() which might do the job...</p>\n"
},
{
"answer_id": 265959,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>The last part of what Marc said is what I think you're looking for. Here is an example that you can drop into <a href=\"http://www.linqpad.net/\" rel=\"nofollow noreferrer\">LINQPad</a> and see the results of the \"flatten.\"</p>\n\n<pre><code>string xml = @\"<xml><nodeA><nodeA1><inner1/><inner2/></nodeA1><nodeA2/></nodeA><NodeB/></xml>\";\n\nXDocument doc = XDocument.Parse(xml);\n\ndoc.Dump();\ndoc.Root.Descendants().Dump();\ndoc.Descendants().Dump();\ndoc.Root.Descendants().Count().Dump();\ndoc.Descendants().Count().Dump();\n</code></pre>\n"
},
{
"answer_id": 7185227,
"author": "ehosca",
"author_id": 199771,
"author_profile": "https://Stackoverflow.com/users/199771",
"pm_score": 1,
"selected": false,
"text": "<p>using an extension method this is really easy to do : </p>\n\n<pre><code>public static class XElementExtensions\n{\n public static string Path(this XElement xElement)\n {\n return PathInternal(xElement);\n }\n\n private static string PathInternal(XElement xElement)\n {\n if (xElement.Parent != null)\n return string.Concat(PathInternal(xElement.Parent), \".\", xElement.Name.LocalName);\n\n return xElement.Name.LocalName;\n }\n}\n</code></pre>\n\n<p>then : </p>\n\n<pre><code>private static void Main()\n{\n string sb =@\"<xml>\n <nodeA>\n <nodeA1>\n <inner1/><inner2/>\n </nodeA1>\n <nodeA2/>\n </nodeA>\n <NodeB/>\n </xml>\";\n\n XDocument xDoc = XDocument.Parse(sb);\n\n var result = xDoc.Root.Descendants()\n .Select(r => new {Path = r.Path()});\n\n foreach (var p in result)\n Console.WriteLine(p.Path);\n}\n</code></pre>\n\n<p>results in : </p>\n\n<pre><code>xml.nodeA\nxml.nodeA.nodeA1\nxml.nodeA.nodeA1.inner1\nxml.nodeA.nodeA1.inner2\nxml.nodeA.nodeA2\nxml.NodeB\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
Is there an easy way with LINQ to flatten an XML file?
I can see a number of ways with XSLT but wondered what the best option with LINQ would be?
I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this
nodeA
--nodeA1
--nodeA2
NodeB
I want to end up with
nodeA
nodeA1
nodeA2
NodeB
|
OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:
```cs
string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlDocument clone = new XmlDocument();
XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
foreach(XmlElement el in doc.SelectNodes("//*")) {
root.AppendChild(clone.ImportNode(el, false));
}
Console.WriteLine(clone.OuterXml);
```
Outputs:
```
<xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
```
---
[was]
Care to define "flatten" in this context? i.e. "before" and "after"?
XDocument has Descendants() and DescendantNodes() which might do the job...
|
221,376 |
<p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="noreferrer">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
|
[
{
"answer_id": 221380,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "<p>The copyright symbol in ASCII is spelled <code>(c)</code> or \"<code>Copyright</code>\".</p>\n\n<p>See circular 61, <a href=\"http://www.copyright.gov/circs/circ61.pdf\" rel=\"noreferrer\">Copyright Registration for Computer Programs</a>. </p>\n\n<p>While it's true that the legal formalism (see Circular 1, <a href=\"http://www.copyright.gov/circs/circ01.pdf\" rel=\"noreferrer\">Copyright Basics</a>) is </p>\n\n<blockquote>\n <p>The symbol © (the letter C in a\n circle), or the word “Copyright,” or\n the abbreviation “Copr.”; and...</p>\n</blockquote>\n\n<p>And it's also true that</p>\n\n<blockquote>\n <p>To guarantee protection for a\n copyrighted work in all UCC member\n countries, the notice must consist of\n the symbol © (the word “Copyright” or\n the abbreviation is not acceptable)</p>\n</blockquote>\n\n<p>You can dig through circular <a href=\"http://www.copyright.gov/circs/circ03.html\" rel=\"noreferrer\">3</a> and <a href=\"http://www.copyright.gov/circs/circ38a.html\" rel=\"noreferrer\">38a</a>.</p>\n\n<p>This has, however, already been tested in court. It isn't an interesting issue. If you do a search for \"(c) acceptable for c-in-a-circle\", you'll find that lawyers all agree that (c) is an acceptable substitute. See Perle and Williams. See Scott on Information Technology Law.</p>\n"
},
{
"answer_id": 221381,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 2,
"selected": false,
"text": "<p>You can always revert to good old (c)</p>\n"
},
{
"answer_id": 221543,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 2,
"selected": false,
"text": "<p>Waiting for <a href=\"http://docs.python.org/dev/3.0/whatsnew/3.0.html\" rel=\"nofollow noreferrer\">Python 3k</a>, where the default encoding of the source will be UTF-8?</p>\n"
},
{
"answer_id": 221569,
"author": "rjmunro",
"author_id": 3408,
"author_profile": "https://Stackoverflow.com/users/3408",
"pm_score": 3,
"selected": false,
"text": "<p>Contrary to the accepted answer, AFAIK, (c) is not an officially recognized alternative to the copyright symbol, although I'm not sure it's been tested in court.</p>\n\n<p>However, © is just an abreviation of the word Copyright. Saying \"Copyright 2008 Robert Munro\" is identical to saying \"© 2008 Robert Munro\"</p>\n\n<p>Your \"Copyright: © 2008 etc.\" Expands to \"Copyright: Copyright 2008 etc.\"</p>\n\n<p>Wikipedia's page seems to agree with me <a href=\"http://en.wikipedia.org/wiki/Copyright_symbol\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Copyright_symbol</a></p>\n\n<p>In the United States, the copyright notice consists of three elements:\n 1. the © symbol, <strong>or</strong> the word \"Copyright\" or abbreviation \"Copr.\";\n...</p>\n"
},
{
"answer_id": 1235665,
"author": "A. L. Flanagan",
"author_id": 132510,
"author_profile": "https://Stackoverflow.com/users/132510",
"pm_score": 2,
"selected": false,
"text": "<p>For Python 2, the \"right\" thing to do is to specify the encoding, or never use non-ASCII characters. Specifying the encoding makes it simpler on the compiler and on humans. Sorry, but Python originally specified ASCII as the default, back in the Dark Ages.</p>\n\n<p>For Python 3, UTF-8 is the default encoding, so you should be fine. In that case I would recommend not specifying the encoding if you use the default.</p>\n\n<p>Whether a language allows/requires an encoding specification or not, in the age of Unicode this is an issue we need to keep in mind for every \"text\" file.</p>\n"
},
{
"answer_id": 19210542,
"author": "sergio",
"author_id": 2852044,
"author_profile": "https://Stackoverflow.com/users/2852044",
"pm_score": 3,
"selected": false,
"text": "<p>Put this line at first:</p>\n\n<pre><code># -*- coding: utf-8 -*-\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11677/"
] |
I need to include a copyright statement at the top of every Python source file I produce:
```
# Copyright: © 2008 etc.
```
However, when I then run such a file I get this message:
SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <http://www.python.org/peps/pep-0263.html> for details.
Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:
```
# -*- coding: iso-8859-1 -*-
```
to tell Python I'm using Latin encoding, or I can change the copyright statement to:
```
# Copyright: \xa9 2008 etc.
```
which just possibly doesn't have the same legal standing.
Is there a more elegant solution?
|
The copyright symbol in ASCII is spelled `(c)` or "`Copyright`".
See circular 61, [Copyright Registration for Computer Programs](http://www.copyright.gov/circs/circ61.pdf).
While it's true that the legal formalism (see Circular 1, [Copyright Basics](http://www.copyright.gov/circs/circ01.pdf)) is
>
> The symbol © (the letter C in a
> circle), or the word “Copyright,” or
> the abbreviation “Copr.”; and...
>
>
>
And it's also true that
>
> To guarantee protection for a
> copyrighted work in all UCC member
> countries, the notice must consist of
> the symbol © (the word “Copyright” or
> the abbreviation is not acceptable)
>
>
>
You can dig through circular [3](http://www.copyright.gov/circs/circ03.html) and [38a](http://www.copyright.gov/circs/circ38a.html).
This has, however, already been tested in court. It isn't an interesting issue. If you do a search for "(c) acceptable for c-in-a-circle", you'll find that lawyers all agree that (c) is an acceptable substitute. See Perle and Williams. See Scott on Information Technology Law.
|
221,378 |
<p>I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways... </p>
<p>Suppose I have a string containing the XML....</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<root>
<Element1>
<Element1_1>
SomeData
</Element1_1>
</Element1>
<Element2>
Some More Data
</Element2>
</root>
</code></pre>
<p><strong>What is the simplest (most readable) way of removing Element1_1?</strong></p>
<p>Update... I can use any .Net API available in .Net 3.5 :D </p>
|
[
{
"answer_id": 221383,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so, <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx\" rel=\"noreferrer\">XNode.Remove</a> is your friend - just select Element1_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.</p>\n\n<p>Examples of how to select the element:</p>\n\n<pre><code>XElement element = doc.XPathSelectElement(\"/root/Element1/Element1_1\");\nelement.Remove();\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>XElement element = doc.Descendants(\"Element1_1\").Single().Remove();\n</code></pre>\n"
},
{
"answer_id": 221403,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>I'd use either this:</p>\n\n<pre><code>XmlDocument x = new XmlDocument();\nx.LoadXml(SomeXmlString);\n\nforeach (XmlNode xn in x.SelectNodes(\"//Element1_1\"))\n xn.ParentNode.RemoveChild(xn);\n</code></pre>\n\n<p>or the same with an explicit XPath:</p>\n\n<pre><code>foreach (XmlNode xn in x.SelectNodes(\"/root/Element1/Element1_1\"))\n xn.ParentNode.RemoveChild(xn);\n</code></pre>\n\n<p>or, even more specific:</p>\n\n<pre><code>XmlNode xn = x.SelectSingleNode(\"/root/Element1/Element1_1\");\nxn.ParentNode.RemoveChild(xn);\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways...
Suppose I have a string containing the XML....
```
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Element1>
<Element1_1>
SomeData
</Element1_1>
</Element1>
<Element2>
Some More Data
</Element2>
</root>
```
**What is the simplest (most readable) way of removing Element1\_1?**
Update... I can use any .Net API available in .Net 3.5 :D
|
Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so, [XNode.Remove](http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx) is your friend - just select Element1\_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.
Examples of how to select the element:
```
XElement element = doc.XPathSelectElement("/root/Element1/Element1_1");
element.Remove();
```
Or:
```
XElement element = doc.Descendants("Element1_1").Single().Remove();
```
|
221,385 |
<p>Has anyone gotten the jquery plugin <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> to run properly in a Rails applications. If so, could you share some hints on how to set it up? I'm having some trouble with creating the "submit-url".</p>
<hr>
<p>IIRC, you cannot simply call ruby code from within javascript (please let me be wrong:-). Do you mean RJS??? Isn't that limited to Prototype? I'm using jQuery.</p>
<hr>
<p><strong>UPDATE:</strong><br>
uh.....asked this a while back and in the meantime switched to a different solution. But IIRC my main issue was the following:</p>
<p>I'm using the RESTful resources. So let's say I have to model a blog and thus have the resource "posts". If I want to edit a post (e.g. the post with the ID 8), my update is sent via HTTP to the URL <a href="http://my.url.com/posts/8" rel="nofollow noreferrer">http://my.url.com/posts/8</a> with the HTTP verb POST. This URL however is constructed in my Rails code. So how would I get my submit-url into my jQuery code? Since this is RESTful code, my update URL will change with every post.</p>
|
[
{
"answer_id": 259187,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "<p>I\"m not sure I entirely understand the problem you're having, but I think you could put something like this in your javascript:</p>\n\n<pre><code><%= url_for(@post) %>\n</code></pre>\n\n<p>It depends how you're structuring your javascript, how you've got your files organised etc...</p>\n"
},
{
"answer_id": 259755,
"author": "Sebastian",
"author_id": 29909,
"author_profile": "https://Stackoverflow.com/users/29909",
"pm_score": 4,
"selected": true,
"text": "<p>Excuse me for bringing this up only now, but I just found the time to look into my code again. I think I solved my problem by the following javascript (my application.js within rails):</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n$(\".edit_textfield\").each( function(i) {\n $(this).editable(\"update\", {\n type : 'textarea',\n rows : 8,\n name : $(this).attr('name'),\n cancel : 'Cancel',\n submit : 'OK',\n indicator : \"<img src='../images/spinner.gif' />\",\n tooltip : 'Double-click to edit...'\n })\n });\n});\n</code></pre>\n\n<p>This works, if your Controller URLs are RESTful.</p>\n"
},
{
"answer_id": 259815,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 1,
"selected": false,
"text": "<p>If you're including .js files in your html then no, but if you have js inline in your view template then yes you can. </p>\n\n<p>You can also have .erb.js files, which are js views.</p>\n\n<p>Anything is possible :D</p>\n"
},
{
"answer_id": 551392,
"author": "Josh Rickard",
"author_id": 66675,
"author_profile": "https://Stackoverflow.com/users/66675",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how I wired up JEditable (1.6.2) with my restful Rails app (2.2.2):</p>\n\n<p><strong>Inline Form:</strong></p>\n\n<pre><code><div id=\"email_name\"><%= h( @email.name ) %></div>\n\n$('#email_name').editable( <%= email_path(@email).to_json %>, {\n name: 'email[name]',\n method: 'PUT',\n submitdata: {\n authenticity_token: <%= form_authenticity_token.to_json %>,\n wants: 'name'\n }\n});\n</code></pre>\n\n<p><strong>Controller:</strong></p>\n\n<pre><code>def update\n @email = Email.find( params[:id] )\n @email.update_attributes!( params[:email )\n respond_to do |format|\n format.js\n end\nend\n</code></pre>\n\n<p><strong>update.js.erb</strong></p>\n\n<pre><code><%=\n case params[:wants]\n when 'name' then h( @email.name )\n # add other attributes if you have more inline forms for this model\n else ''\n end\n%>\n</code></pre>\n\n<p>It is a bit clunky with that switch statement. It would be nice if JEditable would just save the submitted value by default if the ajax request was successful and nothing was returned.</p>\n"
},
{
"answer_id": 880976,
"author": "catalpa",
"author_id": 52211,
"author_profile": "https://Stackoverflow.com/users/52211",
"pm_score": 0,
"selected": false,
"text": "<p>If you're controllers are a little less than restful. Particularly if you have an action to update a specific field then this works as well. The key is passing the authentication token. </p>\n\n<p><em>index.html.erb</em></p>\n\n<pre><code><span id=\"my_edit\"><%= foo.bar %></span>\n\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#my_edit\").editable('<%= url_for(:action => \"update_bar\", \n :id => foo) %>',\n {\n method: 'PUT',\n cancel : 'Cancel',\n submit : 'OK',\n indicator : \"<img src='../images/spinner.gif' />\",\n tooltip : 'Double-click to edit...',\n submitdata: {\n authenticity_token: <%= form_authenticity_token.to_json %>,\n }\n }\n });\n</script>\n</code></pre>\n\n<p>Oversimplified controller that doesn't justify not being restful:</p>\n\n<p><em>foo_controller.rb</em></p>\n\n<pre><code>def update_bar\n foo = Foo.find(params[:id])\n bar= params[:value]\n // insert justifiable code here\n foo.save\n render :text=>params[:value]\nend\n</code></pre>\n\n<p>(Works with Rails 2.2.2 and 2.3.2 w/ Jeditable 1.7.0 and jRails 0.4, though jRails doesn't play much interaction here other than providing the includes for jQuery 1.5)</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29909/"
] |
Has anyone gotten the jquery plugin [jeditable](http://www.appelsiini.net/projects/jeditable) to run properly in a Rails applications. If so, could you share some hints on how to set it up? I'm having some trouble with creating the "submit-url".
---
IIRC, you cannot simply call ruby code from within javascript (please let me be wrong:-). Do you mean RJS??? Isn't that limited to Prototype? I'm using jQuery.
---
**UPDATE:**
uh.....asked this a while back and in the meantime switched to a different solution. But IIRC my main issue was the following:
I'm using the RESTful resources. So let's say I have to model a blog and thus have the resource "posts". If I want to edit a post (e.g. the post with the ID 8), my update is sent via HTTP to the URL <http://my.url.com/posts/8> with the HTTP verb POST. This URL however is constructed in my Rails code. So how would I get my submit-url into my jQuery code? Since this is RESTful code, my update URL will change with every post.
|
Excuse me for bringing this up only now, but I just found the time to look into my code again. I think I solved my problem by the following javascript (my application.js within rails):
```
jQuery(document).ready(function($) {
$(".edit_textfield").each( function(i) {
$(this).editable("update", {
type : 'textarea',
rows : 8,
name : $(this).attr('name'),
cancel : 'Cancel',
submit : 'OK',
indicator : "<img src='../images/spinner.gif' />",
tooltip : 'Double-click to edit...'
})
});
});
```
This works, if your Controller URLs are RESTful.
|
221,386 |
<p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
|
[
{
"answer_id": 221407,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>If two copies fit in memory, then you can easily make a copy. The second copy is the compressed version. Sure, you can use numpy, but you can also use the <a href=\"http://www.python.org/doc/2.5.2/lib/module-array.html\" rel=\"nofollow noreferrer\">array</a> package. Additionally, you can treat your big binary object as a string of bytes and manipulate it directly. </p>\n\n<p>It sounds like your file may be <em>REALLY</em> large, and you can't fit two copies into memory. (You didn't provide a lot of details, so this is just a guess.) You'll have to do your compression in chunks. You'll read in a chunk, do some processing on that chunk and write it out. Again, numpy, array or simple string of bytes will work fine.</p>\n"
},
{
"answer_id": 221696,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "<p>You need to make your question more precise. Do you know the values you want to trim ahead of time?</p>\n\n<p>Assuming you do, I would probably search for the matching sections using <code>subprocess</code> to run \"<code>fgrep -o -b <search string></code>\" and then change the relevant sections of the file using the python <code>file</code> object's <code>seek</code>, <code>read</code> and <code>write</code> methods.</p>\n"
},
{
"answer_id": 221851,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "<p>If you don't have the memory to do <code>open(\"big.file\").read()</code>, then numpy wont really help.. It uses the same memory as python variables do (if you have 1GB of RAM, you can only load 1GB of data into numpy)</p>\n\n<p>The solution is simple - read the file in chunks.. <code>f = open(\"big.file\", \"rb\")</code>, then do a series of <code>f.read(500)</code>, remove the sequence and write it back out to another file object. Pretty much how you do file reading/writing in C..</p>\n\n<p>The problem then is if you miss the pattern you are replacing.. For example:</p>\n\n<pre><code>target_seq = \"567\"\ninput_file = \"1234567890\"\n\ntarget_seq.read(5) # reads 12345, doesn't contain 567\ntarget_seq.read(5) # reads 67890, doesn't contain 567\n</code></pre>\n\n<p>The obvious solution is to start at the first character in the file, check <code>len(target_seq)</code> characters, then go forward one character, check forward again.</p>\n\n<p>For example (pseudo code!):</p>\n\n<pre><code>while cur_data != \"\":\n seek_start = 0\n chunk_size = len(target_seq)\n\n input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)\n cur_data = input_file.read(chunk_size) # reads 123\n if target_seq == cur_data:\n # Found it!\n out_file.write(\"replacement_string\")\n else:\n # not it, shove it in the new file\n out_file.write(cur_data)\n seek_start += 1\n</code></pre>\n\n<p>It's not exactly the most efficient way, but it will work, and not require keeping a copy of the file in memory (or two).</p>\n"
},
{
"answer_id": 1008370,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>dbr's solution is a good idea but a bit overly complicated all you really have to do is rewind the file pointer the length of the sequence you are searching for, before you read your next chunk.</p>\n\n<pre><code>def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):\n inputFile = open(inFilename, \"rb\")\n outputFile = open(outFilename, \"wb\")\n\n data = \"\"\n chunk = 1024\n\n while 1:\n data = inputFile.read(chunk)\n data = data.replace(oldSeq, newSeq)\n outputFile.write(data)\n\n inputFile.seek(-len(oldSequence), 1)\n outputFile.seek(-len(oldSequence), 1)\n\n if len(data) < chunk:\n break\n\n inputFile.close()\n outputFile.close()\n</code></pre>\n"
},
{
"answer_id": 1008461,
"author": "Kenan Banks",
"author_id": 43089,
"author_profile": "https://Stackoverflow.com/users/43089",
"pm_score": 0,
"selected": false,
"text": "<p>This generator-based version will keep exactly one character of the file content in memory at a time.</p>\n\n<p>Note that I am taking your question title quite literally - you want to reduce runs of the same <em>character</em> to a single character. For replacing patterns in general, this does not work:</p>\n\n<pre><code>import StringIO\n\ndef gen_chars(stream):\n while True:\n ch = stream.read(1)\n if ch: \n yield ch\n else:\n break\n\ndef gen_unique_chars(stream):\n lastchar = ''\n for char in gen_chars(stream):\n if char != lastchar:\n yield char\n lastchar=char\n\ndef remove_seq(infile, outfile):\n for ch in gen_unique_chars(infile):\n outfile.write(ch)\n\n# Represents a file open for reading\ninfile = StringIO.StringIO(\"1122233333444555\")\n\n# Represents a file open for writing\noutfile = StringIO.StringIO()\n\n# Will print \"12345\"\nremove_seq(infile, outfile)\noutfile.seek(0)\nprint outfile.read()\n</code></pre>\n"
},
{
"answer_id": 13611980,
"author": "edasx",
"author_id": 1086202,
"author_profile": "https://Stackoverflow.com/users/1086202",
"pm_score": 1,
"selected": false,
"text": "<p>AJMayorga suggestion is fine unless the sizes of the replacement strings are different. Or the replacement string is at the end of the chunk.</p>\n\n<p>I fixed it like this:</p>\n\n<pre><code>def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):\n inputFile = open(inFilename, \"rb\")\n outputFile = open(outFilename, \"wb\")\n\ndata = \"\"\nchunk = 1024\n\noldSeqLen = len(oldSeq)\n\nwhile 1:\n data = inputFile.read(chunk)\n\n dataSize = len(data)\n seekLen= dataSize - data.rfind(oldSeq) - oldSeqLen\n if seekLen > oldSeqLen:\n seekLen = oldSeqLen\n\n data = data.replace(oldSeq, newSeq)\n outputFile.write(data)\n inputFile.seek(-seekLen, 1) \n outputFile.seek(-seekLen, 1)\n\n if dataSize < chunk:\n break\n\ninputFile.close()\noutputFile.close()\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29908/"
] |
I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?
|
If you don't have the memory to do `open("big.file").read()`, then numpy wont really help.. It uses the same memory as python variables do (if you have 1GB of RAM, you can only load 1GB of data into numpy)
The solution is simple - read the file in chunks.. `f = open("big.file", "rb")`, then do a series of `f.read(500)`, remove the sequence and write it back out to another file object. Pretty much how you do file reading/writing in C..
The problem then is if you miss the pattern you are replacing.. For example:
```
target_seq = "567"
input_file = "1234567890"
target_seq.read(5) # reads 12345, doesn't contain 567
target_seq.read(5) # reads 67890, doesn't contain 567
```
The obvious solution is to start at the first character in the file, check `len(target_seq)` characters, then go forward one character, check forward again.
For example (pseudo code!):
```
while cur_data != "":
seek_start = 0
chunk_size = len(target_seq)
input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)
cur_data = input_file.read(chunk_size) # reads 123
if target_seq == cur_data:
# Found it!
out_file.write("replacement_string")
else:
# not it, shove it in the new file
out_file.write(cur_data)
seek_start += 1
```
It's not exactly the most efficient way, but it will work, and not require keeping a copy of the file in memory (or two).
|
221,387 |
<p>I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.</p>
|
[
{
"answer_id": 825415,
"author": "PypeBros",
"author_id": 15304,
"author_profile": "https://Stackoverflow.com/users/15304",
"pm_score": 2,
"selected": false,
"text": "<p>i used the code from ds_wifi_test (which comes with the original dswifi library) when i tried to implement this. Basically, access points are scanned internally when you invoke <code>Wifi_ScanMode()</code>. You can then have the number of AP identified with <code>Wifi_GetNumAP()</code> and retrieve the information for the ith access point with <code>Wifi_GetAPData(i,&data);</code></p>\n\n<pre><code>nbitems=Wifi_GetNumAP();\nWifi_AccessPoint ap;\n\nfor (int i=0;i<nbitems; i++) {\n if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)\n do_whatever_with(&ap);\n}\n</code></pre>\n\n<p>I'm not aware of any \"helper\" functions through the PALib in this regards. All the PALib seems to have is a few \"wrappers\" to ease common tasks once a WFC setting has been defined (<a href=\"http://www.palib.info/wiki/doku.php?id=day20\" rel=\"nofollow noreferrer\">see day#20 tutorial</a>)</p>\n"
},
{
"answer_id": 3515582,
"author": "Shotgun Ninja",
"author_id": 410342,
"author_profile": "https://Stackoverflow.com/users/410342",
"pm_score": 0,
"selected": false,
"text": "<p>If I were you, I'd steer clear of PALib. It's built atop an outdated version of libnds, and isn't updated with the new version in the interests of backwards-compatibility. Instead, take the time to learn libnds, and reap the benefits of a well-maintained library that doesn't have dependencies of its own. The same code that sylvainulg wrote above will still work, as it is dependant on dswifi, not libnds or PALib.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.
|
i used the code from ds\_wifi\_test (which comes with the original dswifi library) when i tried to implement this. Basically, access points are scanned internally when you invoke `Wifi_ScanMode()`. You can then have the number of AP identified with `Wifi_GetNumAP()` and retrieve the information for the ith access point with `Wifi_GetAPData(i,&data);`
```
nbitems=Wifi_GetNumAP();
Wifi_AccessPoint ap;
for (int i=0;i<nbitems; i++) {
if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)
do_whatever_with(&ap);
}
```
I'm not aware of any "helper" functions through the PALib in this regards. All the PALib seems to have is a few "wrappers" to ease common tasks once a WFC setting has been defined ([see day#20 tutorial](http://www.palib.info/wiki/doku.php?id=day20))
|
221,396 |
<p>Is it possible to call a function from PHP using <code>onsubmit</code> from JavaScript? If so could someone give me an example of how it would be done?</p>
<pre><code>function addOrder(){
$con = mysql_connect("localhost", "146687", "password");
if(!$con){
die('Could not connect: ' . mysql_error())
}
$sql = "INSERT INTO orders ((user, 1st row, 2nd row, 3rd row, 4th row)
VALUES ($session->username,1st variable, 2nd variable, 3rd variable, 4th variable))";
mysql_query($sql,$con)
if(mysql_query($sql,$con)){
echo "Your order has been added";
}else{
echo "There was an error adding your order to the databse: " . mysql_error();
}
}
</code></pre>
<p>That's the function I am wanting to call. Its an ordering system, you type in how much of each item you want, hit submit and it <em>should</em> add the order to the table.</p>
|
[
{
"answer_id": 221406,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you want <a href=\"http://en.wikipedia.org/wiki/AJAX\" rel=\"nofollow noreferrer\">AJAX</a>.</p>\n\n<p>This is too big a topic for a single answer, but that should get you going.</p>\n\n<p>Basically, the Javascript will send an HTTP request to a PHP script on your server and then do something with the response. <a href=\"http://json.org\" rel=\"nofollow noreferrer\">JSON</a> is probably something you'll want to learn about too.</p>\n"
},
{
"answer_id": 221435,
"author": "user29593",
"author_id": 29593,
"author_profile": "https://Stackoverflow.com/users/29593",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, another great and easy tutorial for learning ajax is:</p>\n\n<p><a href=\"http://24ways.org/2005/easy-ajax-with-prototype/\" rel=\"nofollow noreferrer\">http://24ways.org/2005/easy-ajax-with-prototype/</a></p>\n\n<p>Prototype is another thing I recommend if you havent gone to far with your project and need to revert a lot of functionality.</p>\n\n<p><a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 221563,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry, your question is too basic. Depending on <em>what</em> PHP function you want to call on formsubmit Ajax will not help you. Are you aware of the fundamental (clientside/serverside) differences between PHP and JavaScript?</p>\n"
},
{
"answer_id": 221601,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 2,
"selected": false,
"text": "<p>It's <strong>indirectly</strong> possible to call a PHP function using JavaScript. As other people have already mentioned, you're going to want to do some type of request - this doesn't necessarily have to be Ajax. It could be synchronous. Without knowing exactly what you're trying to accomplish, here's what I would suggest:</p>\n\n<ul>\n<li>Attach an event handler to the form's submit option (or use the standard submit if you're not going to use Ajax)</li>\n<li>Bundle up any parameters that will need to be passed to the PHP function either in a POST or in the query string of the address to the page.</li>\n<li>Fire the request (either asynchronously or via submit)</li>\n<li>In the PHP script that is the target of the request, pull out of the parameters from the $ _ POST or $ _ GET.</li>\n<li>Call the PHP function that you need with the parameters.</li>\n<li>Echo back the response and parse it as needed once the request completes.</li>\n</ul>\n\n<p>Again, this is a bit general but so is your question. Hopefully this gives some sort of direction.</p>\n"
},
{
"answer_id": 221602,
"author": "dragonmantank",
"author_id": 204,
"author_profile": "https://Stackoverflow.com/users/204",
"pm_score": 2,
"selected": false,
"text": "<p>The closest you are going to get will be <a href=\"http://xajaxproject.org/\" rel=\"nofollow noreferrer\">xajax</a> which will let you wrap a PHP function into an AJAX call. I've used it quite a bit before I started working with Zend Framework and found it too hard to implement in an OO way. </p>\n\n<p>With xajax you write a PHP function that does all of your regular logic and then returns a ObjectResponse object that manipulates the browser through AJAX (alert boxes, change HTML, CSS, etc). You register your function with xajax and then xajax will spit out some javascript into your HTML's section.</p>\n\n<p>In your HTML you just call that javascript function that xajax generated and it takes care of the rest through AJAX.</p>\n"
},
{
"answer_id": 221658,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 5,
"selected": true,
"text": "<h2>You can not call a PHP function from Javascript...</h2>\n\n<p>Javascript is a client language (it's executed on the Web browser, after receiving the web page) while PHP is on the server side (it's executed before the web page is rendered). You have no way to make one call another.</p>\n\n<h2>...but you can get the result of an external PHP script</h2>\n\n<p>There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.</p>\n\n<p>This process is what we call <a href=\"http://fr.wikipedia.org/wiki/Ajax\" rel=\"noreferrer\">AJAX</a>, and it's far easier to do it with a good tool than yourself. Have a look to <a href=\"http://www.jquery.info/\" rel=\"noreferrer\">JQuery</a>, it's powerful yet easy to use Javascript library that has built-in AJAX helpers.</p>\n\n<p>An example with JQuery (client side) :</p>\n\n<pre><code>$.ajax({\n type: \"POST\", // the request type. You most likely going to use POST\n url: \"your_php_script.php\", // the script path on the server side\n data: \"name=John&location=Boston\", // here you put you http param you want to be able to retrieve in $_POST \n success: function(msg) {\n alert( \"Data Saved: \" + msg ); // what you do once the request is completed\n }\n</code></pre>\n"
},
{
"answer_id": 221983,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 2,
"selected": false,
"text": "<p>You will want to do something like:</p>\n\n<pre><code><form action=\"add_order.php\" method=\"POST\" id=\"add_order_form\">\n<!-- all of your form fields -->\n<input type='submit' value='Add Order'>\n</form>\n\n<script type=\"text/javascript\">\n$(\"#add_order_form\").submit(function() {\n var action = $(\"#add_order_form\").attr(\"action\");\n var data = $(\"#add_order_form\").serialize();\n $.post(action, data, function(json, status) {\n if(status == 'success') {\n alert(json.message);\n } else {\n alert('Something went wrong.');\n }\n }, \"json\"); \n return false;\n});\n</script>\n</code></pre>\n\n<p>And then have a PHP file named <code>add_order.php</code> with something like:</p>\n\n<pre><code>$success = 0;\n$con = mysql_connect(\"localhost\", \"146687\", \"password\");\nif(!$con) {\n $message = 'Could not connect to the database.';\n} else {\n // SANITIZE DATA BEFORE INSERTING INTO DATABASE\n // LOOK INTO MYSQL_REAL_ESCAPE_STRING AT LEAST,\n // PREFERABLY INTO PREPARED STATEMENTS\n $query_ok = mysql_query(\"INSERT INTO `orders` ....\");\n if($query_ok) {\n $success = 1;\n $message = \"Order added.\";\n } else {\n $message = \"Unable to save information\";\n }\n}\n\nprint json_encode(array('success' => $success, 'message' => $message));\n</code></pre>\n\n<p>For this beauty to work you will have to go to the <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> website, download it, and include the jquery.js file.</p>\n\n<p>I haven't tested the above but it should work. Good luck.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29912/"
] |
Is it possible to call a function from PHP using `onsubmit` from JavaScript? If so could someone give me an example of how it would be done?
```
function addOrder(){
$con = mysql_connect("localhost", "146687", "password");
if(!$con){
die('Could not connect: ' . mysql_error())
}
$sql = "INSERT INTO orders ((user, 1st row, 2nd row, 3rd row, 4th row)
VALUES ($session->username,1st variable, 2nd variable, 3rd variable, 4th variable))";
mysql_query($sql,$con)
if(mysql_query($sql,$con)){
echo "Your order has been added";
}else{
echo "There was an error adding your order to the databse: " . mysql_error();
}
}
```
That's the function I am wanting to call. Its an ordering system, you type in how much of each item you want, hit submit and it *should* add the order to the table.
|
You can not call a PHP function from Javascript...
--------------------------------------------------
Javascript is a client language (it's executed on the Web browser, after receiving the web page) while PHP is on the server side (it's executed before the web page is rendered). You have no way to make one call another.
...but you can get the result of an external PHP script
-------------------------------------------------------
There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.
This process is what we call [AJAX](http://fr.wikipedia.org/wiki/Ajax), and it's far easier to do it with a good tool than yourself. Have a look to [JQuery](http://www.jquery.info/), it's powerful yet easy to use Javascript library that has built-in AJAX helpers.
An example with JQuery (client side) :
```
$.ajax({
type: "POST", // the request type. You most likely going to use POST
url: "your_php_script.php", // the script path on the server side
data: "name=John&location=Boston", // here you put you http param you want to be able to retrieve in $_POST
success: function(msg) {
alert( "Data Saved: " + msg ); // what you do once the request is completed
}
```
|
221,399 |
<p>I am using <strong>mysql (5.0.32-Debian_7etch6-log)</strong> and i've got a nightly running bulk load <strong>php (5.2.6)</strong> script <strong>(using Zend_DB (1.5.1)</strong> via PDO) which does the following:</p>
<ol>
<li>truncating a set of 4 'import' tables</li>
<li>bulk inserting data into these 4 'import' tables (re-using ids that have previously been in the tables as well, but i truncated the whole table, so that shouldn't be an issue, right?)</li>
<li>if everything goes well, rename the 'live' tables to 'temp', the 'import' tables to 'live' and then the 'temp' (old 'live') tables to 'import'</li>
</ol>
<p>This worked great for weeks. Now I am occassionally getting this, somewhere in the middle of the whole bulk loading process:</p>
<p><code>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '911' for key 1</code></p>
<p>Mind you that, this is not the first id that has been in the table before the truncation already. When I just start the script manually again, it works like a charm.</p>
<p>Any ideas? leftover indexes, something to do with the renaming maybe?</p>
<p>In addition, when I check the table for an entry with the id 911 afterwards, it is not even in there.</p>
|
[
{
"answer_id": 221421,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>Could some other script be inserting into the database while your import script is running?</p>\n"
},
{
"answer_id": 221429,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried enabling the query log to see if you really ARE inserting a duplicate?</p>\n\n<p>Can you reproduce it in your test environment? Do not enable the query log in production.</p>\n\n<p>It is possible that the table has been corrupted if the problem is genuine; this could be caused by a number of things, but dodgy hardware or power failure are possibilities.</p>\n\n<p>Check the mysql log to see if it has had any problems (or crashed) recently or during the period.</p>\n\n<p>Again, all I can suggest is to try to reproduce it in your test environment. Create very large loads of test data and repeatedly load them.</p>\n"
},
{
"answer_id": 222904,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently there were some lock issues or something, I was able to reproduce the behavior by shooting 'SELECT' statements to the affected and related tables in a parallel connection. </p>\n\n<p>now i used <code>DELETE FROM</code> instead of <code>TRUNCATE</code> and changed the <code>RENAME TABLE</code> statements (where i did 3 renames at once each) to a bunch of single <code>ALTER TABLE xxx RENAME TO zzz</code> statements and can't reproduce the error any more.</p>\n\n<p>so this might be solved. maybe someone else can profit from my day spent with research and a lot of try-and-error.</p>\n"
},
{
"answer_id": 223426,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using transactions? You can eliminate a lot of these sorts of problems with transactions, especially if it's possible to either lock the tables or set the transaction isolation mode to serializable. I'm not really familiar with those on MySQL, but I believe that transactions only work on InnoDB tables (or that could be obsolete knowledge).</p>\n"
},
{
"answer_id": 224223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Errors like this can occur when a MyISAM table becomes corrupt. Running the repair command on the table in question is usually all that's required to fix it:</p>\n\n<pre><code>> repair table mytablename;\n</code></pre>\n\n<p>A better solution is not to use MyISAM for tables where the data is constantly changing - InnoDB is much more bulletproof, and as Paul correctly points out, you can use transactions on InnoDB tables, but not on MyISAM.</p>\n\n<p>By the way, I would avoid renaming tables on the fly - that's a fairly clunky thing to be doing on a regular basis, and could cause some very unexpected results if you ever have other users on the system while the renaming is going on. Why not just do something like this:</p>\n\n<pre><code>> truncate table temptable;\n> truncate table importtable;\n\n> #bulk insert new data\n> insert into importtable(col1,col2,col3) \n> values(1,2,3),(4,5,6),(7,8,9);\n\n> #now archive the live data\n> insert into temptable(col1,col2,col3)\n> select col1,col2,col3 from livetable;\n\n> #finally copy the new data to live\n> truncate table livetable;\n> insert into livetable(col1,col2,col3)\n> select col1,col2,col3 from importtable;\n</code></pre>\n\n<p>Of course if you are inserting a very large number of rows then the risk would be that all of your live data is unavailable for as long as the insert takes to complete, but overall this approach is far less destructive to indexes, triggers or anything else that may be linked to the tables in question.</p>\n"
},
{
"answer_id": 1579049,
"author": "Phpdevmd",
"author_id": 191309,
"author_profile": "https://Stackoverflow.com/users/191309",
"pm_score": 0,
"selected": false,
"text": "<p>You are creating a new record with 'id' field omitted (or NULL),\nBUT previously you have updated another record and changed it's 'id' to '911'.\nIn other words, you can't create another record if your table's AUTO_INCREMENT value is taken.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using **mysql (5.0.32-Debian\_7etch6-log)** and i've got a nightly running bulk load **php (5.2.6)** script **(using Zend\_DB (1.5.1)** via PDO) which does the following:
1. truncating a set of 4 'import' tables
2. bulk inserting data into these 4 'import' tables (re-using ids that have previously been in the tables as well, but i truncated the whole table, so that shouldn't be an issue, right?)
3. if everything goes well, rename the 'live' tables to 'temp', the 'import' tables to 'live' and then the 'temp' (old 'live') tables to 'import'
This worked great for weeks. Now I am occassionally getting this, somewhere in the middle of the whole bulk loading process:
`SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '911' for key 1`
Mind you that, this is not the first id that has been in the table before the truncation already. When I just start the script manually again, it works like a charm.
Any ideas? leftover indexes, something to do with the renaming maybe?
In addition, when I check the table for an entry with the id 911 afterwards, it is not even in there.
|
Errors like this can occur when a MyISAM table becomes corrupt. Running the repair command on the table in question is usually all that's required to fix it:
```
> repair table mytablename;
```
A better solution is not to use MyISAM for tables where the data is constantly changing - InnoDB is much more bulletproof, and as Paul correctly points out, you can use transactions on InnoDB tables, but not on MyISAM.
By the way, I would avoid renaming tables on the fly - that's a fairly clunky thing to be doing on a regular basis, and could cause some very unexpected results if you ever have other users on the system while the renaming is going on. Why not just do something like this:
```
> truncate table temptable;
> truncate table importtable;
> #bulk insert new data
> insert into importtable(col1,col2,col3)
> values(1,2,3),(4,5,6),(7,8,9);
> #now archive the live data
> insert into temptable(col1,col2,col3)
> select col1,col2,col3 from livetable;
> #finally copy the new data to live
> truncate table livetable;
> insert into livetable(col1,col2,col3)
> select col1,col2,col3 from importtable;
```
Of course if you are inserting a very large number of rows then the risk would be that all of your live data is unavailable for as long as the insert takes to complete, but overall this approach is far less destructive to indexes, triggers or anything else that may be linked to the tables in question.
|
221,411 |
<p>I'm creating window using pure Win32 API (RegisterClass and CreateWindow functions). How can I specify a font for the window instead of system defined one?</p>
|
[
{
"answer_id": 221419,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 3,
"selected": false,
"text": "<p>In case you superclass a standard common control that already has its own font handle, use this approach: Just create a font using <code>CreateFont</code> or <code>CreateFontIndirect</code> and set it using <code>WM_SETFONT</code> message (in MFC and ATL there would be a corresponding <code>SetFont</code> function). When the font is no longer needed, destroy the font using <code>DeleteObject</code>. Be sure to not destroy the window's previously set font.</p>\n\n<p>In case you're writing a custom control that draws itself, just create a new font object using <code>CreateFont</code> or <code>CreateFontIndirect</code> and store it in your class somewhere. If you want to support third-party users, handle <code>WM_SETFONT</code> and <code>WM_GETFONT</code> to let the user set another font. When painting, use the current font object stored in your class.</p>\n"
},
{
"answer_id": 224457,
"author": "Bob Jones",
"author_id": 2067,
"author_profile": "https://Stackoverflow.com/users/2067",
"pm_score": 4,
"selected": false,
"text": "<p>As vividos said just use <a href=\"http://msdn.microsoft.com/en-us/library/ms534214.aspx\" rel=\"noreferrer\">CreateFont()/CreateFontIndirect</a>:</p>\n\n<pre><code>HFONT hFont = CreateFont (13, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, \n OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \n DEFAULT_PITCH | FF_DONTCARE, TEXT(\"Tahoma\"));\n</code></pre>\n\n<p>And then set this font for your window/control with the <a href=\"http://msdn.microsoft.com/en-us/library/ms632642(VS.85).aspx\" rel=\"noreferrer\">WM_SETFONT</a> message:</p>\n\n<pre><code>SendMessage(window, WM_SETFONT, hFont, TRUE);\n</code></pre>\n"
},
{
"answer_id": 225733,
"author": "Matthew Xavier",
"author_id": 4841,
"author_profile": "https://Stackoverflow.com/users/4841",
"pm_score": 4,
"selected": false,
"text": "<p>When you create your own window class, you are responsible for managing the font yourself. This task will have four parts:</p>\n\n<ol>\n<li>When the window is created (i.e. when you handle <a href=\"http://msdn.microsoft.com/en-us/library/ms632619(VS.85).aspx\" rel=\"noreferrer\">WM_CREATE</a>), use <a href=\"http://msdn.microsoft.com/en-us/library/ms534214.aspx\" rel=\"noreferrer\">CreateFont()</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms534009(VS.85).aspx\" rel=\"noreferrer\">CreateFontIndirect()</a> to obtain an HFONT for the font you want to use in the window. You will need to store this HFONT along with the other data you keep for each instance of the window class. You may choose to have your window class handle <a href=\"http://msdn.microsoft.com/en-us/library/ms632624(VS.85).aspx\" rel=\"noreferrer\">WM_GETFONT</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms632642(VS.85).aspx\" rel=\"noreferrer\">WM_SETFONT</a> as well, but it is generally not required for top-level windows (if you are creating a control window class, you will want to handle WM_SETFONT, since the dialog manager sends that message).</li>\n<li>If your window has any child windows that contain text, send each of them a WM_SETFONT message whenever your window's font changes. All of the common Windows controls handle WM_SETFONT.</li>\n<li>When you draw the contents of your window (typically in response to a <a href=\"http://msdn.microsoft.com/en-us/library/ms534901(VS.85).aspx\" rel=\"noreferrer\">WM_PAINT</a> message), select your HFONT into the device context with the <a href=\"http://msdn.microsoft.com/en-us/library/ms533272(VS.85).aspx\" rel=\"noreferrer\">SelectObject()</a> function before drawing text (or using text functions such as or <a href=\"http://msdn.microsoft.com/en-us/library/ms534026.aspx\" rel=\"noreferrer\">GetTextMetrics()</a>).</li>\n<li>When the window is destroyed (i.e. when you handle <a href=\"http://msdn.microsoft.com/en-us/library/ms632620(VS.85).aspx\" rel=\"noreferrer\">WM_DESTROY</a>), use <a href=\"http://msdn.microsoft.com/en-us/library/ms533225(VS.85).aspx\" rel=\"noreferrer\">DeleteObject()</a> to release the font you created in step 1. Note that if you choose to handle WM_SETFONT in your window, do <em>not</em> delete a font object you receive in your WM_SETFONT handler, as the code that sent the message expects to retain ownership of that handle.</li>\n</ol>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm creating window using pure Win32 API (RegisterClass and CreateWindow functions). How can I specify a font for the window instead of system defined one?
|
As vividos said just use [CreateFont()/CreateFontIndirect](http://msdn.microsoft.com/en-us/library/ms534214.aspx):
```
HFONT hFont = CreateFont (13, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, TEXT("Tahoma"));
```
And then set this font for your window/control with the [WM\_SETFONT](http://msdn.microsoft.com/en-us/library/ms632642(VS.85).aspx) message:
```
SendMessage(window, WM_SETFONT, hFont, TRUE);
```
|
221,416 |
<p>I'm using MDaemon as out mail server and the last days I get an error "554 Message does not conform to standards" for emails sent from one of the machines. Any idea what may be causing it? Other machines work fine.</p>
<p>More info....this is the log file:</p>
<pre>
Mon 2008-10-20 16:11:37: Session 7831; child 1; thread 3908
Mon 2008-10-20 16:11:36: Accepting SMTP connection from [80.78.72.135 : 43579]
Mon 2008-10-20 16:11:36: Performing PTR lookup (135.72.78.80.IN-ADDR.ARPA)
Mon 2008-10-20 16:11:36: * Error: Name server reports domain name unknown
Mon 2008-10-20 16:11:36: * No PTR records found
Mon 2008-10-20 16:11:36: ---- End PTR results
Mon 2008-10-20 16:11:36: --> 220 ikubinfo.com ESMTP MDaemon 9.5.2; Mon, 20 Oct 2008 16:11:36 +0200
Mon 2008-10-20 16:11:36: 250 ikubinfo.com Hello RS, pleased to meet you
Mon 2008-10-20 16:11:36:
Mon 2008-10-20 16:11:36: Performing IP lookup (ikubINFO.com)
Mon 2008-10-20 16:11:36: * D=ikubINFO.com TTL=(633) A=[216.75.60.232]
Mon 2008-10-20 16:11:36: * P=010 S=000 D=ikubINFO.com TTL=(708) MX=[mail.ikubinfo.com]
Mon 2008-10-20 16:11:36: * D=ikubINFO.com TTL=(633) A=[216.75.60.232]
Mon 2008-10-20 16:11:36: ---- End IP lookup results
Mon 2008-10-20 16:11:36: Performing SPF lookup (ikubINFO.com / 80.78.72.135)
Mon 2008-10-20 16:11:36: * ikubINFO.com 80.78.72.135; matched to SPF cache
Mon 2008-10-20 16:11:36: * Result: pass
Mon 2008-10-20 16:11:36: ---- End SPF results
Mon 2008-10-20 16:11:36: --> 250 , Sender ok
Mon 2008-10-20 16:11:36:
Mon 2008-10-20 16:11:36: Performing DNS-BL lookup (80.78.72.135 - connecting IP)
Mon 2008-10-20 16:11:36: * sbl-xbl.spamhaus.org - passed
Mon 2008-10-20 16:11:36: * relays.ordb.org - failed
Mon 2008-10-20 16:11:36: * bl.spamcop.net - passed
Mon 2008-10-20 16:11:36: ---- End DNS-BL results
Mon 2008-10-20 16:11:36: --> 250 , Recipient ok
Mon 2008-10-20 16:11:37: 354 Enter mail, end with .
Mon 2008-10-20 16:11:37: Message size: 389 bytes
Mon 2008-10-20 16:11:37: --> 554 Message does not conform to standards
Mon 2008-10-20 16:11:37: 221 See ya in cyberspace
Mon 2008-10-20 16:11:37: SMTP session terminated (Bytes in/out: 491/319)
</pre>
|
[
{
"answer_id": 221571,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": true,
"text": "<p>SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.</p>\n\n<p>We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct <a href=\"http://en.wikipedia.org/wiki/Reverse_DNS_lookup\" rel=\"noreferrer\">reverse DNS lookup</a> set up.</p>\n"
},
{
"answer_id": 277611,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To resolve problem go to the MDaemon-->setup-->Miscellaneous options-->Server-->SMTP Server Checks commands and headers for RFC Compliance</p>\n"
},
{
"answer_id": 8971137,
"author": "kaleissin",
"author_id": 30368,
"author_profile": "https://Stackoverflow.com/users/30368",
"pm_score": 3,
"selected": false,
"text": "<p>554 is commonly used by dns blacklists when shooing away blacklisted servers. I'm assuming </p>\n\n<blockquote>\n <p>Mon 2008-10-20 16:11:36: * relays.ordb.org - failed</p>\n</blockquote>\n\n<p>in the log you included is to blame.</p>\n"
},
{
"answer_id": 12031439,
"author": "t.durden",
"author_id": 1069440,
"author_profile": "https://Stackoverflow.com/users/1069440",
"pm_score": 2,
"selected": false,
"text": "<p>Can be caused by a miss configured SPF record on the senders end. </p>\n"
},
{
"answer_id": 14293814,
"author": "hamstar",
"author_id": 334975,
"author_profile": "https://Stackoverflow.com/users/334975",
"pm_score": 0,
"selected": false,
"text": "<p>Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24065/"
] |
I'm using MDaemon as out mail server and the last days I get an error "554 Message does not conform to standards" for emails sent from one of the machines. Any idea what may be causing it? Other machines work fine.
More info....this is the log file:
```
Mon 2008-10-20 16:11:37: Session 7831; child 1; thread 3908
Mon 2008-10-20 16:11:36: Accepting SMTP connection from [80.78.72.135 : 43579]
Mon 2008-10-20 16:11:36: Performing PTR lookup (135.72.78.80.IN-ADDR.ARPA)
Mon 2008-10-20 16:11:36: * Error: Name server reports domain name unknown
Mon 2008-10-20 16:11:36: * No PTR records found
Mon 2008-10-20 16:11:36: ---- End PTR results
Mon 2008-10-20 16:11:36: --> 220 ikubinfo.com ESMTP MDaemon 9.5.2; Mon, 20 Oct 2008 16:11:36 +0200
Mon 2008-10-20 16:11:36: 250 ikubinfo.com Hello RS, pleased to meet you
Mon 2008-10-20 16:11:36:
Mon 2008-10-20 16:11:36: Performing IP lookup (ikubINFO.com)
Mon 2008-10-20 16:11:36: * D=ikubINFO.com TTL=(633) A=[216.75.60.232]
Mon 2008-10-20 16:11:36: * P=010 S=000 D=ikubINFO.com TTL=(708) MX=[mail.ikubinfo.com]
Mon 2008-10-20 16:11:36: * D=ikubINFO.com TTL=(633) A=[216.75.60.232]
Mon 2008-10-20 16:11:36: ---- End IP lookup results
Mon 2008-10-20 16:11:36: Performing SPF lookup (ikubINFO.com / 80.78.72.135)
Mon 2008-10-20 16:11:36: * ikubINFO.com 80.78.72.135; matched to SPF cache
Mon 2008-10-20 16:11:36: * Result: pass
Mon 2008-10-20 16:11:36: ---- End SPF results
Mon 2008-10-20 16:11:36: --> 250 , Sender ok
Mon 2008-10-20 16:11:36:
Mon 2008-10-20 16:11:36: Performing DNS-BL lookup (80.78.72.135 - connecting IP)
Mon 2008-10-20 16:11:36: * sbl-xbl.spamhaus.org - passed
Mon 2008-10-20 16:11:36: * relays.ordb.org - failed
Mon 2008-10-20 16:11:36: * bl.spamcop.net - passed
Mon 2008-10-20 16:11:36: ---- End DNS-BL results
Mon 2008-10-20 16:11:36: --> 250 , Recipient ok
Mon 2008-10-20 16:11:37: 354 Enter mail, end with .
Mon 2008-10-20 16:11:37: Message size: 389 bytes
Mon 2008-10-20 16:11:37: --> 554 Message does not conform to standards
Mon 2008-10-20 16:11:37: 221 See ya in cyberspace
Mon 2008-10-20 16:11:37: SMTP session terminated (Bytes in/out: 491/319)
```
|
SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.
We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct [reverse DNS lookup](http://en.wikipedia.org/wiki/Reverse_DNS_lookup) set up.
|
221,432 |
<p>I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.</p>
<p>Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?</p>
<p><strong>[clarification:]</strong> The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it. Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup_window_handle.closed) is easily used, or indeed possible.</p>
|
[
{
"answer_id": 221439,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var myWin = window.open(...);\n\nif (myWin.closed)\n{\n myWin = window.open(...);\n}\n</code></pre>\n"
},
{
"answer_id": 221461,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": true,
"text": "<p>This <a href=\"http://www.irt.org/articles/js205/index.htm\" rel=\"nofollow noreferrer\">excellent, comprehensive article</a> <em>(\"Almost complete control of pop-up windows\")</em> should answer all your questions about javascript popup windows.</p>\n\n<p><em>\"JavaScript 1.1 also introduced the window <strong>closed</strong> property. Using this property, it is possible to detect if a window has been opened and subsequently closed. We can use this to load a page directly into the opener window if it still open for JavaScript 1.1 enabled browsers:\"</em></p>\n\n<pre><code><script language=\"JavaScript\"><!--\nfunction open_main(page) {\n window_handle = window.open(page,'main');\n return false;\n}\n//--></script>\n\n<script language=\"JavaScript1.1\"><!--\nfunction open_main(page) {\n if (opener && !opener.closed) {\n opener.location.href = page;\n }\n else {\n window_handle = window.open(page,'main');\n }\n return false;\n}\n//--></script>\n\n<a href=\"example.htm\" onClick=\"return open_main('example.htm')\">example.htm</a>\n</code></pre>\n\n<p><strong>Addition:</strong>\nYou can get the window handle back in another page by referring to the popup's name this way:</p>\n\n<pre><code>window_handle = window.open(page,'myPopupName');\n</code></pre>\n\n<p>I guess in your case you should think about a consistent way to create all the names of the popup windows throughout the entire application.</p>\n"
},
{
"answer_id": 221762,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 0,
"selected": false,
"text": "<p>There is no universal way to check it as each pop-up blocker has a different behaviour. For example, Opera will not shown the pop-up but the widow.closed will return false as behind the scene Opera keep a shadow copy of the blocked window, just in case the user would like to see it anyway.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6216/"
] |
I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.
Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?
**[clarification:]** The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it. Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup\_window\_handle.closed) is easily used, or indeed possible.
|
This [excellent, comprehensive article](http://www.irt.org/articles/js205/index.htm) *("Almost complete control of pop-up windows")* should answer all your questions about javascript popup windows.
*"JavaScript 1.1 also introduced the window **closed** property. Using this property, it is possible to detect if a window has been opened and subsequently closed. We can use this to load a page directly into the opener window if it still open for JavaScript 1.1 enabled browsers:"*
```
<script language="JavaScript"><!--
function open_main(page) {
window_handle = window.open(page,'main');
return false;
}
//--></script>
<script language="JavaScript1.1"><!--
function open_main(page) {
if (opener && !opener.closed) {
opener.location.href = page;
}
else {
window_handle = window.open(page,'main');
}
return false;
}
//--></script>
<a href="example.htm" onClick="return open_main('example.htm')">example.htm</a>
```
**Addition:**
You can get the window handle back in another page by referring to the popup's name this way:
```
window_handle = window.open(page,'myPopupName');
```
I guess in your case you should think about a consistent way to create all the names of the popup windows throughout the entire application.
|
221,434 |
<p>I'm trying to serve dynamically generated xml pages from a web server, and provide a custom, static, xslt from the same web server, that will offload the processing into the client web browser.</p>
<p>Until recently, I had this working fine in Firefox 2, 3, IE5, 6 and Chrome. Recently, though, something has changed, and Firefox 3 now displays just the text elements in the source.</p>
<p>The page source starts like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Firefox 2.0 and Internet Explorer 7 use simplistic feed sniffing to override desired presentation behavior for this feed, and thus we are obliged to insert this comment, a bit of a waste of bandwidth, unfortunately. This should ensure that the following stylesheet processing instruction is honored by these new browser versions. For some more background you might want to visit the following bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=338621 -->
<?xml-stylesheet type="text/xsl" href="/WebObjects/SantaPreview.woa/Contents/WebServerResources/Root.xsl"?>
<wrapper xmlns="http://www.bbc.co.uk/ContentInterface/Content" xmlns:cont="http://www.bbc.co.uk/ContentInterface/Content" sceneId="T2a_INDEX" serviceName="DSat_T2">
....
</code></pre>
<p>Firebug shows that the Root.xsl file is being loaded, and the response headers for it include the line</p>
<pre><code>Content-Type text/xml
</code></pre>
<p><em>I've also tried it with application/xml as the content type, but it makes no difference :-(</em></p>
<p>The Web Developer Extension shows the correct generated source too, and if you save this and load the page in Firefox, it displays correctly.</p>
<p>The version of Firefox displaying the problem is 3.0.3</p>
<p>Any ideas what I might be doing wrong?</p>
|
[
{
"answer_id": 223998,
"author": "ThePants",
"author_id": 29260,
"author_profile": "https://Stackoverflow.com/users/29260",
"pm_score": 0,
"selected": false,
"text": "<p>try serving it as application/xml instead of text/xml</p>\n"
},
{
"answer_id": 231522,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": true,
"text": "<p>Displaying just the text elements is the behavior you would get out of an empty XSL stylesheet.</p>\n\n<p>To me, that suggests that something fishy is going on with your xpath expressions, and that the xsl:template/@match attributes do not match the source document.</p>\n\n<p>You do not provide enough information to diagnose further, so this blind guess is all I can offer.</p>\n\n<p>EDIT: It turned out the problem was that IE and Chrome silently accept a nodeset as argument to <a href=\"http://www.w3.org/TR/xpath#function-string-length\" rel=\"noreferrer\">string-length</a>, while FF3 does not. Note that the specification mandates an optional string argument and does not specify behavior with a nodeset argument.</p>\n"
},
{
"answer_id": 232858,
"author": "Bill Michell",
"author_id": 7938,
"author_profile": "https://Stackoverflow.com/users/7938",
"pm_score": 2,
"selected": false,
"text": "<p><em>Answering my own question in the light of subsequent investigation. <a href=\"https://stackoverflow.com/questions/221434/how-can-i-get-firefox-3-to-display-a-page-after-performing-the-xsl-stylesheet-p#231522\">ddaa</a> lead me in the right direction.</em></p>\n\n<p>Firefox seems to be pretty fussy with xslt conversions. Double-check your xslt to ensure it has no errors that IE and Chrome are masking.</p>\n\n<p>XML Spy is a good, though not cheap, product that will highlight a range of errors in the xslt. It seems to pick up at least as many issues as the Firefox renderer does.</p>\n\n<p>It seems you can't rely on the Web Developer extension to pick up the problem, unfortunately.</p>\n"
},
{
"answer_id": 3925500,
"author": "Prof. Falken",
"author_id": 193892,
"author_profile": "https://Stackoverflow.com/users/193892",
"pm_score": 2,
"selected": false,
"text": "<p>I just write here for posterity - I had the same symptom, also Firefox 3. However in <i>my</i> case, the problem was another:</p>\n\n<p>Firefox seems to really, <em>really</em> dislike when an XSL file has an underscore <strong><code>_</code></strong> in the name. My XSLT file was called something like <code>my_super_nice_xslt_which_loads_in_opera_and_ie.xsl</code>.</p>\n\n<p>So, people, let's not use underscores. Use a hyphen (minus) instead:\n<code>my-super-nice-xslt-which-loads-in-opera-and-ie.xsl</code>.</p>\n\n<p>Then it will load in Firefox as well. I think I will just use dead simple names with letters and numbers in them from now on. You know the saying, \"once bitten, twice shy\". <em>(In my case, I was bitten twice, but forgot the first time, so that makes me like four times shy this time.)</em></p>\n"
},
{
"answer_id": 16191491,
"author": "Thomas Leonard",
"author_id": 50926,
"author_profile": "https://Stackoverflow.com/users/50926",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using NoScript, that also disables XSL stylesheets until you <code>Allow <site></code>.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938/"
] |
I'm trying to serve dynamically generated xml pages from a web server, and provide a custom, static, xslt from the same web server, that will offload the processing into the client web browser.
Until recently, I had this working fine in Firefox 2, 3, IE5, 6 and Chrome. Recently, though, something has changed, and Firefox 3 now displays just the text elements in the source.
The page source starts like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<!-- Firefox 2.0 and Internet Explorer 7 use simplistic feed sniffing to override desired presentation behavior for this feed, and thus we are obliged to insert this comment, a bit of a waste of bandwidth, unfortunately. This should ensure that the following stylesheet processing instruction is honored by these new browser versions. For some more background you might want to visit the following bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=338621 -->
<?xml-stylesheet type="text/xsl" href="/WebObjects/SantaPreview.woa/Contents/WebServerResources/Root.xsl"?>
<wrapper xmlns="http://www.bbc.co.uk/ContentInterface/Content" xmlns:cont="http://www.bbc.co.uk/ContentInterface/Content" sceneId="T2a_INDEX" serviceName="DSat_T2">
....
```
Firebug shows that the Root.xsl file is being loaded, and the response headers for it include the line
```
Content-Type text/xml
```
*I've also tried it with application/xml as the content type, but it makes no difference :-(*
The Web Developer Extension shows the correct generated source too, and if you save this and load the page in Firefox, it displays correctly.
The version of Firefox displaying the problem is 3.0.3
Any ideas what I might be doing wrong?
|
Displaying just the text elements is the behavior you would get out of an empty XSL stylesheet.
To me, that suggests that something fishy is going on with your xpath expressions, and that the xsl:template/@match attributes do not match the source document.
You do not provide enough information to diagnose further, so this blind guess is all I can offer.
EDIT: It turned out the problem was that IE and Chrome silently accept a nodeset as argument to [string-length](http://www.w3.org/TR/xpath#function-string-length), while FF3 does not. Note that the specification mandates an optional string argument and does not specify behavior with a nodeset argument.
|
221,452 |
<pre><code>Control.TabIndex
</code></pre>
<p>Only allows me to overide the Tab order of controls in a given container. </p>
<p>Is there a way to specify this across all the controls in, for example a UserControl, regardless of the contains used to arrange the controls.</p>
<p>Cheers,</p>
<p>Jan</p>
|
[
{
"answer_id": 234133,
"author": "James Osborn",
"author_id": 6686,
"author_profile": "https://Stackoverflow.com/users/6686",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure that there is a particularly good way of doing what you are asking, but check out <a href=\"http://www.julmar.com/blog/mark/PermaLink,guid,6e4769e5-a0b3-47b2-a142-6dfefd0c028e.aspx\" rel=\"nofollow noreferrer\" title=\"Changing WPF focus in code\">Changing WPF focus in code</a>.</p>\n\n<p>That uses <code>KeyboardNavigation.TabNavigation</code> to set how the various containers take and give up the Focus on tabbing, and also sets the <code>TabIndex</code> properties for each control. Look at the example code with the <code>TabNavigation</code> set to \"Continue\".</p>\n\n<p>If your tabbing problems are simple, you should be able to find a solution here, if they are complex of need to be generalised, then it might take some more work.</p>\n"
},
{
"answer_id": 667122,
"author": "Steven",
"author_id": 80566,
"author_profile": "https://Stackoverflow.com/users/80566",
"pm_score": 0,
"selected": false,
"text": "<p>This kind of focus handling is horrible in WPF. The best approch is to make a lot of controls not accept focus with Focusable=\"False\".</p>\n\n<p>The TabNavigation answer would solve the tab key however the arrow keys will not work like you want.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460845/"
] |
```
Control.TabIndex
```
Only allows me to overide the Tab order of controls in a given container.
Is there a way to specify this across all the controls in, for example a UserControl, regardless of the contains used to arrange the controls.
Cheers,
Jan
|
I'm not sure that there is a particularly good way of doing what you are asking, but check out [Changing WPF focus in code](http://www.julmar.com/blog/mark/PermaLink,guid,6e4769e5-a0b3-47b2-a142-6dfefd0c028e.aspx "Changing WPF focus in code").
That uses `KeyboardNavigation.TabNavigation` to set how the various containers take and give up the Focus on tabbing, and also sets the `TabIndex` properties for each control. Look at the example code with the `TabNavigation` set to "Continue".
If your tabbing problems are simple, you should be able to find a solution here, if they are complex of need to be generalised, then it might take some more work.
|
221,455 |
<p>My stomach churns when I see this kind of output.</p>
<p><a href="http://www.freeimagehosting.net/uploads/e1097a5a10.jpg" rel="nofollow noreferrer">http://www.freeimagehosting.net/uploads/e1097a5a10.jpg</a></p>
<p>and this was my command
as suggested by <a href="https://stackoverflow.com/questions/75500/best-way-to-convert-pdf-files-to-tiff-files#221341">Best way to convert pdf files to tiff files</a></p>
<pre><code>gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit
</code></pre>
<p>What am I doing wrong?</p>
<p>(commercial products will not be considered)</p>
|
[
{
"answer_id": 221504,
"author": "danio",
"author_id": 12663,
"author_profile": "https://Stackoverflow.com/users/12663",
"pm_score": 5,
"selected": true,
"text": "<p>tiffg4 is a black&white output device.\nYou should use tiff24nc or tiff12nc as the output device colour PDFs - see <a href=\"http://pages.cs.wisc.edu/~ghost/doc/AFPL/8.00/Devices.htm#TIFF\" rel=\"noreferrer\">ghostscript output devices</a>.\nThese will be uncompressed but you could put the resulting TIFFs through imagemagick or similar to resave as compressed TIFF.</p>\n"
},
{
"answer_id": 221588,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>It is quite nice for a fax! ;-)</p>\n\n<p>danio's answer is probably the best, if you need a color copy.</p>\n\n<p>I notice also, from the linked thread, that you omitted to specify DPI for the output, hence the bad look... If you need pure dithered B&W, you should use a higher resolution.</p>\n\n<p>I also got a good looking image using <a href=\"http://pagesperso-orange.fr/pierre.g/xnview/en_nconvert.html\" rel=\"nofollow noreferrer\" title=\"NConvert\">NConvert</a></p>\n\n<pre><code>nconvert -page 1 -out tiff -dpi 200 -c 2 -o c.tif FMD.pdf\n</code></pre>\n\n<p>I mention it for the record, because I think you need a license to redistribute it (it is free for personal use otherwise).</p>\n"
},
{
"answer_id": 224517,
"author": "Setori",
"author_id": 21537,
"author_profile": "https://Stackoverflow.com/users/21537",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks guys this is what I ended up with</p>\n\n<pre><code> os.popen(' '.join([\n self._ghostscriptPath + 'gswin32c.exe', \n '-q',\n '-dNOPAUSE',\n '-dBATCH',\n '-r800',\n '-sDEVICE=tiffg4',\n '-sPAPERSIZE=a4',\n '-sOutputFile=%s %s' % (tifDest, pdfSource),\n ]))\n</code></pre>\n"
},
{
"answer_id": 2981522,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 1,
"selected": false,
"text": "<p>setori's command does not specify the resolution to use for the <em>tiffg4</em> output. The consequence is: Ghostscript will use its default setting for that output, which is 204x196dpi.</p>\n\n<p>In order to increase the resolution to 600dpi, add a <code>-r600</code> commandline parameter:</p>\n\n<pre><code>gswin32c.exe ^\n -o output.tiff ^\n -sDEVICE=tiffg4 ^\n -r600 ^\n input.pdf\n</code></pre>\n\n<p>Also note that TIFFG4 is the standard fax format and as such it uses black+white/grayscale only, but no colors.</p>\n\n<p><strong>@jeff:</strong> Have you ever tried the <code>-dDITHERPPI=<lpi></code> parameter with Ghostscript? (Reasonable values for <em>lpi</em> are N/5 to N/20, where N is the resolution in dpi. So for <code>-r600</code> use try with <code>-dDITHERPPI=30</code> to <code>dDITHERPPI=120</code>).</p>\n"
},
{
"answer_id": 4427418,
"author": "Amil Waduwawara",
"author_id": 540323,
"author_profile": "https://Stackoverflow.com/users/540323",
"pm_score": 4,
"selected": false,
"text": "<p>I have been using ImageMagick for quite a sometime. It's very nice tool with a lot of features.</p>\n<p>Install <a href=\"https://www.imagemagick.org/script/download.php#windows\" rel=\"nofollow noreferrer\">ImageMagick</a> and run following command. This is what I used on Linux, you may have to replace <code>convert</code> with the correct one.</p>\n<p>Below command converts PDFs to <strong>CCITT Group 3</strong> standard TIFs (Fax standard):</p>\n<pre><code>convert -define quantum:polarity=min-is-white \\\n -endian MSB \\\n -units PixelsPerInch \\\n -density 204x196 \\\n -monochrome \\\n -compress Fax \\\n -sample 1728 \\\n "input.pdf" "output.tif"\n</code></pre>\n<p>Also you may use <a href=\"http://www.graphicsmagick.org/\" rel=\"nofollow noreferrer\">GraphicsMagick</a>, it is also similar to ImageMagick, but ImageMagick more concerns with quality than speed.</p>\n"
},
{
"answer_id": 7466753,
"author": "Stephen Quan",
"author_id": 705252,
"author_profile": "https://Stackoverflow.com/users/705252",
"pm_score": 2,
"selected": false,
"text": "<p>Like other posts suggested, use a color format (e.g. -sDEVICE=tiff24nc) and specify a higher resolution (e.g. -r600x600):</p>\n\n<pre><code>gswin32c.exe -q -dNOPAUSE -r600 -sDEVICE=tiff24nc -sOutputFile=a.tif a.pdf -c quit\n</code></pre>\n"
},
{
"answer_id": 10403444,
"author": "Gene Garber",
"author_id": 1303375,
"author_profile": "https://Stackoverflow.com/users/1303375",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into the same problem with fax pages.</p>\n\n<p>I was using Imagick in php and this command fixed the way it looked.</p>\n\n<pre><code>$Imagick->blackThresholdImage('grey');\n</code></pre>\n\n<p>I didn't see any threshold option using 'gs' but convert may also work for you.</p>\n\n<pre><code>convert a.pdf -threshold 60% a.tif\n</code></pre>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
My stomach churns when I see this kind of output.
<http://www.freeimagehosting.net/uploads/e1097a5a10.jpg>
and this was my command
as suggested by [Best way to convert pdf files to tiff files](https://stackoverflow.com/questions/75500/best-way-to-convert-pdf-files-to-tiff-files#221341)
```
gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit
```
What am I doing wrong?
(commercial products will not be considered)
|
tiffg4 is a black&white output device.
You should use tiff24nc or tiff12nc as the output device colour PDFs - see [ghostscript output devices](http://pages.cs.wisc.edu/~ghost/doc/AFPL/8.00/Devices.htm#TIFF).
These will be uncompressed but you could put the resulting TIFFs through imagemagick or similar to resave as compressed TIFF.
|
221,467 |
<p>I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes.</p>
<p>Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to determine which performs better.</p>
<p>I'm not sure what it means by casting to Object types. Here is my code so far</p>
<pre><code> //Generic
class Person<T> {
T var1;
public Person(T yer) {
var1 = yer;
}
public T Value { get { return var1; } }
}
//Normal class
class Human {
int var1;
public Human(int yer) {
var1 = yer;
}
public int Value { get { return var1; } }
}
</code></pre>
<p>My main program running the loops</p>
<pre><code>for (int i = 0; i < 1000000; i++) {
Person<int> me = new Person<int>(1);
int hey = me.Value;
}
for (int i = 0; i < 1000000; i++) {
Human per = new Human(1);
object her = (object)per.Value;
}
</code></pre>
<p>I don't know if Im doing this right. Help please :-)</p>
|
[
{
"answer_id": 221470,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 4,
"selected": true,
"text": "<p>I think that the question is asking you to create a collection class, and insert instances of your class into that.</p>\n\n<p>E.g., </p>\n\n<p>Generics version:</p>\n\n<pre><code>List<Human> myList = new List<Human>();\nHuman h = new Human();\nmyList.Add(h);\n</code></pre>\n\n<p>Object version:</p>\n\n<pre><code>ArrayList myObjectList = new ArrayList();\nHuman h = new Human();\nmyObjectList.Add((object)h));\n</code></pre>\n\n<p>I haven't checked whether that compiles, and have to run now.</p>\n"
},
{
"answer_id": 221480,
"author": "Chris Conway",
"author_id": 2849,
"author_profile": "https://Stackoverflow.com/users/2849",
"pm_score": 0,
"selected": false,
"text": "<p>I think you've got it right except for the for loops. An int is an object type so replace</p>\n\n<pre><code>object her = (object)per.Value;\n</code></pre>\n\n<p>with </p>\n\n<pre><code>int her = per.Value;\n</code></pre>\n\n<p>The other thing you're missing is some performance counters. Have a look at the Timer class to see what kinds of things you can do to see which is a better performer.</p>\n"
},
{
"answer_id": 221481,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure, but it sounds to me like a question that is trying to test out your knowledge of <a href=\"http://msdn.microsoft.com/en-us/library/yz2be5wk(VS.80).aspx\" rel=\"nofollow noreferrer\">boxing and unboxing</a> rules.</p>\n\n<p>int i = 123;\nobject o = (object)i; // boxing</p>\n\n<p>The object o can then be unboxed and assigned to integer variable i:</p>\n\n<p>o = 123;\ni = (int)o; // unboxing</p>\n\n<p>If an object gets boxed and unboxed it is slower as a new object gets created.</p>\n"
},
{
"answer_id": 221483,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you are doing it right. There isn't much you can do with pure Object instances as most operators don't work on them. There are four public methods defined: Equals, GetHashCode, GetType and ToString. I guess you could fiddle with Equals and see if that makes any difference.</p>\n"
},
{
"answer_id": 221488,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 1,
"selected": false,
"text": "<p>I think the question is for looping over a collection of your classes.</p>\n\n<p><strong>Generic</strong></p>\n\n<pre><code>List<Person> pList = new List<Person>();\nfor(int i = 0; i<1000; ++i)\n pList.Add(new Person(30));\n\nStopWatch sw = new StopWatch();\nsw.start();\nint sum = 0;\nforeach(Person p in pList)\n sum += p.Value;\nsw.Stop();\n</code></pre>\n\n<p><strong>Object</strong></p>\n\n<pre><code>ArrayList hList = new ArrayList;\nfor(int i = 0; i<1000; ++i)\n hList.Add(new Human(30));\n\nStopWatch sw = new StopWatch();\nsw.start();\nint sum = 0;\nforeach(Object h in hList)\n sum += ((Human)h).Value;\nsw.Stop();\n</code></pre>\n"
},
{
"answer_id": 221511,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 0,
"selected": false,
"text": "<p>Well if I am doing it right, then according to my counters (DateTime.Now.Ticks) then I can't see any difference in performance at all. </p>\n\n<p>If I take endian's approach then I can see where the performance hit is.</p>\n\n<p>Lets hope my exam questions are a little clearer.</p>\n\n<p>Thanks everyone.</p>\n"
},
{
"answer_id": 221518,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>What you are being asked to do is use the Object inside your class, so Person<> is perfect. What you need to do is change Human so that Var1 is an object. Then, wherever you use var1 cast it to or from an int:</p>\n\n<pre><code>class Human \n{ \n object var1;\n public Human(int yer) \n { \n var1 = (object) yer; \n }\n public int Value \n { \n get { return (int) var1; }\n } \n}\n</code></pre>\n\n<p>The confusion come from the fact in this example, var1 really can't be anything besides an int, so it's really not a good candidate for generics, and in production should be written as you originally wrote Human. But as I wrote it, it's OK for this exercise.</p>\n"
},
{
"answer_id": 9680520,
"author": "Ian",
"author_id": 1265974,
"author_profile": "https://Stackoverflow.com/users/1265974",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a late addition to this question but I used this code exactly and got it to work by using <code>DateTime.Now.Ticks</code> just by updating the following:</p>\n\n<pre><code> DateTime t = DateTime.Now;\n for (int i = 0; i < 1000000; i++)\n {\n Person<int> me = new Person<int>(1);\n int hey = me.Value;\n }\n long a = DateTime.Now.Ticks - t.Ticks;\n TimeSpan A = new TimeSpan(a);\n\n\n for (int i = 0; i < 1000000; i++)\n {\n Human per = new Human(1);\n object her = (object)per.Value;\n }\n\n long b = DateTime.Now.Ticks - t.Ticks;\n TimeSpan B = new TimeSpan(b);\n\n Console.WriteLine(A.ToString());\n Console.WriteLine(B.ToString());\n Console.ReadLine();\n</code></pre>\n\n<p>There is a big difference in performance, as generics is about twice as fast.</p>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes.
Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to determine which performs better.
I'm not sure what it means by casting to Object types. Here is my code so far
```
//Generic
class Person<T> {
T var1;
public Person(T yer) {
var1 = yer;
}
public T Value { get { return var1; } }
}
//Normal class
class Human {
int var1;
public Human(int yer) {
var1 = yer;
}
public int Value { get { return var1; } }
}
```
My main program running the loops
```
for (int i = 0; i < 1000000; i++) {
Person<int> me = new Person<int>(1);
int hey = me.Value;
}
for (int i = 0; i < 1000000; i++) {
Human per = new Human(1);
object her = (object)per.Value;
}
```
I don't know if Im doing this right. Help please :-)
|
I think that the question is asking you to create a collection class, and insert instances of your class into that.
E.g.,
Generics version:
```
List<Human> myList = new List<Human>();
Human h = new Human();
myList.Add(h);
```
Object version:
```
ArrayList myObjectList = new ArrayList();
Human h = new Human();
myObjectList.Add((object)h));
```
I haven't checked whether that compiles, and have to run now.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.