qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
147,941
|
<p>I am trying to read an Http response stream twice via the following:</p>
<pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
RssReader reader = new RssReader(stream);
do
{
element = reader.Read();
if (element is RssChannel)
{
feed.Channels.Add((RssChannel)element);
}
} while (element != null);
StreamReader sr = new StreamReader(stream);
feed._FeedRawData = sr.ReadToEnd();
</code></pre>
<p>However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).</p>
<p>Basically, I would like to parse the stream for XML and have access to the raw data (in string format).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 147961,
"author": "Iain",
"author_id": 23385,
"author_profile": "https://Stackoverflow.com/users/23385",
"pm_score": 7,
"selected": true,
"text": "Stream responseStream = CopyAndClose(resp.GetResponseStream());\n// Do something with the stream\nresponseStream.Position = 0;\n// Do something with the stream again\n\n\nprivate static Stream CopyAndClose(Stream inputStream)\n{\n const int readSize = 256;\n byte[] buffer = new byte[readSize];\n MemoryStream ms = new MemoryStream();\n\n int count = inputStream.Read(buffer, 0, readSize);\n while (count > 0)\n {\n ms.Write(buffer, 0, count);\n count = inputStream.Read(buffer, 0, readSize);\n }\n ms.Position = 0;\n inputStream.Close();\n return ms;\n}\n"
},
{
"answer_id": 59044358,
"author": "Jack Miller",
"author_id": 2484903,
"author_profile": "https://Stackoverflow.com/users/2484903",
"pm_score": 2,
"selected": false,
"text": "// Create the streams.\nMemoryStream destination = new MemoryStream();\n\nusing (FileStream source = File.Open(@\"c:\\temp\\data.dat\",\n FileMode.Open))\n{\n\n Console.WriteLine(\"Source length: {0}\", source.Length.ToString());\n\n // Copy source to destination.\n source.CopyTo(destination);\n}\n\nConsole.WriteLine(\"Destination length: {0}\", destination.Length.ToString());\n destination // re-set to beginning and convert stream to string\ndestination.Position = 0;\nStreamReader streamReader = new StreamReader(destination);\nstring text = streamReader.ReadToEnd();\n// re-set to beginning and read again\ndestination.Position = 0;\nRssReader cssReader = new RssReader(destination);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10505/"
] |
147,953
|
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX</p>
<pre><code>HIERARCHIZE({
[Location].[Test Company],
Descendants([Location].[Test Company], [Location].[Region]),
Descendants([Location].[Test Company], [Location].[Area]),
Descendants([Location].[Test Company], [Location].[Site])
})
</code></pre>
<p>Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?</p>
|
[
{
"answer_id": 147987,
"author": "Santiago Cepas",
"author_id": 6547,
"author_profile": "https://Stackoverflow.com/users/6547",
"pm_score": 4,
"selected": true,
"text": "DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
147,962
|
<p>I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below.</p>
<p>My requirement is as follows:</p>
<ul>
<li>I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. </li>
<li>The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name & location) containing them, for the complete the list of words. </li>
<li>The documents must contain <strong>all</strong> the words in the list.</li>
<li>I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time.</li>
</ul>
<p>A possible approach to a solution I came up with is as follows:
I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word_Docs'.</p>
<ul>
<li>'Documents' will have (idDoc, Name, Location) of all documents.</li>
<li>'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once).</li>
<li>'Word_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in.</li>
</ul>
<p>The function is then called with the content of an editbox on each keystroke (except space):</p>
<ul>
<li>the string is tokenized</li>
<li>(here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual_words, doc_name, doc_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs?</li>
<li>this dataset (/list/array) is then returned </li>
</ul>
<p>The returned list-content is then displayed:</p>
<p>e.g.: called with: "seq sta cod"
displays:</p>
<pre><code>sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt]
- stop - code - Counting Sequences [file://docs/sample/con_seq.txt]
sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc]
</code></pre>
<p>(and-so-on)</p>
<p>Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit?
Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist.
If word-completion: how would that be implemented?</p>
<p>(Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))</p>
|
[
{
"answer_id": 147989,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "-- N is the number of elements in the list\n\nSELECT idDoc, COUNT(1)\nFROM Word_Docs wd INNER JOIN Words w on w.idWord = wd.idWord\nWHERE w.Word IN ('word1', ..., 'wordN')\nGROUP BY wd.idDoc\nHAVING COUNT(1) = N\n"
},
{
"answer_id": 148098,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "SELECT COUNT(Document.idDoc) AS NumOfHits, Documents.Name AS Name, Documents.Location AS Location \nFROM Documents INNER JOIN Word_Docs ON Word_Docs.idDoc=Documents.idDoc \nINNER JOIN Words ON Words.idWord=Words_Docs.idWord\nWHERE Words.Word IN ('Word1', 'Word2', 'Word3', ..., 'WordX')\nGROUP BY Document.idDoc HAVING NumOfHits=X\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] |
147,969
|
<p>I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?</p>
<p>BTW, <em>I know of the existence of the various Unit frameworks in Ruby</em> - this is an exercise to learn the Ruby idioms, rather than to "get something done".</p>
|
[
{
"answer_id": 148938,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 4,
"selected": false,
"text": "Assertions module Assertions\n def assert(param)\n # do something with param\n end\n\n # define more assertions here\nend\n class Object\n include Assertions\nend\n"
},
{
"answer_id": 1261375,
"author": "Julik",
"author_id": 153886,
"author_profile": "https://Stackoverflow.com/users/153886",
"pm_score": 8,
"selected": true,
"text": " raise \"This is wrong\" unless expr\n"
},
{
"answer_id": 2966157,
"author": "regularfry",
"author_id": 190007,
"author_profile": "https://Stackoverflow.com/users/190007",
"pm_score": 3,
"selected": false,
"text": "def assert(msg=nil)\n if DEBUG\n raise msg || \"Assertion failed!\" unless yield\n end\nend\n"
},
{
"answer_id": 7481328,
"author": "jmanrubia",
"author_id": 469697,
"author_profile": "https://Stackoverflow.com/users/469697",
"pm_score": 5,
"selected": false,
"text": "assert assert assert some_string != \"some value\"\nassert clients.empty?, \"Isn't the clients list empty?\"\n\ninvariant \"Lists with different sizes?\" do\n one_variable = calculate_some_value\n other_variable = calculate_some_other_value\n one_variable > other_variable\nend \n assert invariant raise"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
] |
147,976
|
<p>I'm making a simple jquery command:</p>
<p><code>element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");</code></p>
<p>using the attributes/html method: <a href="http://docs.jquery.com/Attributes/html" rel="nofollow noreferrer">http://docs.jquery.com/Attributes/html</a></p>
<p>It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.</p>
<p>So instead of <code>" "</code> <em>(6 spaces)</em> it's just <code>""</code>. </p>
<p>Once again, this is running on App Engine, but I don't think that should matter...</p>
|
[
{
"answer_id": 148387,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 1,
"selected": false,
"text": " html()"
},
{
"answer_id": 148404,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 2,
"selected": false,
"text": "$('element').html(' ');\n "
},
{
"answer_id": 173189,
"author": "J5.",
"author_id": 25380,
"author_profile": "https://Stackoverflow.com/users/25380",
"pm_score": 0,
"selected": false,
"text": "element.html('\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ ');"
},
{
"answer_id": 173204,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "padding-left text-indent element.css(\"textIndent\", \"3em\");\n "
},
{
"answer_id": 173474,
"author": "davil",
"author_id": 22592,
"author_profile": "https://Stackoverflow.com/users/22592",
"pm_score": 3,
"selected": true,
"text": "element.html(String.fromCharCode(32));\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9106/"
] |
147,988
|
<p>I want to split an arithmetic expression into tokens, to convert it into RPN.</p>
<p>Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew something myself.</p>
<p>This sounds like a classic textbook example for Compiler Design 101, but I'm afraid I'm lacking some formal education here. Is there a standard algorithm you can point me to?</p>
<p>My other options are to read up on <a href="http://en.wikipedia.org/wiki/Lexical_analysis" rel="nofollow noreferrer">Lexical Analysis</a> or to roll up something quick and dirty with the available string functions.</p>
|
[
{
"answer_id": 148269,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": true,
"text": "$expr = '(5*(7 + 2 * -9.3) - 8 )/ 11';\n$tokens = preg_split('/([*\\/^+-]+)\\s*|([\\d.]+)\\s*/', $expr, -1,\n PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);\n$tts = print_r($tokens, true);\necho \"<pre>x=$tts</pre>\";\n"
},
{
"answer_id": 148674,
"author": "Hanno Fietz",
"author_id": 2077,
"author_profile": "https://Stackoverflow.com/users/2077",
"pm_score": 0,
"selected": false,
"text": "static function rgTokenize($s)\n{\n $rg = array();\n\n // remove whitespace\n $s = preg_replace(\"/\\s+/\", '', $s);\n\n // split at numbers, identifiers, function names and operators\n $rg = preg_split('/([*\\/^+\\(\\)-])|(#\\d+)|([\\d.]+)|(\\w+)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);\n\n // find right-associative '-' and put it as a sign onto the following number\n for ($ix = 0, $ixMax = count($rg); $ix < $ixMax; $ix++) {\n if ('-' == $rg[$ix]) {\n if (isset($rg[$ix - 1]) && self::fIsOperand($rg[$ix - 1])) {\n continue;\n } else if (isset($rg[$ix + 1]) && self::fIsOperand($rg[$ix + 1])) {\n $rg[$ix + 1] = $rg[$ix].$rg[$ix + 1];\n unset($rg[$ix]);\n } else {\n throw new Exception(\"Syntax error: Found right-associative '-' without operand\");\n }\n }\n }\n $rg = array_values($rg);\n\n echo join(\" \", $rg).\"\\n\";\n\n return $rg;\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
147,995
|
<p>When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage.</p>
<p>For example: </p>
<pre><code>http://example.org/users/index/moderators/page:2/sort:name/dir:asc
</code></pre>
<p>here <strong>moderators</strong> is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.</p>
|
[
{
"answer_id": 396723,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$paginator->options(array('url'=>$this->data['Transaction']));\n foreach($this->params['named'] as $k=>$v)\n{\n /*\n * set data as is normally expected\n */\n $this->data['Transaction'][$k] = $v;\n}\n"
},
{
"answer_id": 1024288,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "$urlpagin = '?my_get1=1&my_get2=2';\n$paginator->options = array('url'=>$urlpagin);\n url/controller/action/?my_get1=1&my_get2=2/sort:.../...\n"
},
{
"answer_id": 6056413,
"author": "Loftx",
"author_id": 89941,
"author_profile": "https://Stackoverflow.com/users/89941",
"pm_score": 3,
"selected": true,
"text": "$this->Paginator->options(array('url' => $this->passedArgs));\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] |
147,996
|
<p>I am using VB6 and the Win32 API to write data to a file, this functionality is for the export of data, therefore write performance to the disk is the key factor in my considerations. As such I am using the <code>FILE_FLAG_NO_BUFFERING</code> and <code>FILE_FLAG_WRITE_THROUGH</code> options when opening the file with a call to <code>CreateFile</code>.</p>
<p><code>FILE_FLAG_NO_BUFFERING</code> requires that I use my own buffer and write data to the file in multiples of the disk's sector size, this is no problem generally, apart from the last part of data, which if it is not an exact multiple of the sector size will include character zero's padding out the file, how do I set the file size once the last block is written to not include these character zero's?</p>
<p>I can use <code>SetEndOfFile</code> however this requires me to close the file and re-open it without using <code>FILE_FLAG_NO_BUFFERING</code>. I have seen someone talk about <code>NtSetInformationFile</code> however I cannot find how to use and declare this in VB6. <code>SetFileInformationByHandle</code> can do exactly what I want however it is only available in Windows Vista, my application needs to be compatible with previous versions of Windows.</p>
|
[
{
"answer_id": 148111,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 3,
"selected": true,
"text": "FILE_FLAG_NO_BUFFERING FILE_FLAG_WRITE_THROUGH"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/147996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23387/"
] |
148,003
|
<p>I have an array of a few million numbers.</p>
<pre><code>double* const data = new double (3600000);
</code></pre>
<p>I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other.</p>
<p>So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000).</p>
<p>I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary.</p>
<p>I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 148030,
"author": "Drakosha",
"author_id": 19868,
"author_profile": "https://Stackoverflow.com/users/19868",
"pm_score": 4,
"selected": true,
"text": "* create sorted container (std::multiset) of first 1000 numbers\n* in loop (j=1, j<(3600000-1000); ++j)\n - calculate range\n - remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array)\n - add to set new relevant number (i.e. in index *j+1000-1* of the array)\n"
},
{
"answer_id": 150298,
"author": "James Caccese",
"author_id": 23581,
"author_profile": "https://Stackoverflow.com/users/23581",
"pm_score": 0,
"selected": false,
"text": "// This should run in (DATA_LEN - RANGE_WIDTH)log(RANGE_WIDTH)\n#include <set>\n#include <algorithm>\nusing namespace std;\n\nconst int DATA_LEN = 3600000;\ndouble* const data = new double (DATA_LEN);\n\n....\n....\n\nconst int RANGE_WIDTH = 1000;\ndouble range = new double(DATA_LEN - RANGE_WIDTH);\nmultiset<double> data_set;\ndata_set.insert(data[i], data[RANGE_WIDTH]);\n\nfor (int i = 0 ; i < DATA_LEN - RANGE_WIDTH - 1 ; i++)\n{\n range[i] = *data_set.end() - *data_set.begin();\n multiset<double>::iterator iter = data_set.find(data[i]);\n data_set.erase(iter);\n data_set.insert(data[i+1]);\n}\nrange[i] = *data_set.end() - *data_set.begin();\n\n// range now holds the values you seek\n"
},
{
"answer_id": 150398,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "std::multiset<double> range;\ndouble currentmax = 0.0;\nfor (int i = 0; i < 3600000; ++i)\n{\n if (i >= 1000)\n range.erase(range.find(data[i-1000]));\n range.insert(data[i]);\n if (i >= 999)\n currentmax = max(currentmax, *range.rbegin());\n}\n"
},
{
"answer_id": 169059,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "Simple: 106875\nQuite Complex: 1218\nComplex: 1219\n #include <algorithm>\n#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\n// Callback types.\ntypedef void (*OutputCallback) (int min, int max);\ntypedef int (*GeneratorCallback) ();\n\n// Declarations of the test functions.\nclock_t Simple (int, int, GeneratorCallback, OutputCallback);\nclock_t QuiteComplex (int, int, GeneratorCallback, OutputCallback);\nclock_t Complex (int, int, GeneratorCallback, OutputCallback);\n #include \"Range.h\"\n\nint\n checksum;\n\n// This callback is used to get data.\nint CreateData ()\n{\n return rand ();\n}\n\n// This callback is used to output the results.\nvoid OutputResults (int min, int max)\n{\n //cout << min << \" - \" << max << endl;\n checksum += max - min;\n}\n\n// The program entry point.\nvoid main ()\n{\n int\n count = 3600000,\n window = 1000;\n\n srand (0);\n checksum = 0;\n std::cout << \"Simple: Ticks = \" << Simple (count, window, CreateData, OutputResults) << \", checksum = \" << checksum << std::endl;\n srand (0);\n checksum = 0;\n std::cout << \"Quite Complex: Ticks = \" << QuiteComplex (count, window, CreateData, OutputResults) << \", checksum = \" << checksum << std::endl;\n srand (0);\n checksum = 0;\n std::cout << \"Complex: Ticks = \" << Complex (count, window, CreateData, OutputResults) << \", checksum = \" << checksum << std::endl;\n}\n #include \"Range.h\"\n\n// Function to actually process the data.\n// A circular buffer of min/max values for the current window is filled\n// and once full, the oldest min/max pair is sent to the output callback\n// and replaced with the newest input value. Each value inputted is \n// compared against all min/max pairs.\nvoid ProcessData\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output,\n int *min_buffer,\n int *max_buffer\n)\n{\n int\n i;\n\n for (i = 0 ; i < window ; ++i)\n {\n int\n value = input ();\n\n min_buffer [i] = max_buffer [i] = value;\n\n for (int j = 0 ; j < i ; ++j)\n {\n min_buffer [j] = min (min_buffer [j], value);\n max_buffer [j] = max (max_buffer [j], value);\n }\n }\n\n for ( ; i < count ; ++i)\n {\n int\n index = i % window;\n\n output (min_buffer [index], max_buffer [index]);\n\n int\n value = input ();\n\n min_buffer [index] = max_buffer [index] = value;\n\n for (int k = (i + 1) % window ; k != index ; k = (k + 1) % window)\n {\n min_buffer [k] = min (min_buffer [k], value);\n max_buffer [k] = max (max_buffer [k], value);\n }\n }\n\n output (min_buffer [count % window], max_buffer [count % window]);\n}\n\n// A simple method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t Simple\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n int\n *min_buffer = new int [window],\n *max_buffer = new int [window];\n\n clock_t\n start = clock ();\n\n ProcessData (count, window, input, output, min_buffer, max_buffer);\n\n clock_t\n end = clock ();\n\n delete [] max_buffer;\n delete [] min_buffer;\n\n return end - start;\n}\n #include \"Range.h\"\n\ntemplate <class T>\nclass Range\n{\nprivate:\n // Class Types\n\n // Node Data\n // Stores a value and its position in various lists.\n struct Node\n {\n Node\n *m_queue_next,\n *m_list_greater,\n *m_list_lower;\n\n T\n m_value;\n };\n\npublic:\n // Constructor\n // Allocates memory for the node data and adds all the allocated\n // nodes to the unused/free list of nodes.\n Range\n (\n int window_size\n ) :\n m_nodes (new Node [window_size]),\n m_queue_tail (m_nodes),\n m_queue_head (0),\n m_list_min (0),\n m_list_max (0),\n m_free_list (m_nodes)\n {\n for (int i = 0 ; i < window_size - 1 ; ++i)\n {\n m_nodes [i].m_list_lower = &m_nodes [i + 1];\n }\n\n m_nodes [window_size - 1].m_list_lower = 0;\n }\n\n // Destructor\n // Tidy up allocated data.\n ~Range ()\n {\n delete [] m_nodes;\n }\n\n // Function to add a new value into the data structure.\n void AddValue\n (\n T value\n )\n {\n Node\n *node = GetNode ();\n\n // clear links\n node->m_queue_next = 0;\n\n // set value of node\n node->m_value = value;\n\n // find place to add node into linked list\n Node\n *search;\n\n for (search = m_list_max ; search ; search = search->m_list_lower)\n {\n if (search->m_value < value)\n {\n if (search->m_list_greater)\n {\n node->m_list_greater = search->m_list_greater;\n search->m_list_greater->m_list_lower = node;\n }\n else\n {\n m_list_max = node;\n }\n\n node->m_list_lower = search;\n search->m_list_greater = node;\n }\n }\n\n if (!search)\n {\n m_list_min->m_list_lower = node;\n node->m_list_greater = m_list_min;\n m_list_min = node;\n }\n }\n\n // Accessor to determine if the first output value is ready for use.\n bool RangeAvailable ()\n {\n return !m_free_list;\n }\n\n // Accessor to get the minimum value of all values in the current window.\n T Min ()\n {\n return m_list_min->m_value;\n }\n\n // Accessor to get the maximum value of all values in the current window.\n T Max ()\n {\n return m_list_max->m_value;\n }\n\nprivate:\n // Function to get a node to store a value into.\n // This function gets nodes from one of two places:\n // 1. From the unused/free list\n // 2. From the end of the fifo queue, this requires removing the node from the list and tree\n Node *GetNode ()\n {\n Node\n *node;\n\n if (m_free_list)\n {\n // get new node from unused/free list and place at head\n node = m_free_list;\n\n m_free_list = node->m_list_lower;\n\n if (m_queue_head)\n {\n m_queue_head->m_queue_next = node;\n }\n\n m_queue_head = node;\n }\n else\n {\n // get node from tail of queue and place at head\n node = m_queue_tail;\n\n m_queue_tail = node->m_queue_next;\n m_queue_head->m_queue_next = node;\n m_queue_head = node;\n\n // remove node from linked list\n if (node->m_list_lower)\n {\n node->m_list_lower->m_list_greater = node->m_list_greater;\n }\n else\n {\n m_list_min = node->m_list_greater;\n }\n\n if (node->m_list_greater)\n {\n node->m_list_greater->m_list_lower = node->m_list_lower;\n }\n else\n {\n m_list_max = node->m_list_lower;\n }\n }\n\n return node;\n }\n\n // Member Data.\n Node\n *m_nodes,\n *m_queue_tail,\n *m_queue_head,\n *m_list_min,\n *m_list_max,\n *m_free_list;\n};\n\n// A reasonable complex but more efficent method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t QuiteComplex\n(\n int size,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n Range <int>\n range (window);\n\n clock_t\n start = clock ();\n\n for (int i = 0 ; i < size ; ++i)\n { \n range.AddValue (input ());\n\n if (range.RangeAvailable ())\n {\n output (range.Min (), range.Max ());\n }\n }\n\n clock_t\n end = clock ();\n\n return end - start;\n}\n #include \"Range.h\"\n\ntemplate <class T>\nclass Range\n{\nprivate:\n // Class Types\n\n // Red/Black tree node colours.\n enum NodeColour\n {\n Red,\n Black\n };\n\n // Node Data\n // Stores a value and its position in various lists and trees.\n struct Node\n {\n // Function to get the sibling of a node.\n // Because leaves are stored as null pointers, it must be possible\n // to get the sibling of a null pointer. If the object is a null pointer\n // then the parent pointer is used to determine the sibling.\n Node *Sibling\n (\n Node *parent\n )\n {\n Node\n *sibling;\n\n if (this)\n {\n sibling = m_tree_parent->m_tree_less == this ? m_tree_parent->m_tree_more : m_tree_parent->m_tree_less;\n }\n else\n {\n sibling = parent->m_tree_less ? parent->m_tree_less : parent->m_tree_more;\n }\n\n return sibling;\n }\n\n // Node Members\n Node\n *m_queue_next,\n *m_tree_less,\n *m_tree_more,\n *m_tree_parent,\n *m_list_greater,\n *m_list_lower;\n\n NodeColour\n m_colour;\n\n T\n m_value;\n };\n\npublic:\n // Constructor\n // Allocates memory for the node data and adds all the allocated\n // nodes to the unused/free list of nodes.\n Range\n (\n int window_size\n ) :\n m_nodes (new Node [window_size]),\n m_queue_tail (m_nodes),\n m_queue_head (0),\n m_tree_root (0),\n m_list_min (0),\n m_list_max (0),\n m_free_list (m_nodes)\n {\n for (int i = 0 ; i < window_size - 1 ; ++i)\n {\n m_nodes [i].m_list_lower = &m_nodes [i + 1];\n }\n\n m_nodes [window_size - 1].m_list_lower = 0;\n }\n\n // Destructor\n // Tidy up allocated data.\n ~Range ()\n {\n delete [] m_nodes;\n }\n\n // Function to add a new value into the data structure.\n void AddValue\n (\n T value\n )\n {\n Node\n *node = GetNode ();\n\n // clear links\n node->m_queue_next = node->m_tree_more = node->m_tree_less = node->m_tree_parent = 0;\n\n // set value of node\n node->m_value = value;\n\n // insert node into tree\n if (m_tree_root)\n {\n InsertNodeIntoTree (node);\n BalanceTreeAfterInsertion (node);\n }\n else\n {\n m_tree_root = m_list_max = m_list_min = node;\n node->m_tree_parent = node->m_list_greater = node->m_list_lower = 0;\n }\n\n m_tree_root->m_colour = Black;\n }\n\n // Accessor to determine if the first output value is ready for use.\n bool RangeAvailable ()\n {\n return !m_free_list;\n }\n\n // Accessor to get the minimum value of all values in the current window.\n T Min ()\n {\n return m_list_min->m_value;\n }\n\n // Accessor to get the maximum value of all values in the current window.\n T Max ()\n {\n return m_list_max->m_value;\n }\n\nprivate:\n // Function to get a node to store a value into.\n // This function gets nodes from one of two places:\n // 1. From the unused/free list\n // 2. From the end of the fifo queue, this requires removing the node from the list and tree\n Node *GetNode ()\n {\n Node\n *node;\n\n if (m_free_list)\n {\n // get new node from unused/free list and place at head\n node = m_free_list;\n\n m_free_list = node->m_list_lower;\n\n if (m_queue_head)\n {\n m_queue_head->m_queue_next = node;\n }\n\n m_queue_head = node;\n }\n else\n {\n // get node from tail of queue and place at head\n node = m_queue_tail;\n\n m_queue_tail = node->m_queue_next;\n m_queue_head->m_queue_next = node;\n m_queue_head = node;\n\n // remove node from tree\n node = RemoveNodeFromTree (node);\n RebalanceTreeAfterDeletion (node);\n\n // remove node from linked list\n if (node->m_list_lower)\n {\n node->m_list_lower->m_list_greater = node->m_list_greater;\n }\n else\n {\n m_list_min = node->m_list_greater;\n }\n\n if (node->m_list_greater)\n {\n node->m_list_greater->m_list_lower = node->m_list_lower;\n }\n else\n {\n m_list_max = node->m_list_lower;\n }\n }\n\n return node;\n }\n\n // Rebalances the tree after insertion\n void BalanceTreeAfterInsertion\n (\n Node *node\n )\n {\n node->m_colour = Red;\n\n while (node != m_tree_root && node->m_tree_parent->m_colour == Red)\n {\n if (node->m_tree_parent == node->m_tree_parent->m_tree_parent->m_tree_more)\n {\n Node\n *uncle = node->m_tree_parent->m_tree_parent->m_tree_less;\n\n if (uncle && uncle->m_colour == Red)\n {\n node->m_tree_parent->m_colour = Black;\n uncle->m_colour = Black;\n node->m_tree_parent->m_tree_parent->m_colour = Red;\n node = node->m_tree_parent->m_tree_parent;\n }\n else\n {\n if (node == node->m_tree_parent->m_tree_less)\n {\n node = node->m_tree_parent;\n LeftRotate (node);\n }\n\n node->m_tree_parent->m_colour = Black;\n node->m_tree_parent->m_tree_parent->m_colour = Red;\n RightRotate (node->m_tree_parent->m_tree_parent);\n }\n }\n else\n {\n Node\n *uncle = node->m_tree_parent->m_tree_parent->m_tree_more;\n\n if (uncle && uncle->m_colour == Red)\n {\n node->m_tree_parent->m_colour = Black;\n uncle->m_colour = Black;\n node->m_tree_parent->m_tree_parent->m_colour = Red;\n node = node->m_tree_parent->m_tree_parent;\n }\n else\n {\n if (node == node->m_tree_parent->m_tree_more)\n {\n node = node->m_tree_parent;\n RightRotate (node);\n }\n\n node->m_tree_parent->m_colour = Black;\n node->m_tree_parent->m_tree_parent->m_colour = Red;\n LeftRotate (node->m_tree_parent->m_tree_parent);\n }\n }\n }\n }\n\n // Adds a node into the tree and sorted linked list\n void InsertNodeIntoTree\n (\n Node *node\n )\n {\n Node\n *parent = 0,\n *child = m_tree_root;\n\n bool\n greater;\n\n while (child)\n {\n parent = child;\n child = (greater = node->m_value > child->m_value) ? child->m_tree_more : child->m_tree_less;\n }\n\n node->m_tree_parent = parent;\n\n if (greater)\n {\n parent->m_tree_more = node;\n\n // insert node into linked list\n if (parent->m_list_greater)\n {\n parent->m_list_greater->m_list_lower = node;\n }\n else\n {\n m_list_max = node;\n }\n\n node->m_list_greater = parent->m_list_greater;\n node->m_list_lower = parent;\n parent->m_list_greater = node;\n }\n else\n {\n parent->m_tree_less = node;\n\n // insert node into linked list\n if (parent->m_list_lower)\n {\n parent->m_list_lower->m_list_greater = node;\n }\n else\n {\n m_list_min = node;\n }\n\n node->m_list_lower = parent->m_list_lower;\n node->m_list_greater = parent;\n parent->m_list_lower = node;\n }\n }\n\n // Red/Black tree manipulation routine, used for removing a node\n Node *RemoveNodeFromTree\n (\n Node *node\n )\n {\n if (node->m_tree_less && node->m_tree_more)\n {\n // the complex case, swap node with a child node\n Node\n *child;\n\n if (node->m_tree_less)\n {\n // find largest value in lesser half (node with no greater pointer)\n for (child = node->m_tree_less ; child->m_tree_more ; child = child->m_tree_more)\n {\n }\n }\n else\n {\n // find smallest value in greater half (node with no lesser pointer)\n for (child = node->m_tree_more ; child->m_tree_less ; child = child->m_tree_less)\n {\n }\n }\n\n swap (child->m_colour, node->m_colour);\n\n if (child->m_tree_parent != node)\n {\n swap (child->m_tree_less, node->m_tree_less);\n swap (child->m_tree_more, node->m_tree_more);\n swap (child->m_tree_parent, node->m_tree_parent);\n\n if (!child->m_tree_parent)\n {\n m_tree_root = child;\n }\n else\n {\n if (child->m_tree_parent->m_tree_less == node)\n {\n child->m_tree_parent->m_tree_less = child;\n }\n else\n {\n child->m_tree_parent->m_tree_more = child;\n }\n }\n\n if (node->m_tree_parent->m_tree_less == child)\n {\n node->m_tree_parent->m_tree_less = node;\n }\n else\n {\n node->m_tree_parent->m_tree_more = node;\n }\n }\n else\n {\n child->m_tree_parent = node->m_tree_parent;\n node->m_tree_parent = child;\n\n Node\n *child_less = child->m_tree_less,\n *child_more = child->m_tree_more;\n\n if (node->m_tree_less == child)\n {\n child->m_tree_less = node;\n child->m_tree_more = node->m_tree_more;\n node->m_tree_less = child_less;\n node->m_tree_more = child_more;\n }\n else\n {\n child->m_tree_less = node->m_tree_less;\n child->m_tree_more = node;\n node->m_tree_less = child_less;\n node->m_tree_more = child_more;\n }\n\n if (!child->m_tree_parent)\n {\n m_tree_root = child;\n }\n else\n {\n if (child->m_tree_parent->m_tree_less == node)\n {\n child->m_tree_parent->m_tree_less = child;\n }\n else\n {\n child->m_tree_parent->m_tree_more = child;\n }\n }\n }\n\n if (child->m_tree_less)\n {\n child->m_tree_less->m_tree_parent = child;\n }\n\n if (child->m_tree_more)\n {\n child->m_tree_more->m_tree_parent = child;\n }\n\n if (node->m_tree_less)\n {\n node->m_tree_less->m_tree_parent = node;\n }\n\n if (node->m_tree_more)\n {\n node->m_tree_more->m_tree_parent = node;\n }\n }\n\n Node\n *child = node->m_tree_less ? node->m_tree_less : node->m_tree_more;\n\n if (node->m_tree_parent->m_tree_less == node)\n {\n node->m_tree_parent->m_tree_less = child;\n }\n else\n {\n node->m_tree_parent->m_tree_more = child;\n }\n\n if (child)\n {\n child->m_tree_parent = node->m_tree_parent;\n }\n\n return node;\n }\n\n // Red/Black tree manipulation routine, used for rebalancing a tree after a deletion\n void RebalanceTreeAfterDeletion\n (\n Node *node\n )\n {\n Node\n *child = node->m_tree_less ? node->m_tree_less : node->m_tree_more;\n\n if (node->m_colour == Black)\n {\n if (child && child->m_colour == Red)\n {\n child->m_colour = Black;\n }\n else\n {\n Node\n *parent = node->m_tree_parent,\n *n = child;\n\n while (parent)\n {\n Node\n *sibling = n->Sibling (parent);\n\n if (sibling && sibling->m_colour == Red)\n {\n parent->m_colour = Red;\n sibling->m_colour = Black;\n\n if (n == parent->m_tree_more)\n {\n LeftRotate (parent);\n }\n else\n {\n RightRotate (parent);\n }\n }\n\n sibling = n->Sibling (parent);\n\n if (parent->m_colour == Black &&\n sibling->m_colour == Black &&\n (!sibling->m_tree_more || sibling->m_tree_more->m_colour == Black) &&\n (!sibling->m_tree_less || sibling->m_tree_less->m_colour == Black))\n {\n sibling->m_colour = Red;\n n = parent;\n parent = n->m_tree_parent;\n continue;\n }\n else\n {\n if (parent->m_colour == Red &&\n sibling->m_colour == Black &&\n (!sibling->m_tree_more || sibling->m_tree_more->m_colour == Black) &&\n (!sibling->m_tree_less || sibling->m_tree_less->m_colour == Black))\n {\n sibling->m_colour = Red;\n parent->m_colour = Black;\n break;\n }\n else\n {\n if (n == parent->m_tree_more &&\n sibling->m_colour == Black &&\n (sibling->m_tree_more && sibling->m_tree_more->m_colour == Red) &&\n (!sibling->m_tree_less || sibling->m_tree_less->m_colour == Black))\n {\n sibling->m_colour = Red;\n sibling->m_tree_more->m_colour = Black;\n RightRotate (sibling);\n }\n else\n {\n if (n == parent->m_tree_less &&\n sibling->m_colour == Black &&\n (!sibling->m_tree_more || sibling->m_tree_more->m_colour == Black) &&\n (sibling->m_tree_less && sibling->m_tree_less->m_colour == Red))\n {\n sibling->m_colour = Red;\n sibling->m_tree_less->m_colour = Black;\n LeftRotate (sibling);\n }\n }\n\n sibling = n->Sibling (parent);\n sibling->m_colour = parent->m_colour;\n parent->m_colour = Black;\n\n if (n == parent->m_tree_more)\n {\n sibling->m_tree_less->m_colour = Black;\n LeftRotate (parent);\n }\n else\n {\n sibling->m_tree_more->m_colour = Black;\n RightRotate (parent);\n }\n break;\n }\n }\n }\n }\n }\n }\n\n // Red/Black tree manipulation routine, used for balancing the tree\n void LeftRotate\n (\n Node *node\n )\n {\n Node\n *less = node->m_tree_less;\n\n node->m_tree_less = less->m_tree_more;\n\n if (less->m_tree_more)\n {\n less->m_tree_more->m_tree_parent = node;\n }\n\n less->m_tree_parent = node->m_tree_parent;\n\n if (!node->m_tree_parent)\n {\n m_tree_root = less;\n }\n else\n {\n if (node == node->m_tree_parent->m_tree_more)\n {\n node->m_tree_parent->m_tree_more = less;\n }\n else\n {\n node->m_tree_parent->m_tree_less = less;\n }\n }\n\n less->m_tree_more = node;\n node->m_tree_parent = less;\n }\n\n // Red/Black tree manipulation routine, used for balancing the tree\n void RightRotate\n (\n Node *node\n )\n {\n Node\n *more = node->m_tree_more;\n\n node->m_tree_more = more->m_tree_less;\n\n if (more->m_tree_less)\n {\n more->m_tree_less->m_tree_parent = node;\n }\n\n more->m_tree_parent = node->m_tree_parent;\n\n if (!node->m_tree_parent)\n {\n m_tree_root = more;\n }\n else\n {\n if (node == node->m_tree_parent->m_tree_less)\n {\n node->m_tree_parent->m_tree_less = more;\n }\n else\n {\n node->m_tree_parent->m_tree_more = more;\n }\n }\n\n more->m_tree_less = node;\n node->m_tree_parent = more;\n }\n\n // Member Data.\n Node\n *m_nodes,\n *m_queue_tail,\n *m_queue_head,\n *m_tree_root,\n *m_list_min,\n *m_list_max,\n *m_free_list;\n};\n\n// A complex but more efficent method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t Complex\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n Range <int>\n range (window);\n\n clock_t\n start = clock ();\n\n for (int i = 0 ; i < count ; ++i)\n { \n range.AddValue (input ());\n\n if (range.RangeAvailable ())\n {\n output (range.Min (), range.Max ());\n }\n }\n\n clock_t\n end = clock ();\n\n return end - start;\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3175/"
] |
148,004
|
<p>Is it possible to find out who called a stored procedure?</p>
<p>For example, say I get an error in <code>proc3</code>. From within that proc I want to know if it was called by <code>proc1</code> or <code>proc2</code>.</p>
|
[
{
"answer_id": 148054,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 2,
"selected": false,
"text": "BEGIN TRY\nEXEC Proc3\nEND TRY\nBEGIN CATCH\nSELECT 'Error Caught'\nSELECT\n ERROR_PROCEDURE()\nEND CATCH\n"
},
{
"answer_id": 148058,
"author": "Kramii",
"author_id": 11514,
"author_profile": "https://Stackoverflow.com/users/11514",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE proc3\n @Caller nvarchar(128) -- Name of calling proc.\n AS\n BEGIN\n -- Produce error message that includes caller's name.\n RAISERROR ('Caller was %s.', 16,10, @Caller);\n END\n GO\n\n CREATE PROCEDURE proc1\n AS\n BEGIN\n -- Get the name of this proc.\n DECLARE @ProcName nvarchar(128);\n SET @ProcName = OBJECT_NAME(@@PROCID);\n -- Pass it to proc3.\n EXEC proc3 @ProcName\n END\n GO\n\n CREATE PROCEDURE proc2\n AS\n BEGIN\n -- Get the name of this proc.\n DECLARE @ProcName nvarchar(128);\n SET @ProcName = OBJECT_NAME(@@PROCID);\n -- Pass it to proc3.\n EXEC proc3 @ProcName\n END\n GO\n"
},
{
"answer_id": 148283,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE Log\n(timestamp dattime, \nspid int, \nprocname varchar(255), \nmessage varchar(255) )\n\n... text of proc ... \nINSERT INTO Log\nSELECT get_date(), @@spid, @currentproc, 'doing something' \n-- you have to define @currentproc in each proc\n\n-- get name of caller\nSELECT @caller = procname \nFROM Log\nWHERE spid = @@spid \nAND timestamp = (SELECT max(timestamp) \n FROM Log \n WHERE timestamp < get_date() \n AND procname != @currentproc ) \n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279/"
] |
148,005
|
<p>In SQL, how do update a table, setting a column to a different value for each row?</p>
<p>I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:</p>
<pre><code>update person set unique_number = (select nextval('number_sequence') );
</code></pre>
<p>but it seems that <em>nextval</em> is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?</p>
|
[
{
"answer_id": 148017,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 6,
"selected": true,
"text": "update person set unique_number = nextval('number_sequence');\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] |
148,024
|
<p>I have got a C function in a static library, let's call it A, with the following interface :</p>
<pre><code>int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z);
</code></pre>
<p>This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C".</p>
<p>Now, here is what stune me : </p>
<ul>
<li>y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666).</li>
<li>when called from a C binary, this function works seamlessly (value
pointed by z is modified).</li>
<li>if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed.</li>
</ul>
<p>I think that the above points show that it is not a stupid mistake with the declaration of my variables. </p>
<p>I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ?
I was thinking about a problem on the C/C++ interface, per instance the way a char* is interpreted.</p>
<p>Edit : I finally found out what was the problem. See below my answer.</p>
|
[
{
"answer_id": 148044,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "extern \"C\""
},
{
"answer_id": 148458,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "z"
},
{
"answer_id": 149641,
"author": "Barth",
"author_id": 20986,
"author_profile": "https://Stackoverflow.com/users/20986",
"pm_score": 2,
"selected": true,
"text": "C++ Lib (M) ---> dyn C++ lib (N) ---> C lib (P) v.1.0\n |\n ------> C lib (P) v.1.1\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
148,039
|
<p>i have a big web application running in perl CGI. It's running ok, it's well written, but as it was done in the past, all the html are defined hardcoded in the CGI calls, so as you could imagine, it's hard to mantain, improve and etc. So now i would like to start to add some templating and integrate with a framework (catalyst or CGI::application). My question is: Somebody here has an experience like that? There is any things that i must pay attention for? I'm aware that with both frameworks i can run native CGI scripts, so it's good because i can run both (CGI native ad "frameworked" code) together without any trauma. Any tips?</p>
|
[
{
"answer_id": 148077,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 4,
"selected": true,
"text": "Test::WWW::Mechanize"
},
{
"answer_id": 152203,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 2,
"selected": false,
"text": "http://app.com/docs/list\nhttp://app.com/docs/view/123\n http://app.com/docs.cgi?action=view&id=123\n Catalyst DBIx::Class"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
148,042
|
<p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
|
[
{
"answer_id": 148048,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt\"\n in in frozenset AwesomeJobs = frozenset([\"mechanic\", \"tech\", ... lots of others ])\ndef func():\n if job in AwesomeJobs:\n print \"awesome\"\n frozenset set"
},
{
"answer_id": 148049,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 1,
"selected": false,
"text": "if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt\"\n"
},
{
"answer_id": 148050,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 1,
"selected": false,
"text": "if job in [ \"mechanic\", \"tech\" ]:\n print \"awesome\"\nelif job in [ \"tool\", \"rock\" ]:\n print \"dolt\"\n"
},
{
"answer_id": 148055,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "if job in [\"mechanic\", \"tech\"]:\n print \"awesome\"\n AwesomeJobs = set([\"mechanic\", \"tech\", ... lots of others ])\n...\n\ndef func():\n if job in AwesomeJobs:\n print \"awesome\"\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
148,056
|
<p>I have created my own Tree implementation for <a href="https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation">various reasons</a> and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised.</p>
<p>In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation.</p>
<p>So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't <em>want</em> to override those methods because they also contained shared logic that shouldn't be duplicated!</p>
<p>The problem can be boiled down to this:</p>
<pre><code>public class Foo {
public String value() { return "foo"; }
public Foo doStuff() {
// Logic logic logic..
return new Foo();
}
}
class Bar extends Foo {
public String value() { return "bar"; }
}
new Bar().doStuff().value(); // returns 'foo', we want 'bar'
</code></pre>
<p>The first thing that popped into my head would have a 'create hook' that extending classes could override:</p>
<pre><code>public Foo createFooHook(/* required parameters */) {
return new Foo();
}
</code></pre>
<p>Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... <em>wrong</em> about it. </p>
<p>It's like cooking while naked-- it feels dangerous and <em>unnecessary</em>.</p>
<p>So, <strong>how would you deal with this situation?</strong></p>
|
[
{
"answer_id": 148122,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 3,
"selected": true,
"text": "Foo abstract class AbstractFoo {\n public String value() { return \"Foo\"; }\n\n public AbstractFoo doStuff() {\n // Logic logic logic\n return hook();\n }\n\n protected abstract AbstractFoo hook();\n}\n\nclass Foo extends AbstractFoo {\n protected AbstractFoo hook() { return new Foo(); }\n}\n\nclass Bar extends AbstractFoo {\n public String value() { return \"Bar\"; }\n\n protected AbstractFoo hook() { return new Bar(); }\n}\n\nnew Bar().doStuff().value(); // Returns 'Bar'!\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
148,057
|
<p>If you have Mathematica code in foo.m, Mathematica can be invoked with <code>-noprompt</code>
and with <code>-initfile foo.m</code>
(or <code>-run "<<foo.m"</code>)
and the command line arguments are available in <code>$CommandLine</code> (with extra junk in there) but is there a way to just have some mathematica code like</p>
<pre><code>#!/usr/bin/env MathKernel
x = 2+2;
Print[x];
Print["There were ", Length[ARGV], " args passed in on the command line."];
linesFromStdin = readList[];
etc.
</code></pre>
<p>and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?</p>
|
[
{
"answer_id": 3484871,
"author": "sakra",
"author_id": 112955,
"author_profile": "https://Stackoverflow.com/users/112955",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\nexec <\"$0\" || exit; read; read; exec /usr/local/bin/math -noprompt \"$@\" | sed '/^$/d'; exit\n(* Mathematica code starts here *)\nx = 2+2;\nPrint[x];\n"
},
{
"answer_id": 7972521,
"author": "mcandre",
"author_id": 350106,
"author_profile": "https://Stackoverflow.com/users/350106",
"pm_score": 3,
"selected": false,
"text": "export PATH=$PATH:/Applications/Mathematica.app/Contents/MacOS\n #!/usr/bin/env MathKernel -script\n $ cat hello.ma\n#!/usr/bin/env MathKernel -script\n\nPrint[\"Hello World!\"]\n\n$ chmod a+x hello.ma\n$ ./hello.ma\n\"Hello World!\"\n"
},
{
"answer_id": 14907902,
"author": "Ivan Lopes",
"author_id": 2074247,
"author_profile": "https://Stackoverflow.com/users/2074247",
"pm_score": 1,
"selected": false,
"text": "$ cat test.m\n#!/bin/bash\nMathKernel -noprompt -run < <( cat $0| sed -e '1,4d' ) | sed '1d'\nexit 0\n### code start Here ... ###\nPrint[\"Hello World!\"]\nX=7\nX*5\n $ chmod +x test.m\n\n$ ./test.m\n\"Hello World!\"\n\n7\n35\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
148,059
|
<p>I'm experimenting with OpenSSL on my network application and I want to test if the data sent is encrypted and can't be seen by eavesdropper.</p>
<p>What tools can you use to check? Could this be done programmatically so it could be placed in a unit test?</p>
|
[
{
"answer_id": 32475440,
"author": "f01",
"author_id": 422842,
"author_profile": "https://Stackoverflow.com/users/422842",
"pm_score": 4,
"selected": false,
"text": "$ openssl s_client -connect mail.prefetch.net:443 -state -nbio 2>&1 | grep \"^SSL\" $ ssldump -a -A -H -i en0 $ ssldump -a -A -H -k rsa.key -i en0 $ ssldump -a -A -H -k rsa.key -i en0 host fred and port 443"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
148,068
|
<p>I'm fairly new to the AJAX methodologies (I only recently discovered <a href="http://jquery.com/" rel="noreferrer">jQuery</a> a short time ago). I am interested to know if there is anyway to authenticate a user on a PHP setup; securely.</p>
<p>Does jQuery have any special options to allow use of HTTPS (or any other way to encrypt my ajax call)?</p>
<p>Yes, I could very well just post data back to the server, but that ruins the fun. :)</p>
|
[
{
"answer_id": 169200,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 2,
"selected": false,
"text": "$_GET"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
] |
148,074
|
<p>Is the sorting algorithm used by .NET's <code>Array.Sort()</code> method a <a href="http://en.wikipedia.org/wiki/Stable_sort#Classification" rel="noreferrer">stable</a> algorithm?</p>
|
[
{
"answer_id": 148123,
"author": "Atif Aziz",
"author_id": 6682,
"author_profile": "https://Stackoverflow.com/users/6682",
"pm_score": 6,
"selected": false,
"text": "Array.Sort Array.Sort using System;\nusing System.Collections.Generic;\n\npublic static class ArrayExtensions {\n\n public static void StableSort<T>(this T[] values, Comparison<T> comparison) {\n var keys = new KeyValuePair<int, T>[values.Length];\n for (var i = 0; i < values.Length; i++)\n keys[i] = new KeyValuePair<int, T>(i, values[i]);\n Array.Sort(keys, values, new StabilizingComparer<T>(comparison));\n }\n\n private sealed class StabilizingComparer<T> : IComparer<KeyValuePair<int, T>> \n {\n private readonly Comparison<T> _comparison;\n\n public StabilizingComparer(Comparison<T> comparison) {\n _comparison = comparison;\n }\n\n public int Compare(KeyValuePair<int, T> x, \n KeyValuePair<int, T> y) {\n var result = _comparison(x.Value, y.Value);\n return result != 0 ? result : x.Key.CompareTo(y.Key);\n }\n }\n}\n StableSort static class Program \n{\n static void Main() \n {\n var unsorted = new[] {\n new Person { BirthYear = 1948, Name = \"Cat Stevens\" },\n new Person { BirthYear = 1955, Name = \"Kevin Costner\" },\n new Person { BirthYear = 1952, Name = \"Vladimir Putin\" },\n new Person { BirthYear = 1955, Name = \"Bill Gates\" },\n new Person { BirthYear = 1948, Name = \"Kathy Bates\" },\n new Person { BirthYear = 1956, Name = \"David Copperfield\" },\n new Person { BirthYear = 1948, Name = \"Jean Reno\" },\n };\n\n Array.ForEach(unsorted, Console.WriteLine);\n\n Console.WriteLine();\n var unstable = (Person[]) unsorted.Clone();\n Array.Sort(unstable, (x, y) => x.BirthYear.CompareTo(y.BirthYear));\n Array.ForEach(unstable, Console.WriteLine);\n\n Console.WriteLine();\n var stable = (Person[]) unsorted.Clone();\n stable.StableSort((x, y) => x.BirthYear.CompareTo(y.BirthYear));\n Array.ForEach(stable, Console.WriteLine);\n }\n}\n\nsealed class Person \n{\n public int BirthYear { get; set; }\n public string Name { get; set; }\n\n public override string ToString() {\n return string.Format(\n \"{{ BirthYear = {0}, Name = {1} }}\", \n BirthYear, Name);\n }\n}\n { BirthYear = 1948, Name = Cat Stevens }\n{ BirthYear = 1955, Name = Kevin Costner }\n{ BirthYear = 1952, Name = Vladimir Putin }\n{ BirthYear = 1955, Name = Bill Gates }\n{ BirthYear = 1948, Name = Kathy Bates }\n{ BirthYear = 1956, Name = David Copperfield }\n{ BirthYear = 1948, Name = Jean Reno }\n\n{ BirthYear = 1948, Name = Jean Reno }\n{ BirthYear = 1948, Name = Kathy Bates }\n{ BirthYear = 1948, Name = Cat Stevens }\n{ BirthYear = 1952, Name = Vladimir Putin }\n{ BirthYear = 1955, Name = Bill Gates }\n{ BirthYear = 1955, Name = Kevin Costner }\n{ BirthYear = 1956, Name = David Copperfield }\n\n{ BirthYear = 1948, Name = Cat Stevens }\n{ BirthYear = 1948, Name = Kathy Bates }\n{ BirthYear = 1948, Name = Jean Reno }\n{ BirthYear = 1952, Name = Vladimir Putin }\n{ BirthYear = 1955, Name = Kevin Costner }\n{ BirthYear = 1955, Name = Bill Gates }\n{ BirthYear = 1956, Name = David Copperfield }\n"
},
{
"answer_id": 14849554,
"author": "halority",
"author_id": 2067637,
"author_profile": "https://Stackoverflow.com/users/2067637",
"pm_score": -1,
"selected": false,
"text": "public static class ComparisonExtensions\n{\n public static Comparison<T> WithGetHashCode<T>(this Comparison<T> current)\n {\n return (x, y) =>\n {\n var result = current(x, y);\n if (result == 0)\n return x.GetHashCode() - y.GetHashCode();\n return result;\n };\n }\n}\n Comparison<Person> comparison = (x, y) => x.BirthYear.CompareTo(y.BirthYear);\nArray.Sort(unstable, comparison.WithGetHashCode());\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] |
148,078
|
<p>I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action.</p>
<p>Let's take an example :</p>
<ol>
<li><p>The timer elapses, so the method is
called. The task could take a few
seconds.</p></li>
<li><p>Right after, the user clicks on some
button, which should trigger the
same task : BAM. It does nothing
since the method is already running.</p></li>
</ol>
<p>I used the following solution :</p>
<pre><code>public void DoRecurentJob()
{
if(!Monitor.TryEnter(this.lockObject))
{
return;
}
try
{
// Do work
}
finally
{
Monitor.Exit(this.lockObject);
}
}
</code></pre>
<p>Where <code>lockObject</code> is declared like that:</p>
<pre><code>private readonly object lockObject = new object();
</code></pre>
<p><strong>Edit</strong> : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static.</p>
<p>Is there a better way to do that ? Or maybe this one is just wrong for any reason ?</p>
|
[
{
"answer_id": 148105,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 2,
"selected": false,
"text": "Mutex Semaphore"
},
{
"answer_id": 148154,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "public class MyClass\n{ \n public void AccessResource()\n {\n OneAtATime(this);\n }\n\n private static void OneAtATime(MyClass instance) \n { \n if( !Monitor.TryEnter(lockObject) )\n // ...\n"
},
{
"answer_id": 148210,
"author": "Kimoz",
"author_id": 7753,
"author_profile": "https://Stackoverflow.com/users/7753",
"pm_score": 2,
"selected": false,
"text": "public class MyClass\n{\n\n // Used as a lock context\n private readonly object myLock = new object();\n\n public void DoSomeWork()\n {\n lock (myLock)\n {\n // Critical code section\n }\n }\n}\n private static readonly object myLock = new object();\n"
},
{
"answer_id": 157252,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 0,
"selected": false,
"text": "[MethodImpl(MethodImplOptions.Synchronized)] \npublic void OneAtATime() { }\n synchronized"
},
{
"answer_id": 44294030,
"author": "shannon",
"author_id": 608220,
"author_profile": "https://Stackoverflow.com/users/608220",
"pm_score": 0,
"selected": false,
"text": "private queued = false;\nprivate running = false;\nprivate object thislock = new object();\n\nvoid Enqueue() {\n queued = true;\n while (Dequeue()) {\n try {\n // do work\n } finally {\n running = false;\n }\n }\n}\n\nbool Dequeue() {\n lock (thislock) {\n if (running || !queued) {\n return false;\n }\n else\n {\n queued = false;\n running = true;\n return true;\n }\n }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
148,084
|
<p>To deploy a new version of our website we do the following:</p>
<ol>
<li>Zip up the new code, and upload it to the server.</li>
<li>On the live server, delete all the live code from the IIS website directory.</li>
<li>Extract the new code zipfile into the now empty IIS directory</li>
</ol>
<p>This process is all scripted, and happens quite quickly, but there can still be a 10-20 second downtime when the old files are being deleted, and the new files being deployed.</p>
<p>Any suggestions on a 0 second downtime method?</p>
|
[
{
"answer_id": 22250245,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 1,
"selected": false,
"text": "try\n Web-Service: Tell all applications on all web-servers to go into primary read-only mode \n Application switch to primary read-only mode, and responds \n Web sockets begin notifying all clients \n Wait for all applications to respond\n\n wait (custom short interval)\n\n Web-Service: Tell all applications on all web-servers to go into secondary read-only mode \n Application switch to secondary read-only mode (data-entry fuse)\n Updatedb - secondary read-only mode (switches database to read-only)\n\n Web-Service: Create backup of database \n Web-Service: Restore backup to new database\n Web-Service: Update new database with new schema \n\n Deploy new application to apt-repository \n (for windows, you will have to write your own custom deployment web-service)\n ssh into every machine in array_of_new_webapps\n run apt-get update\n then either \n apt-get dist-upgrade\n OR\n apt-get install <packagename>\n OR \n apt-get install --only-upgrade <packagename>\n depending on what you need\n -- This deploys the new application to all new chroots (or servers/VMs)\n\n Test: Test new application under test.domain.xxx\n -- everything that fails should throw an exception here\n commit myupdate;\n\n Web-Service: Tell all applications to send web-socket request to reload the pages to all clients at time x (+/- random number)\n @client: notify of reload and that this causes loss of unsafed data, with option to abort \n\n @ time x: Switch load balancer from array_of_old_webapps to array_of_new_webapps \n Decomission/Recycle array_of_old_webapps, etc.\n\ncatch\n rollback myupdate \n switch to read-write mode\n Web-Service: Tell all applications to send web-socket request to unblock read-only mode\nend try \n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23393/"
] |
148,086
|
<p>Is there any simple way to programatically colorize images in .NET? Basically we have a black and white image and need to put a layer of say pink above it and reduce the opacity of that layer to make the picture colorized in pink.</p>
|
[
{
"answer_id": 148126,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "RenderTargetBitmap bmp = new RenderTargetBitmap( imageWidth,imageHeight, \n DPIHoriz, DPIVert, \n PixelFormats.Pbrga32);\n // if you don't want to make the controls 'visible' on screen, you need to trigger size calculations explicitly. \ngrid.Measure(new Size(imageWidth, imageHeight));\ngrid.Arrange(new Rect(0,0, imageWidth, imageHeight);\nbmp.Render(grid);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
] |
148,097
|
<p>In IIS 6, I can use the Web Service Extensions folder in Inetmgr to allow/prohibit isapi filters, such as ASP.net. I want to be able to do this programmatically (in particular, from an installer script/exe).</p>
<p><img src="https://i56.photobucket.com/albums/g192/assaflavie/misc/iis.png?t=1222681203" alt="alt text"></p>
<p>Any ideas?</p>
|
[
{
"answer_id": 148126,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "RenderTargetBitmap bmp = new RenderTargetBitmap( imageWidth,imageHeight, \n DPIHoriz, DPIVert, \n PixelFormats.Pbrga32);\n // if you don't want to make the controls 'visible' on screen, you need to trigger size calculations explicitly. \ngrid.Measure(new Size(imageWidth, imageHeight));\ngrid.Arrange(new Rect(0,0, imageWidth, imageHeight);\nbmp.Render(grid);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
] |
148,116
|
<p>So, In a Flex app I add a new GUI component by creating it and calling <code>parent.addChild()</code>. However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does:</p>
<pre><code>return addChildAt(child, numChildren);
</code></pre>
<p>In the cases where it breaks, somehow the numChildren is off by one. Leading to this error:</p>
<blockquote>
<p>RangeError: Error #2006: The supplied
index is out of bounds. at
flash.display::DisplayObjectContainer/addChildAt()
at
mx.core::Container/addChildAt()
at
mx.core::Container/addChild()
. . at
flash.events::EventDispatcher/dispatchEventFunction()
at
flash.events::EventDispatcher/dispatchEvent()
at
mx.core::UIComponent/dispatchEvent()
at
mx.controls::SWFLoader::contentLoaderInfo_completeEventHandler()</p>
</blockquote>
<p>Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.</p>
|
[
{
"answer_id": 8670817,
"author": "Paul",
"author_id": 2592338,
"author_profile": "https://Stackoverflow.com/users/2592338",
"pm_score": 0,
"selected": false,
"text": "var myDisplay : DisplayObject = new DisplayObject();\n\nmyDisplay.addChild(myChild1);\nmyDisplay.addChild(myChild2);\nmyDisplay.addChild(myChild3);\nmyDisplay.addChild(myChild4);\n\nScrollPane.source = myDisplay;\nScrollPane.update();\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
148,129
|
<p>I'm trying to find out whether I should be using business critical logic in a trigger or constraint inside of my database.<br>
So far I've added logic in triggers as it gives me the control over what happens next and means I can provide custom user messages instead of an error that will probably confuse the users.</p>
<p>Is there any noticable performance gain in using constraints over triggers and what are the best practices for determining which to use.</p>
|
[
{
"answer_id": 285721,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 3,
"selected": false,
"text": "(Amount >= 0) WHERE (Amount = -5)"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
148,130
|
<p>Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?</p>
<p><strong>Answer</strong> - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.</p>
|
[
{
"answer_id": 148135,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 7,
"selected": true,
"text": "BufferedInputStream bis = new BufferedInputStream(inputStream);\nbis.mark(2);\nint byte1 = bis.read();\nint byte2 = bis.read();\nbis.reset();\n// note: you must continue using the BufferedInputStream instead of the inputStream\n"
},
{
"answer_id": 148138,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 2,
"selected": false,
"text": "package com.heatonresearch.httprecipes.html;\n\nimport java.io.*;\n\n/**\n * The Heaton Research Spider Copyright 2007 by Heaton\n * Research, Inc.\n * \n * HTTP Programming Recipes for Java ISBN: 0-9773206-6-9\n * http://www.heatonresearch.com/articles/series/16/\n * \n * PeekableInputStream: This is a special input stream that\n * allows the program to peek one or more characters ahead\n * in the file.\n * \n * This class is released under the:\n * GNU Lesser General Public License (LGPL)\n * http://www.gnu.org/copyleft/lesser.html\n * \n * @author Jeff Heaton\n * @version 1.1\n */\npublic class PeekableInputStream extends InputStream\n{\n\n /**\n * The underlying stream.\n */\n private InputStream stream;\n\n /**\n * Bytes that have been peeked at.\n */\n private byte peekBytes[];\n\n /**\n * How many bytes have been peeked at.\n */\n private int peekLength;\n\n /**\n * The constructor accepts an InputStream to setup the\n * object.\n * \n * @param is\n * The InputStream to parse.\n */\n public PeekableInputStream(InputStream is)\n {\n this.stream = is;\n this.peekBytes = new byte[10];\n this.peekLength = 0;\n }\n\n /**\n * Peek at the next character from the stream.\n * \n * @return The next character.\n * @throws IOException\n * If an I/O exception occurs.\n */\n public int peek() throws IOException\n {\n return peek(0);\n }\n\n /**\n * Peek at a specified depth.\n * \n * @param depth\n * The depth to check.\n * @return The character peeked at.\n * @throws IOException\n * If an I/O exception occurs.\n */\n public int peek(int depth) throws IOException\n {\n // does the size of the peek buffer need to be extended?\n if (this.peekBytes.length <= depth)\n {\n byte temp[] = new byte[depth + 10];\n for (int i = 0; i < this.peekBytes.length; i++)\n {\n temp[i] = this.peekBytes[i];\n }\n this.peekBytes = temp;\n }\n\n // does more data need to be read?\n if (depth >= this.peekLength)\n {\n int offset = this.peekLength;\n int length = (depth - this.peekLength) + 1;\n int lengthRead = this.stream.read(this.peekBytes, offset, length);\n\n if (lengthRead == -1)\n {\n return -1;\n }\n\n this.peekLength = depth + 1;\n }\n\n return this.peekBytes[depth];\n }\n\n /*\n * Read a single byte from the stream. @throws IOException\n * If an I/O exception occurs. @return The character that\n * was read from the stream.\n */\n @Override\n public int read() throws IOException\n {\n if (this.peekLength == 0)\n {\n return this.stream.read();\n }\n\n int result = this.peekBytes[0];\n this.peekLength--;\n for (int i = 0; i < this.peekLength; i++)\n {\n this.peekBytes[i] = this.peekBytes[i + 1];\n }\n\n return result;\n }\n\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
148,136
|
<p>I'm currently generating SQL insert statements from more than one tables, and in the generated data I need to use a CASE statement, like this:</p>
<pre><code>select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values ('
||t.f1||','
||CASE
WHEN t.f2 > 0 THEN '1'
ELSE '0'
END CASE
from table2 t , table3 t3
</code></pre>
<p>But at this point if I want to continue my statement with <code>... END CASE||','|| ....</code> I can't run the query anymore, as TOAD complains about not finding the FROM keyword.</p>
<p>A quick solution was to separate the ouput into fields, then save it to text, and edit, but there must be a better way.</p>
|
[
{
"answer_id": 148159,
"author": "pablo",
"author_id": 16112,
"author_profile": "https://Stackoverflow.com/users/16112",
"pm_score": 3,
"selected": true,
"text": "select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values ('\n ||t.f1||','\n ||CASE\n WHEN t.f2 > 0 THEN '1'\n ELSE '0'\n END||','||t.f2\n from table2 t , table3 t3\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11621/"
] |
148,143
|
<p>When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open?</p>
|
[
{
"answer_id": 148242,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 0,
"selected": false,
"text": "Ctrl+F4"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11559/"
] |
148,157
|
<p>I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. </p>
<p>I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case.
Both activities have the same correlation token (modification) and the same owner (the owning state).
Has anybody an idea why the link is not removed and how to remove the modification link?</p>
<p>Thank you in advance, Stefan!</p>
|
[
{
"answer_id": 148242,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 0,
"selected": false,
"text": "Ctrl+F4"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21729/"
] |
148,161
|
<p>I'm using Zend Studio for Eclipse (Linux), and I'm trying to generate getter and setters methods in a PHP class.</p>
<p>I try to do this: <a href="http://files.zend.com/help/Zend-Studio-Eclipse-Help/creating_getters_and_setters.htm" rel="nofollow noreferrer">http://files.zend.com/help/Zend-Studio-Eclipse-Help/creating_getters_and_setters.htm</a>
but I haven't "Generate Getters and Setters" option in Source Menu, it's missed!</p>
<p>Could u help me? Thanks!</p>
|
[
{
"answer_id": 148627,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 2,
"selected": false,
"text": "/**\n * @var ${PropertyType} \n */\nprivate $$m${PropertyName};\n${cursor}\n\n/**\n * Getter for ${PropertyName}\n *\n * @author ${user}\n * @since ${date} ${time}\n * @return ${PropertyType} private variable $$m_${PropertyName}\n */\npublic function get${PropertyName}() \n{\n return $$this->m_${PropertyName};\n}\n\n/**\n * Setter for ${PropertyName}\n *\n * @author ${user}\n * @since ${date} ${time}\n * @param ${PropertyType} $$Value\n*/\npublic function set${PropertyName}($$Value) \n{\n $$this->m_${PropertyName} = $$Value;\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
148,169
|
<p>Given : </p>
<blockquote>
<p>Group hasMany Persons</p>
</blockquote>
<p>but the relationship is independent (ie. Persons can exist without belonging to a Group), should the foreign key in the persons' table (ie group_id) be set to 0 (or NULL) when deleting a group? If you do not, the person will try to belong to a group that doesn't exist. </p>
<p>The reason I ask is that this is the default behavior in Cakephp. If you set dependent to true, it will delete the associated models, but if it's set to false it will leave the associated model untouched.</p>
|
[
{
"answer_id": 22261149,
"author": "Big D",
"author_id": 2141112,
"author_profile": "https://Stackoverflow.com/users/2141112",
"pm_score": 0,
"selected": false,
"text": "id, group_id, person_id\n Person hasMany GroupPerson\nGroup hasMany GroupPerson\nGroupPerson belongsTo Person, Group\n var $validate=array(\n 'person_id'=>array(\n array(\n 'rule'=>'isUnique',\n 'message'=>'This person is already in a group.'\n )\n )\n);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] |
148,178
|
<p>I've got a really odd error message that only occurs when I add the following line to my project:</p>
<pre><code>std::list<CRect> myVar;
</code></pre>
<p>It's worth noting that it doesn't have to be a std::list, it can be std::vector or any other STL container I assume.</p>
<p>Here is the error message:</p>
<blockquote>
<p>Error 1 error LNK2005: "public:
__thiscall std::list</p>
<blockquote>
<p>::list >(void)"
(??0?$list@VCRect@@V?$allocator@VCRect@@@std@@@std@@QAE@XZ)
already defined in
SomeLowLevelLibrary.lib</p>
</blockquote>
</blockquote>
<p>The low level library that's referenced in the error message has no idea about the project I am building, it only has core low level functionality and doesn't deal with high level MFC GUIs.</p>
<p>I can get the linker error to go away if I change the line of code to:</p>
<pre><code>std::list<CRect*> myVar;
</code></pre>
<p>But I don't want to hack it for the sake of it.</p>
<p>Also, it doesn't matter if I create the variable on the stack or the heap, I still get the same error.</p>
<p>Does anyone have any ideas whatsoever about this?
I'm using Microsoft Visual Studio 2008 SP1 on Vista Enterprise.</p>
<p><strong>Edit:</strong> The linker error above is for the std::list<> constructor, I also get an error for the destructor, _Nextnode and clear functions.</p>
<p><strong>Edit:</strong> In other files in the project, std::vector won't link, in other files it might be std::list. I can't work out why some containers work, and some don't. MFC linkage is static across both libraries. In the low level library we have 1 class that inherits from std::list.</p>
<p><strong>Edit:</strong> The low level library doesn't have any classes that inherit from CRect, but it does make use of STL.</p>
|
[
{
"answer_id": 1612595,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": true,
"text": "class LIB_EXPORT CRectList : public std::list<CRect>\n{\n};\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
148,182
|
<p>I've been searching and can't find the download files on opengl.org. can someone please point me to the right direction?</p>
|
[
{
"answer_id": 148212,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "#include <windows.h> \n#include <GL/gl.h> \n#include <GL/glu.h> \n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618/"
] |
148,185
|
<p>C++ preprocessor <code>#define</code> is totally different.</p>
<p>Is the PHP <code>define()</code> any different than just creating a var?</p>
<pre><code>define("SETTING", 0);
$something = SETTING;
</code></pre>
<p>vs</p>
<pre><code>$setting = 0;
$something = $setting;
</code></pre>
|
[
{
"answer_id": 1844206,
"author": "JAL",
"author_id": 92448,
"author_profile": "https://Stackoverflow.com/users/92448",
"pm_score": 3,
"selected": false,
"text": "php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f.\"\\n\";\n php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f.\"\\n\";\n"
},
{
"answer_id": 10098634,
"author": "gcb",
"author_id": 183132,
"author_profile": "https://Stackoverflow.com/users/183132",
"pm_score": 2,
"selected": false,
"text": "true 0.65ms\n$true 0.69ms (1)\n$config['true'] 0.87ms\nTRUE_CONST 1.28ms (2)\ntrue 0.65ms\ndefined('TRUE_CONST') 2.06ms (3)\ndefined('UNDEF_CONST') 12.34ms (4)\nisset($config['def_key']) 0.91ms (5)\nisset($config['undef_key']) 0.79ms\nisset($empty_hash[$good_key]) 0.78ms\nisset($small_hash[$good_key]) 0.86ms\nisset($big_hash[$good_key]) 0.89ms\nisset($small_hash[$bad_key]) 0.78ms\nisset($big_hash[$bad_key]) 0.80ms\n"
},
{
"answer_id": 61856900,
"author": "cory marsh",
"author_id": 13562446,
"author_profile": "https://Stackoverflow.com/users/13562446",
"pm_score": 0,
"selected": false,
"text": "$loops = 90000;\n$m0 = microtime(true);\nfor ($i=0; $i<$loops; $i++) {\n define(\"FOO$i\", true);\n}\n$m1 = microtime(true);\necho \"Define new const {$loops}s: (\" . ($m1-$m0) . \")\\n\";\n// etc...\n Define new const 90000s: (0.012847185134888)\nDefine same const 90000s: (0.89289903640747)\nDefine same super global 90000s: (0.0010528564453125)\nDefine new super global 90000s: (0.0080759525299072)\ncheck same undefined 90000s: (0.0021710395812988)\ncheck same defined 90000s: (0.00087404251098633)\ncheck different defined 90000s: (0.0076708793640137)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21240/"
] |
148,190
|
<p>I have a legacy VB6 application that was built using MSDE.</p>
<p>As many client's database grow towards the MSDE 2 GB limit they are upgraded to SQL 2005 Express.</p>
<p>This has proven very successful until today.</p>
<p>I have spent the entire day troubleshooting a client's network on which our application runs unacceptably slowly, when connecting the a SQL 2005 Express named instance across the "network". </p>
<p>I say "network" because it is only two XP SP2 machines - there is no dedicated server here. No AD.</p>
<p>In trying to isolate this problem I have installed SQL 2005 Express on both machines and placed copies of our database on both machines. I have even completely reinstalled our application using the SQL2005 Express install routine we now have. It makes no difference whether I restore an old MSDE database or use a newly created SQL 2005 Express one.</p>
<p>When running our application and connecting to either machine's local server performance is fine. Once you connect our application on either PC to the server on the other PC, it is unworkably slow. (Regardless of the combination).</p>
<p>Now, I have rebuilt statistics (exec sp_updatestats), rebuilt ALL indexes, disabled (temporarily) firewalls and virus software and clutched and countless other straws.</p>
<p>I have resorted to running FileMon and ProcessMon on both machines and have even written a little test application to simply connect and query a table in the database. It too runs slowly - (takes about 5 - 6 seconds to connect).</p>
<p>The monitors (File and Process) show delays when SQL Server is writing to a log file (c:\program files\microsoft sql server\mssql.1\log files\log_12.trc).</p>
<p>Other tools though, like SQL Management Studio Express and even SSEUtil (a SQL Server Express Diagnostic Utility I found) run perfectly when connecting from the client to the server. Queries (even large ones) run as you would expect.</p>
<p>I feel sure this problem is environmental as we have so many sites running what would appear to be the same setup, with no such problems.</p>
<p>Can someone tell me what I should be doing to isolate this problem or even offer any clues or suggestions that could help solve this?</p>
|
[
{
"answer_id": 1844206,
"author": "JAL",
"author_id": 92448,
"author_profile": "https://Stackoverflow.com/users/92448",
"pm_score": 3,
"selected": false,
"text": "php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f.\"\\n\";\n php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f.\"\\n\";\n"
},
{
"answer_id": 10098634,
"author": "gcb",
"author_id": 183132,
"author_profile": "https://Stackoverflow.com/users/183132",
"pm_score": 2,
"selected": false,
"text": "true 0.65ms\n$true 0.69ms (1)\n$config['true'] 0.87ms\nTRUE_CONST 1.28ms (2)\ntrue 0.65ms\ndefined('TRUE_CONST') 2.06ms (3)\ndefined('UNDEF_CONST') 12.34ms (4)\nisset($config['def_key']) 0.91ms (5)\nisset($config['undef_key']) 0.79ms\nisset($empty_hash[$good_key]) 0.78ms\nisset($small_hash[$good_key]) 0.86ms\nisset($big_hash[$good_key]) 0.89ms\nisset($small_hash[$bad_key]) 0.78ms\nisset($big_hash[$bad_key]) 0.80ms\n"
},
{
"answer_id": 61856900,
"author": "cory marsh",
"author_id": 13562446,
"author_profile": "https://Stackoverflow.com/users/13562446",
"pm_score": 0,
"selected": false,
"text": "$loops = 90000;\n$m0 = microtime(true);\nfor ($i=0; $i<$loops; $i++) {\n define(\"FOO$i\", true);\n}\n$m1 = microtime(true);\necho \"Define new const {$loops}s: (\" . ($m1-$m0) . \")\\n\";\n// etc...\n Define new const 90000s: (0.012847185134888)\nDefine same const 90000s: (0.89289903640747)\nDefine same super global 90000s: (0.0010528564453125)\nDefine new super global 90000s: (0.0080759525299072)\ncheck same undefined 90000s: (0.0021710395812988)\ncheck same defined 90000s: (0.00087404251098633)\ncheck different defined 90000s: (0.0076708793640137)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] |
148,202
|
<p>Microsoft <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" rel="nofollow noreferrer">recently announced</a> that the Javascript/HTML DOM library <strong>jQuery will be integrated</strong> into the ASP.NET MVC framework and into ASP.NET / Visual Studio.</p>
<p>What is the best practice or strategy adopting jQuery using <strong>ASP.NET 2.0</strong>? I'd like to prepare a large, existing ASP.NET Web Application (<strong>not</strong> MVC) for jQuery. How would I deal with versioning and related issues?</p>
<p>Are the any caveats integrating jQuery and <strong>ASP.NET Ajax</strong>? Or <strong>3rd party components</strong> like Telerik or Intersoft controls?</p>
|
[
{
"answer_id": 148301,
"author": "paudirac",
"author_id": 15554,
"author_profile": "https://Stackoverflow.com/users/15554",
"pm_score": 3,
"selected": true,
"text": "\n$(function() {\n // some actions\n});\n \nif (Sys.WebForms.PageRequestManager) {\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() {\n $('#updateListView1').trigger(\"gridLoaded\");\n });\n}\n gridLoaded $(document).ready"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
148,204
|
<p>last time I asked how to populate a data structure <a href="https://stackoverflow.com/questions/144474/java-arrays-vectors">here</a>. Now I would like to know if there's something in Java, like the <a href="http://www.php.net/print_r" rel="nofollow noreferrer">print_r</a> I use in PHP, to represent what I have populated in the Maps and lists without having to do my own algorithm.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 148221,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 4,
"selected": true,
"text": "toString toString"
},
{
"answer_id": 148238,
"author": "DeeCee",
"author_id": 5895,
"author_profile": "https://Stackoverflow.com/users/5895",
"pm_score": 0,
"selected": false,
"text": "List <String> list = …; // fills your list \n\n// print each list element \n\nfor (String s : list) {\n\n System.out.println(s);\n\n }\n"
},
{
"answer_id": 149072,
"author": "jm4",
"author_id": 20441,
"author_profile": "https://Stackoverflow.com/users/20441",
"pm_score": 2,
"selected": false,
"text": "toString() toString() java.lang.Object@1b9240e toString() print_r"
},
{
"answer_id": 151082,
"author": "laz",
"author_id": 8753,
"author_profile": "https://Stackoverflow.com/users/8753",
"pm_score": 3,
"selected": false,
"text": " // Output a list\n final List<String> list = new ArrayList<String>();\n list.add(\"one\");\n list.add(\"two\");\n list.add(\"three\");\n list.add(\"four\");\n System.out.println(list);\n\n // Output an array\n final String[] array = {\"four\", \"three\", \"two\", \"one\"};\n System.out.println(Arrays.asList(array));\n\n // Output a map\n final Map<String, String> map = new HashMap<String, String>();\n map.put(\"one\", \"value\");\n map.put(\"two\", \"value\");\n map.put(\"three\", \"value\");\n System.out.println(map.entrySet());\n"
},
{
"answer_id": 5962071,
"author": "darpet",
"author_id": 312741,
"author_profile": "https://Stackoverflow.com/users/312741",
"pm_score": 3,
"selected": false,
"text": "int firstParameter = 0;\nB secondObject = new B();\n String myName = \"this is my name\"; \n"
},
{
"answer_id": 7892282,
"author": "stivlo",
"author_id": 445543,
"author_profile": "https://Stackoverflow.com/users/445543",
"pm_score": 2,
"selected": false,
"text": "print_r String output = RecursiveDump.dump(...);\n toString() toString() toString()"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] |
148,225
|
<p>Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.</p>
<p>Particular order doesn't matter much here.</p>
<p>I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.</p>
|
[
{
"answer_id": 148230,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "#include <stdint.h>\n#include <stdio.h>\n\nunion ui64 {\n uint64_t one;\n uint16_t four[4];\n};\n\nint\nmain()\n{\n union ui64 number = {0x123456789abcdef0};\n printf(\"%x %x %x %x\\n\", number.four[0], number.four[1],\n number.four[2], number.four[3]);\n return 0;\n}\n"
},
{
"answer_id": 148232,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "union LongLongIntToThreeUnsignedShorts {\n long long int long_long_int;\n unsigned short int short_ints[sizeof(long long int) / sizeof(short int)];\n};\n"
},
{
"answer_id": 148235,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "(unsigned short)((((unsigned long long int)value)>>(x))&(0xFFFF))\n value long long int x"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
148,239
|
<p>I am am trying to load a SQL table from a flat file. The flat i am talking about is a comma separated file. This has all the data required to populate a table will each column separated by a comma ",". I need some way by which i can load this content into the table faster.</p>
|
[
{
"answer_id": 148246,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": true,
"text": "BULK INSERT"
},
{
"answer_id": 148292,
"author": "Jean Paul Galea",
"author_id": 6618,
"author_profile": "https://Stackoverflow.com/users/6618",
"pm_score": 1,
"selected": false,
"text": "mysqldump -u username -p database_name < sql_file.sql\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
148,251
|
<p>My favorite equation for centering an xhtml element using only CSS is as follows:</p>
<pre><code>display: block;
position: absolute;
width: _insert width here_;
left: 50%;
margin-left: _insert width divided by two & multiplied by negative one here_
</code></pre>
<p>There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)</p>
<p>edit - oops, forgot the 'negative' part of one in the margin-left. fixed.</p>
|
[
{
"answer_id": 148265,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": false,
"text": "text-align:center; margin:auto; <div style=\"text-align:center\">\n <div style=\"width:30px; margin:auto; text-align:left\">\n <!-- this div is sitting in the middle of the other -->\n </div>\n</div>\n"
},
{
"answer_id": 148274,
"author": "Ris Adams",
"author_id": 15683,
"author_profile": "https://Stackoverflow.com/users/15683",
"pm_score": 4,
"selected": false,
"text": "div #centered{\n margin: 0 auto;\n}\n"
},
{
"answer_id": 148339,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": -1,
"selected": false,
"text": "<html>\n<head>\n<title>Center Example</title>\n<style>\n.center {\n clear:both;\n width:100%;\n overflow:hidden;\n position:relative;\n}\n.center .helper {\n float:left;\n position:relative;\n left:50%;\n}\n.center .helper .content {\n float:left;\n position:relative;\n right:50%;\n border:thin solid red;\n}\n</style>\n</head>\n<body>\n<div class=\"center\">\n <div class=\"helper\">\n <div class=\"content\">Centered on the page<br>and left aligned!</div>\n </div>\n</div>\n</body>\n</html> \n"
},
{
"answer_id": 148491,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": -1,
"selected": false,
"text": "body {\n text-align: center;\n}\n#container {\n width: 770px;\n margin: 0 auto;\n text-align: left;\n}\n margin: 0 auto;"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14026/"
] |
148,275
|
<p>I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this?</p>
<p>I am using Managed DX with C#.</p>
|
[
{
"answer_id": 152297,
"author": "Garth",
"author_id": 23407,
"author_profile": "https://Stackoverflow.com/users/23407",
"pm_score": 4,
"selected": true,
"text": "//this will allow you to import the necessary functions from the .dll\nusing System.Runtime.InteropServices;\n\n//this imports the function used to extend the transparent window border.\n[DllImport(\"dwmapi.dll\")]\nstatic extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);\n\n//this is used to specify the boundaries of the transparent area\ninternal struct Margins {\n public int Left, Right, Top, Bottom;\n}\nprivate Margins marg;\n\n//Do this every time the form is resized. It causes the window to be made transparent.\nmarg.Left = 0;\nmarg.Top = 0;\nmarg.Right = this.Width;\nmarg.Bottom = this.Height;\nDwmExtendFrameIntoClientArea(this.Handle, ref marg);\n\n//This initializes the DirectX device. It needs to be done once.\n//The alpha channel in the backbuffer is critical.\nPresentParameters presentParameters = new PresentParameters();\npresentParameters.Windowed = true;\npresentParameters.SwapEffect = SwapEffect.Discard;\npresentParameters.BackBufferFormat = Format.A8R8G8B8;\n\nDevice device = new Device(0, DeviceType.Hardware, this.Handle,\nCreateFlags.HardwareVertexProcessing, presentParameters);\n\n//the OnPaint functions maked the background transparent by drawing black on it.\n//For whatever reason this results in transparency.\nprotected override void OnPaint(PaintEventArgs e) {\n Graphics g = e.Graphics;\n\n // black brush for Alpha transparency\n SolidBrush blackBrush = new SolidBrush(Color.Black);\n g.FillRectangle(blackBrush, 0, 0, Width, Height);\n blackBrush.Dispose();\n\n //call your DirectX rendering function here\n}\n\n//this is the dx rendering function. The Argb clearing function is important,\n//as it makes the directx background transparent.\nprotected void dxrendering() {\n device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0);\n\n device.BeginScene();\n //draw stuff here.\n device.EndScene();\n device.Present();\n}\n"
},
{
"answer_id": 28009960,
"author": "thewhiteambit",
"author_id": 2042691,
"author_profile": "https://Stackoverflow.com/users/2042691",
"pm_score": 3,
"selected": false,
"text": "SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);\nCOLORREF color = 0;\nBYTE alpha = 128;\nSetLayeredWindowAttributes(hWnd, color, alpha, LWA_ALPHA);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23407/"
] |
148,281
|
<p>The output we get when printing C++ sources from Eclipse is rather ugly. </p>
<p>Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?</p>
|
[
{
"answer_id": 150158,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": true,
"text": "enscript enscript"
},
{
"answer_id": 14266862,
"author": "William Symionow",
"author_id": 1683291,
"author_profile": "https://Stackoverflow.com/users/1683291",
"pm_score": 0,
"selected": false,
"text": " MinGw-get.exe install gdb-python\n PYTHONPATH should be C:\\Python27\\Lib (or similar)\n PYTHONHOME should be C:\\Python27\n %PYTHONHOME%;...\n python\nimport sys\nsys.path.insert(0, 'C:/MinGW/share/gcc-4.6.1/python') \nfrom libstdcxx.v6.printers import register_libstdcxx_printers\nregister_libstdcxx_printers (None)\nend\n C:\\MinGW\\bin\\gdb-python27.exe .gdbinit --OR--\n 835,059 4^done\n835,059 (gdb) \n835,059 5-enable-pretty-printing\n835,069 5^done\n....\n835,129 12^done\n835,129 (gdb) \n835,129 13source C:\\MinGW\\bin\\.gdbinit\n835,139 &\"source C:\\\\MinGW\\\\bin\\\\.gdbinit\\n\"\n835,142 13^done\n835,142 (gdb) \n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19734/"
] |
148,298
|
<p>Okay, we know that the following two lines are equivalent - </p>
<ol>
<li><code>(0 == i)</code></li>
<li><code>(i == 0)</code></li>
</ol>
<p>Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.</p>
<p>My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? </p>
<p>In particular, this question popped into my mind when I saw the following code - </p>
<pre><code>if(DialogResult.OK == MessageBox.Show("Message")) ...
</code></pre>
<p>In my opinion, I would never recommend the above. Any second opinions?</p>
|
[
{
"answer_id": 148311,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 4,
"selected": false,
"text": "if (InterstingValue1 == foo) { } else\nif (InterstingValue2 == foo) { } else\nif (InterstingValue3 == foo) { }\n if (\"SomeValue\".equals(someString)) {\n}\n"
},
{
"answer_id": 148317,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 0,
"selected": false,
"text": "if (i = 0) {\n}\n"
},
{
"answer_id": 148357,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "if(DialogResult.OK == MessageBox.Show(\"Message\"))\n"
},
{
"answer_id": 148433,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 0,
"selected": false,
"text": ":1 -> x\n :if(1=x)\n"
},
{
"answer_id": 148574,
"author": "Rob Gilliam",
"author_id": 23408,
"author_profile": "https://Stackoverflow.com/users/23408",
"pm_score": 1,
"selected": false,
"text": "if (DateClass.SATURDAY == dateObject.getDayOfWeek())\n"
},
{
"answer_id": 999657,
"author": "Sean Reilly",
"author_id": 8313,
"author_profile": "https://Stackoverflow.com/users/8313",
"pm_score": -1,
"selected": false,
"text": "if(DialogResult.OK == MessageBox.Show(\"Message\")) ...\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621/"
] |
148,305
|
<p>I'm working on a SaaS application where each customer will have different configurations depending on the edition they have purchased, additional features they have purchased, etc. For example, a customer might have a limit of 3 custom reports.</p>
<p>Obviously I want to store this configuration in the database, but I am unsure of the best approach. We want to be able to add additional features in the future without requiring a change to the database schema, so a single table with a column per configuration option isn't sensible.</p>
<p>Possible options are a table with one entry per customer, with an XML field containing the entire configuration for that customer, but that adds complexity when the XML schema changes to add additional features.</p>
<p>We could use a table with key value pairs, and store all configuration settings as strings and then parse to the correct data type, but that seems a bit of a cludge, as does having a seperate table for string config options, integer config options, etc.</p>
<p>Is there a good pattern for this type of scenario which people are using?</p>
|
[
{
"answer_id": 148331,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)\n"
},
{
"answer_id": 160207,
"author": "Simurr",
"author_id": 3478,
"author_profile": "https://Stackoverflow.com/users/3478",
"pm_score": 3,
"selected": true,
"text": "PACKAGE 1 -> 3 reports, date entry, some other stuff.\nPACKAGE 2 -> 6 reports, more stuff\nPACKAGE 3 -> 12 reports, almost all the stuff\nUBER PACKAGE -> everything\n Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon.\n Create a table with all the product features.\nCreate a link table for customers and the features they want.\nIn that link table add an additional field for modification if needed.\n customer_id (pk)\n module_id (pk)\nmodule_name (reports!)\n module_id (pk) (fk -> modules)\ncustomer_id (pk) (fk -> customers)\ncustomization (configuration file or somesuch?)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4048/"
] |
148,314
|
<p>I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.</p>
<p>The issue is that the Portal Theme does not get reflected on these services after integration.</p>
<p>When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.</p>
<p>I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.</p>
<p>Whch property should i change to remove the blue colour.</p>
|
[
{
"answer_id": 148331,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)\n"
},
{
"answer_id": 160207,
"author": "Simurr",
"author_id": 3478,
"author_profile": "https://Stackoverflow.com/users/3478",
"pm_score": 3,
"selected": true,
"text": "PACKAGE 1 -> 3 reports, date entry, some other stuff.\nPACKAGE 2 -> 6 reports, more stuff\nPACKAGE 3 -> 12 reports, almost all the stuff\nUBER PACKAGE -> everything\n Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon.\n Create a table with all the product features.\nCreate a link table for customers and the features they want.\nIn that link table add an additional field for modification if needed.\n customer_id (pk)\n module_id (pk)\nmodule_name (reports!)\n module_id (pk) (fk -> modules)\ncustomer_id (pk) (fk -> customers)\ncustomization (configuration file or somesuch?)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
148,350
|
<p>I want to be able to access custom URLs with apache httpclient. Something like this:</p>
<pre><code>HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("media:///squishy.jpg");
int statusCode = client.executeMethod(method);
</code></pre>
<p>Can I somehow register a custom URL handler? Or should I just register one with Java, using</p>
<pre><code>URL.setURLStreamHandlerFactory(...)
</code></pre>
<p>Regards.</p>
|
[
{
"answer_id": 148390,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 1,
"selected": true,
"text": "URL.setURLStreamHandlerFactory(...)\n"
},
{
"answer_id": 148392,
"author": "mitchnull",
"author_id": 18645,
"author_profile": "https://Stackoverflow.com/users/18645",
"pm_score": 1,
"selected": false,
"text": " org.apache.commons.httpclient.protocol.Protocol.registerProtocol(\"ss-https\", \n new Protocol(\"ss-https\",\n (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443));\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11384/"
] |
148,361
|
<p>I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events.</p>
<p>Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus?</p>
<p>Here's a simplified sample to illustrate the problem:</p>
<pre><code><html>
<head>
</head>
<body>
<div id="outer" style="background-color:#eeeeee;padding:10px">
outer
<div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;">
want to be able to focus this element and pick up keypresses
</div>
</div>
<script language="Javascript">
function onClick()
{
document.getElementById('inner').innerHTML="clicked";
document.getElementById('inner').focus();
}
//this handler is never called
function onKeypressDiv()
{
document.getElementById('inner').innerHTML="keypress on div";
}
function onKeypressDoc()
{
document.getElementById('inner').innerHTML="keypress on doc";
}
//install event handlers
document.getElementById('inner').addEventListener("click", onClick, false);
document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false);
document.addEventListener("keypress", onKeypressDoc, false);
</script>
</body>
</html>
</code></pre>
<p>On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener.</p>
<p>Do I simply need to implement an application-specific notion of keyboard focus?</p>
<p>I should add I only need this to work in Firefox.</p>
|
[
{
"answer_id": 148444,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 8,
"selected": true,
"text": "<div id=\"inner\" tabindex=\"0\">\n this div can now have focus and receive keyboard events\n</div>\n"
},
{
"answer_id": 8529146,
"author": "Peter Bagnall",
"author_id": 51031,
"author_profile": "https://Stackoverflow.com/users/51031",
"pm_score": 3,
"selected": false,
"text": "document.getElementById('inner').contentEditable=true;\ndocument.getElementById('inner').focus();\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6521/"
] |
148,373
|
<p>I wrote a sample program at <a href="http://codepad.org/ko8vVCDF" rel="noreferrer">http://codepad.org/ko8vVCDF</a> that uses a template function.</p>
<p>How do I retrict the template function to only use numbers? (int, double etc.)</p>
<pre><code>#include <vector>
#include <iostream>
using namespace std;
template <typename T>
T sum(vector<T>& a)
{
T result = 0;
int size = a.size();
for(int i = 0; i < size; i++)
{
result += a[i];
}
return result;
}
int main()
{
vector<int> int_values;
int_values.push_back(2);
int_values.push_back(3);
cout << "Integer: " << sum(int_values) << endl;
vector<double> double_values;
double_values.push_back(1.5);
double_values.push_back(2.1);
cout << "Double: " << sum(double_values);
return 0;
}
</code></pre>
|
[
{
"answer_id": 148377,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "sum T T result = T();"
},
{
"answer_id": 148397,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 4,
"selected": false,
"text": "template <class T>\nclass NumbersOnly\n{\nprivate:\n void ValidateType( int &i ) const {}\n void ValidateType( long &l ) const {}\n void ValidateType( double &d ) const {}\n void ValidateType( float &f ) const {}\n\npublic:\n NumbersOnly()\n {\n T valid;\n ValidateType( valid );\n };\n};\n NumbersOnly<int> justFine;\nNumbersOnly<SomeClass> noDeal;\n"
},
{
"answer_id": 148408,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 5,
"selected": true,
"text": "template<class T>\nSumTraits\n{\npublic:\n const static bool canUseSum = false;\n}\n template<>\nclass SumTraits<int>\n{\n public:\n const static bool canUseSum = true;\n};\n if (!SumTraits<T>::canUseSum) {\n // throw something here\n}\n"
},
{
"answer_id": 148462,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 2,
"selected": false,
"text": "IsNumber IsNumber #include <vector>\n#include <iostream>\n\nusing namespace std;\n\ntemplate<class T> struct IsNumber{ \n private:\n IsNumber(){}\n };\n\n template<> struct IsNumber<float>{\n IsNumber(){};\n };\n\n template<> struct IsNumber<double>{\n IsNumber(){};\n };\n\n template<> struct IsNumber<int>{\n IsNumber(){};\n };\n\ntemplate <typename T>\nT sum(vector<T>& a)\n{\n IsNumber<T> test;\n T result = 0;\n int size = a.size();\n for(int i = 0; i < size; i++)\n {\n result += a[i];\n }\n\n return result;\n}\n\n\n\n\nint main()\n{\n vector<int> int_values;\n int_values.push_back(2);\n int_values.push_back(3);\n cout << \"Integer: \" << sum(int_values) << endl;\n\n vector<double> double_values;\n double_values.push_back(1.5);\n double_values.push_back(2.1);\n cout << \"Double: \" << sum(double_values);\n\n return 0;\n}\n"
},
{
"answer_id": 149127,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "#include <vector>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_arithmetic.hpp>\n\ntemplate<typename T> \n typename boost::enable_if<typename boost::is_arithmetic<T>::type, T>::type \n sum(const std::vector<T>& vec)\n{\n typedef typename std::vector<T>::size_type size_type;\n T result;\n size_type size = vec.size();\n for(size_type i = 0; i < size; i++)\n {\n result += vec[i];\n }\n\n return result;\n}\n #include <vector>\n#include <type_traits>\n\ntemplate<typename T> \n typename std::enable_if<std::is_arithmetic<T>::value, T>::type \n sum(const std::vector<T>& vec)\n{\n T result;\n for (auto item : vec)\n result += item;\n return result;\n}\n"
},
{
"answer_id": 74204221,
"author": "Cipher",
"author_id": 4933864,
"author_profile": "https://Stackoverflow.com/users/4933864",
"pm_score": 0,
"selected": false,
"text": "#include <fmt/format.h>\n\ntemplate <typename T> struct restrict_type {};\ntemplate<> struct restrict_type<float> {typedef float type;};\ntemplate<> struct restrict_type<int> {typedef int type;};\n\ntemplate<typename T>\ntypename restrict_type<T>::type add(T val1, T val2){\n return val1 + val2;\n}\n\nint main()\n{\n fmt::print(\"{}\\n\", add(12, 30));\n fmt::print(\"{}\\n\", add(12.5f, 30.9f));\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22040/"
] |
148,384
|
<p>When I measure request times on "the inside" of an Asp.Net application and compare it to timings on "the outside" of the app, I get different values -- 1000-5000ms strange overheads from time to time. </p>
<p>Maybe the requests are beeing queued up in front of IIS? </p>
<p>Or something strange is going on in an HttpModule?</p>
<p>The question: Is there a way to inspect the request pipeline for tracing exactly where the time is spent before the app is hit?</p>
|
[
{
"answer_id": 148501,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 0,
"selected": false,
"text": "<trace enabled=\"true\" pageOutput=\"true\" />"
},
{
"answer_id": 148609,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 2,
"selected": false,
"text": "<!-- pageOutput enables trace output from the page itself -->\n<system.web>\n<trace enabled=\"true\" pageOutput=\"true\" traceMode=\"SortByTime\"/>\n</system.web>\n <%@ Page Language=\"C#\" Trace=\"true\" \n Inherits=\"System.Web.UI.Page\" CodeFile=\"Default.aspx.cs\" %>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11239/"
] |
148,398
|
<p>In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level)</p>
|
[
{
"answer_id": 10195960,
"author": "carlos martini",
"author_id": 1313494,
"author_profile": "https://Stackoverflow.com/users/1313494",
"pm_score": 0,
"selected": false,
"text": " CREATE TABLE [dbo].[BusData](\n [ID] [int] IDENTITY(1,1) NOT NULL,\n [RecordId] [nvarchar](MAX) NULL,\n [CompanyName] [nvarchar](MAX) NOT NULL,\n [FirstName] [nvarchar](MAX) NOT NULL,\n [LastName] [nvarchar](MAX) NOT NULL,\n [ADDRESS] [nvarchar](MAX) NOT NULL,\n [CITY] [nvarchar](MAX) NOT NULL,\n [County] [nvarchar](MAX) NOT NULL,\n [STATE] [nvarchar](MAX) NOT NULL,\n [ZIP] [nvarchar](MAX) NOT NULL,\n [PHONE] [nvarchar](MAX) NOT NULL,\n [COUNTRY] [nvarchar](MAX) NOT NULL,\n [NPA] [nvarchar](MAX) NULL,\n [NXX] [nvarchar](MAX) NULL,\n [XXXX] [nvarchar](MAX) NULL,\n [CurrentRecord] [nvarchar](MAX) NULL,\n [TotalCount] [nvarchar](MAX) NULL,\n [Status] [int] NOT NULL,\n [ChangeDate] [datetime] NOT NULL\n ) ON [PRIMARY]\n CREATE TABLE [dbo].[BusData](\n [ID] [int] IDENTITY(1,1) NOT NULL,\n [RecordId] [nvarchar](50) NULL,\n [CompanyName] [nvarchar](50) NOT NULL,\n [FirstName] [nvarchar](50) NOT NULL,\n [LastName] [nvarchar](50) NOT NULL,\n [ADDRESS] [nvarchar](50) NOT NULL,\n [CITY] [nvarchar](50) NOT NULL,\n [County] [nvarchar](50) NOT NULL,\n [STATE] [nvarchar](2) NOT NULL,\n [ZIP] [nvarchar](16) NOT NULL,\n [PHONE] [nvarchar](18) NOT NULL,\n [COUNTRY] [nvarchar](50) NOT NULL,\n [NPA] [nvarchar](3) NULL,\n [NXX] [nvarchar](3) NULL,\n [XXXX] [nvarchar](4) NULL,\n [CurrentRecord] [nvarchar](50) NULL,\n [TotalCount] [nvarchar](50) NULL,\n [Status] [int] NOT NULL,\n [ChangeDate] [datetime] NOT NULL\n ) ON [PRIMARY]\n"
},
{
"answer_id": 26120578,
"author": "QMaster",
"author_id": 1830909,
"author_profile": "https://Stackoverflow.com/users/1830909",
"pm_score": 5,
"selected": false,
"text": "SET NOCOUNT ON;\n\n--===== Test Variable Assignment 1,000,000 times using NVARCHAR(10)\nDECLARE @SomeString NVARCHAR(10),\n @StartTime DATETIME;\n--===== \n SELECT @startTime = GETDATE();\n SELECT TOP 1000000\n @SomeString = 'ABC'\n FROM master.sys.all_columns ac1,\n master.sys.all_columns ac2;\n SELECT testTime='10', Duration = DATEDIFF(ms,@StartTime,GETDATE());\nGO\n--===== Test Variable Assignment 1,000,000 times using NVARCHAR(4000)\nDECLARE @SomeString NVARCHAR(4000),\n @StartTime DATETIME;\n SELECT @startTime = GETDATE();\n SELECT TOP 1000000\n @SomeString = 'ABC'\n FROM master.sys.all_columns ac1,\n master.sys.all_columns ac2;\n SELECT testTime='4000', Duration = DATEDIFF(ms,@StartTime,GETDATE());\nGO\n--===== Test Variable Assignment 1,000,000 times using NVARCHAR(MAX)\nDECLARE @SomeString NVARCHAR(MAX),\n @StartTime DATETIME;\n SELECT @startTime = GETDATE();\n SELECT TOP 1000000\n @SomeString = 'ABC'\n FROM master.sys.all_columns ac1,\n master.sys.all_columns ac2;\n SELECT testTime='MAX', Duration = DATEDIFF(ms,@StartTime,GETDATE());\nGO\n"
},
{
"answer_id": 35177895,
"author": "Tim Abell",
"author_id": 10245,
"author_profile": "https://Stackoverflow.com/users/10245",
"pm_score": 6,
"selected": false,
"text": "nvarchar(MAX) nvarchar(100) nvarchar(MAX) nvarchar(4000)"
},
{
"answer_id": 39789531,
"author": "Kvasi",
"author_id": 799650,
"author_profile": "https://Stackoverflow.com/users/799650",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE t4000 (a NVARCHAR(4000) NULL);\n\nCREATE TABLE tmax (a NVARCHAR(MAX) NULL);\n\nDECLARE @abc4 NVARCHAR(4000) = N'ABC';\n\nINSERT INTO t4000\nSELECT TOP 1000000 @abc4\n FROM\n master.sys.all_columns ac1,\n master.sys.all_columns ac2;\n\nDECLARE @abc NVARCHAR(MAX) = N'ABC';\n\nINSERT INTO tmax\nSELECT TOP 1000000 @abc\n FROM\n master.sys.all_columns ac1,\n master.sys.all_columns ac2;\n\nSET STATISTICS TIME ON;\nSET STATISTICS IO ON;\n\nSELECT * FROM dbo.t4000;\nSELECT * FROM dbo.tmax;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21379/"
] |
148,403
|
<p>Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.</p>
|
[
{
"answer_id": 148419,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "codecvt codecvt<wchar_t, char, mbstate_t>"
},
{
"answer_id": 148665,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": false,
"text": "utf8_codecvt_facet typedef wchar_t ucs4_t;\n\n std::locale old_locale;\n std::locale utf8_locale(old_locale,new utf8_codecvt_facet<ucs4_t>);\n\n // Set a New global locale\n std::locale::global(utf8_locale);\n\n // Send the UCS-4 data out, converting to UTF-8\n {\n std::wofstream ofs(\"data.ucd\");\n ofs.imbue(utf8_locale);\n std::copy(ucs4_data.begin(),ucs4_data.end(),\n std::ostream_iterator<ucs4_t,ucs4_t>(ofs));\n }\n\n // Read the UTF-8 data back in, converting to UCS-4 on the way in\n std::vector<ucs4_t> from_file;\n {\n std::wifstream ifs(\"data.ucd\");\n ifs.imbue(utf8_locale);\n ucs4_t item = 0;\n while (ifs >> item) from_file.push_back(item);\n }\n utf8_codecvt_facet.hpp utf8_codecvt_facet.cpp"
},
{
"answer_id": 148696,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 4,
"selected": false,
"text": "string wstring string wstring string s = \"This is surely ASCII.\";\nwstring w(s.begin(), s.end());\n string string"
},
{
"answer_id": 148766,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": "wchar_t std::string wchar_to_UTF8(const wchar_t * in)\n{\n std::string out;\n unsigned int codepoint = 0;\n for (in; *in != 0; ++in)\n {\n if (*in >= 0xd800 && *in <= 0xdbff)\n codepoint = ((*in - 0xd800) << 10) + 0x10000;\n else\n {\n if (*in >= 0xdc00 && *in <= 0xdfff)\n codepoint |= *in - 0xdc00;\n else\n codepoint = *in;\n\n if (codepoint <= 0x7f)\n out.append(1, static_cast<char>(codepoint));\n else if (codepoint <= 0x7ff)\n {\n out.append(1, static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f)));\n out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));\n }\n else if (codepoint <= 0xffff)\n {\n out.append(1, static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f)));\n out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));\n out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));\n }\n else\n {\n out.append(1, static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07)));\n out.append(1, static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));\n out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));\n out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));\n }\n codepoint = 0;\n }\n }\n return out;\n}\n d800 dfff wchar_t std::wstring UTF8_to_wchar(const char * in)\n{\n std::wstring out;\n unsigned int codepoint;\n while (*in != 0)\n {\n unsigned char ch = static_cast<unsigned char>(*in);\n if (ch <= 0x7f)\n codepoint = ch;\n else if (ch <= 0xbf)\n codepoint = (codepoint << 6) | (ch & 0x3f);\n else if (ch <= 0xdf)\n codepoint = ch & 0x1f;\n else if (ch <= 0xef)\n codepoint = ch & 0x0f;\n else\n codepoint = ch & 0x07;\n ++in;\n if (((*in & 0xc0) != 0x80) && (codepoint <= 0x10ffff))\n {\n if (sizeof(wchar_t) > 2)\n out.append(1, static_cast<wchar_t>(codepoint));\n else if (codepoint > 0xffff)\n {\n out.append(1, static_cast<wchar_t>(0xd800 + (codepoint >> 10)));\n out.append(1, static_cast<wchar_t>(0xdc00 + (codepoint & 0x03ff)));\n }\n else if (codepoint < 0xd800 || codepoint >= 0xe000)\n out.append(1, static_cast<wchar_t>(codepoint));\n }\n }\n return out;\n}\n wchar_t sizeof(wchar_t) > 2"
},
{
"answer_id": 14809553,
"author": "Vladimir Grigorov",
"author_id": 22764,
"author_profile": "https://Stackoverflow.com/users/22764",
"pm_score": 6,
"selected": false,
"text": "std::string source;\n...\nstd::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;\nstd::u16string dest = convert.from_bytes(source); \n std::u16string source;\n...\nstd::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;\nstd::string dest = convert.to_bytes(source); \n"
},
{
"answer_id": 56415362,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 0,
"selected": false,
"text": "//\n// Converts utf-8 string to wide version.\n//\n// returns target string length.\n//\nsize_t utf8towchar(const char* s, size_t inSize, wchar_t* out, size_t bufSize);\n\n//\n// Converts wide string to utf-8 string.\n//\n// returns filled buffer length (not string length)\n//\nsize_t wchartoutf8(const wchar_t* s, size_t inSize, char* out, size_t outsize);\n\n#ifdef __cplusplus\n\nstd::wstring utf8towide(const char* s);\nstd::wstring utf8towide(const std::string& s);\nstd::string widetoutf8(const wchar_t* ws);\nstd::string widetoutf8(const std::wstring& ws);\n\n#endif\n #include \"cutf.h\"\n\n#define ok(statement) \\\n if( !(statement) ) \\\n { \\\n printf(\"Failed statement: %s\\n\", #statement); \\\n r = 1; \\\n }\n\nint simpleStringTest()\n{\n const wchar_t* chineseText = L\"主体\";\n auto s = widetoutf8(chineseText);\n size_t r = 0;\n\n printf(\"simple string test: \");\n\n ok( s.length() == 6 );\n uint8_t utf8_array[] = { 0xE4, 0xB8, 0xBB, 0xE4, 0xBD, 0x93 };\n\n for(int i = 0; i < 6; i++)\n ok(((uint8_t)s[i]) == utf8_array[i]);\n\n auto ws = utf8towide(s);\n ok(ws.length() == 2);\n ok(ws == chineseText);\n\n if( r == 0 )\n printf(\"ok.\\n\");\n\n return (int)r;\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22764/"
] |
148,407
|
<p>Why does the code below return true only for a = 1?</p>
<pre><code>main(){
int a = 10;
if (true == a)
cout<<"Why am I not getting executed";
}
</code></pre>
|
[
{
"answer_id": 148423,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 6,
"selected": true,
"text": "main(){\n int a = 10;\n if (1 == a)\n cout<<\"y i am not getting executed\";\n }\n"
},
{
"answer_id": 148425,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 5,
"selected": false,
"text": "main(){\nint a = 10;\nif (((bool)a) == true)\n cout<<\"I am definitely getting executed\";\n}\n main(){\nint a = 10;\nif (a)\n cout<<\"I am definitely getting executed\";\n}\n main(){\nint a = 0;\nif (0 == false)\n cout<<\"I am definitely getting executed\";\n}\n"
},
{
"answer_id": 148434,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 2,
"selected": false,
"text": "if ( 0 )\n{\n// never run\n}\n\nif ( 1 )\n{\n// always run\n}\n\nif ( var1 == 1 )\n{\n// run when var1 is \"1\"\n}\n main(){\nint a = 10;\nif (1 == a)\n cout<<\"y i am not getting executed\";\n}\n main(){\nint a = 10;\nif (true == (bool)a)\n cout<<\"if you want to explicitly use true/false\";\n}\n main(){\nint a = 10;\nif ( a )\n cout<<\"usual C++ style\";\n}\n"
},
{
"answer_id": 148483,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "main(){\nint a = 10;\nif (a) // all non-zero satisfy 'truth'\n cout<<\"y i am not getting executed\";\n}\n main(){\nint a = 10;\nif (!!a == true) // ! result is guaranteed to be == true or == false\n cout<<\"y i am not getting executed\";\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
148,421
|
<p>I have a button on an ASP.NET wep application form and when clicked goes off and posts information a third party web service. </p>
<p>I have an UpdateProgress associated with the button. </p>
<p>how do disable/hide the button while the progress is visible (i.e. the server has not completed the operation) </p>
<p>I am looking at doing this to stop users clicking again when the information is being sent (as this results in duplicate information being sent) </p>
|
[
{
"answer_id": 148440,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": true,
"text": "<div id=\"ButtonBar\">\n <asp:Button id= ............\n</div>\n <script language=\"javascript\">\n // Get a reference to the PageRequestManager.\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n\n // Using that prm reference, hook _initializeRequest\n // and _endRequest, to run our code at the begin and end\n // of any async postbacks that occur.\n prm.add_initializeRequest(InitializeRequest);\n prm.add_endRequest(EndRequest);\n\n // Executed anytime an async postback occurs.\n function InitializeRequest(sender, args) \n {\n $get('ButtonBar').style.visibility = \"hidden\";\n }\n\n // Executed when the async postback completes.\n function EndRequest(sender, args) \n {\n $get('ButtonBar').style.visibility = \"visible\";\n }\n</script>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
148,441
|
<p>If I have a script tag like this:</p>
<pre><code><script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
</code></pre>
<p>I would like to get the content of the "script.js" file. I'm thinking about something like <code>document.getElementById("myscript").text</code> but it doesn't work in this case.</p>
|
[
{
"answer_id": 148450,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": -1,
"selected": false,
"text": "<script>"
},
{
"answer_id": 148675,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": -1,
"selected": false,
"text": "document.getElementById('myscript').getAttribute(\"src\");\ndocument.getElementById('myscript').getAttribute(\"type\");\n"
},
{
"answer_id": 151276,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": -1,
"selected": false,
"text": "document.getElementById(\"myscript\").innerHTML\n"
},
{
"answer_id": 4927418,
"author": "Dave Transom",
"author_id": 137854,
"author_profile": "https://Stackoverflow.com/users/137854",
"pm_score": -1,
"selected": false,
"text": "var scriptContent = document.getElementById(\"myscript\").innerHTML;\n"
},
{
"answer_id": 35731426,
"author": "Sauleil",
"author_id": 331752,
"author_profile": "https://Stackoverflow.com/users/331752",
"pm_score": 3,
"selected": false,
"text": "rel=\"import\" <link rel=\"import\" href=\"/path/to/imports/stuff.html\">\n"
},
{
"answer_id": 42487712,
"author": "mathheadinclouds",
"author_id": 1563634,
"author_profile": "https://Stackoverflow.com/users/1563634",
"pm_score": 1,
"selected": false,
"text": "jQuery.load(...) <br> jQuery.getScript(...) jQuery.ajax dataType: \"text\" <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n <html>\n <head>\n <script id=\"scriptData\">\n var scriptData = [\n { name: \"foo\" , url: \"path/to/foo\" },\n { name: \"bar\" , url: \"path/to/bar\" }\n ];\n </script>\n <script id=\"scriptLoader\">\n var LOADER = {\n loadedCount: 0,\n toBeLoadedCount: 0,\n load_jQuery: function (){\n var jqNode = document.createElement(\"script\");\n jqNode.setAttribute(\"src\", \"/path/to/jquery\");\n jqNode.setAttribute(\"onload\", \"LOADER.loadScripts();\");\n jqNode.setAttribute(\"id\", \"jquery\");\n document.head.appendChild(jqNode);\n },\n loadScripts: function (){\n var scriptDataLookup = this.scriptDataLookup = {};\n var scriptNodes = this.scriptNodes = {};\n var scriptNodesArr = this.scriptNodesArr = [];\n for (var j=0; j<scriptData.length; j++){\n var theEntry = scriptData[j];\n scriptDataLookup[theEntry.name] = theEntry;\n }\n //console.log(JSON.stringify(scriptDataLookup, null, 4));\n for (var i=0; i<scriptData.length; i++){\n var entry = scriptData[i];\n var name = entry.name;\n var theURL = entry.url;\n this.toBeLoadedCount++;\n var node = document.createElement(\"script\");\n node.setAttribute(\"id\", name);\n scriptNodes[name] = node;\n scriptNodesArr.push(node);\n jQuery.ajax({\n method : \"GET\",\n url : theURL,\n dataType : \"text\"\n }).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));\n }\n },\n makeFailHandler: function(name, node){\n var THIS = this;\n return function(xhr, errorName, errorMessage){\n console.log(name, \"FAIL\");\n console.log(xhr);\n console.log(errorName);\n console.log(errorMessage);\n debugger;\n }\n },\n makeHandler: function(name, node){\n var THIS = this;\n return function (fileContents, status, xhr){\n THIS.loadedCount++;\n //console.log(\"loaded\", name, \"content length\", fileContents.length, \"status\", status);\n //console.log(\"loaded:\", THIS.loadedCount, \"/\", THIS.toBeLoadedCount);\n THIS.scriptDataLookup[name].fileContents = fileContents;\n if (THIS.loadedCount >= THIS.toBeLoadedCount){\n THIS.allScriptsLoaded();\n }\n }\n },\n allScriptsLoaded: function(){\n for (var i=0; i<this.scriptNodesArr.length; i++){\n var scriptNode = this.scriptNodesArr[i];\n var name = scriptNode.id;\n var data = this.scriptDataLookup[name];\n var fileContents = data.fileContents;\n var textNode = document.createTextNode(fileContents);\n scriptNode.appendChild(textNode);\n document.head.appendChild(scriptNode); // execution is here\n //console.log(scriptNode);\n }\n // call code to make the frames here\n }\n };\n </script>\n </head>\n <frameset rows=\"200pixels,*\" onload=\"LOADER.load_jQuery();\">\n <frame src=\"about:blank\"></frame>\n <frame src=\"about:blank\"></frame>\n </frameset>\n </html>\n"
},
{
"answer_id": 48403181,
"author": "humanityANDpeace",
"author_id": 1711186,
"author_profile": "https://Stackoverflow.com/users/1711186",
"pm_score": 4,
"selected": false,
"text": "<script> same-origin-policy <script> src <script src=[url]></script> CORS CORS function printScriptTextContent(script)\n{\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\",script.src)\n xhr.onreadystatechange = function () {\n if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {\n console.log(\"the script text content is\",xhr.responseText);\n }\n };\n xhr.send();\n}\nArray.prototype.slice.call(document.querySelectorAll(\"script[src]\")).forEach(printScriptTextContent);\n"
},
{
"answer_id": 66503034,
"author": "NVRM",
"author_id": 2494754,
"author_profile": "https://Stackoverflow.com/users/2494754",
"pm_score": -1,
"selected": false,
"text": "[...document.scripts].forEach((script) => {\n fetch(script.src)\n .then((response) => response.text() )\n .then((source) => console.log(source) )\n\n})\n"
},
{
"answer_id": 70282243,
"author": "Alex Sorkin",
"author_id": 13814910,
"author_profile": "https://Stackoverflow.com/users/13814910",
"pm_score": 0,
"selected": false,
"text": "window.someVarForReturn = `content for return`\n <script src=\"file.js\"></script>\n<script>console.log(someVarForReturn)</script>\n window.someVarForReturn = `<did>My template</div>`\n <script src=\"file.js\"></script>\n<script>\nnew DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]\n</script>\n"
},
{
"answer_id": 73122562,
"author": "Mhmdrz_A",
"author_id": 5953610,
"author_profile": "https://Stackoverflow.com/users/5953610",
"pm_score": 0,
"selected": false,
"text": "src const scriptSrc = document.querySelector('script#yours').src;\n// re-request the same location\nconst scriptContent = await fetch(scriptSrc).then((res) => res.text());\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23423/"
] |
148,451
|
<p>I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. </p>
<p>How do I get <code>sed</code> to replace just the first occurrence of a string in a file rather than replacing every occurrence?</p>
<p>If I use</p>
<pre><code>sed s/#include/#include "newfile.h"\n#include/
</code></pre>
<p>it replaces all #includes. </p>
<p>Alternative suggestions to achieve the same thing are also welcome.</p>
|
[
{
"answer_id": 148473,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 8,
"selected": true,
"text": " # sed script to change \"foo\" to \"bar\" only on the first occurrence\n 1{x;s/^/first/;x;}\n 1,/foo/{x;/first/s///;x;s/foo/bar/;}\n #---end of script---\n sed sed '0,/foo/s//bar/' file \n"
},
{
"answer_id": 148474,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 5,
"selected": false,
"text": "awk '/#include/ && !done { print \"#include \\\"newfile.h\\\"\"; done=1;}; 1;' file.c\n /#include/ && !done\n {print \"#include \\\"newfile.h\\\"\"; done=1;}\n 1;\n"
},
{
"answer_id": 148476,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 3,
"selected": false,
"text": "sed s/#include/#include \"newfile.h\"\\n#include/1\n"
},
{
"answer_id": 148492,
"author": "mitchnull",
"author_id": 18645,
"author_profile": "https://Stackoverflow.com/users/18645",
"pm_score": 3,
"selected": false,
"text": " /#include/!{p;d;}\n i\\\n #include \"newfile.h\"\n :a\n n\n ba\n"
},
{
"answer_id": 148499,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "#!/bin/sed -f\n1,/^#include/ {\n /^#include/i\\\n#include \"newfile.h\"\n}\n #include #include #include #include sed 0,/^#include/ 1,"
},
{
"answer_id": 297673,
"author": "wakingrufus",
"author_id": 37847,
"author_profile": "https://Stackoverflow.com/users/37847",
"pm_score": 2,
"selected": false,
"text": "BEGIN {i=0}\n(i==0) && /#include/ {print \"#include \\\"newfile.h\\\"\"; i=1}\n{print $0} \nEND {}\n awk -f awkscript headerfile.h > headerfilenew.h\n"
},
{
"answer_id": 3502386,
"author": "Sushil",
"author_id": 422841,
"author_profile": "https://Stackoverflow.com/users/422841",
"pm_score": 6,
"selected": false,
"text": "sed '0,/pattern/s/pattern/replacement/' filename\n sed '0,/<Menu>/s/<Menu>/<Menu><Menu>Sub menu<\\/Menu>/' try.txt > abc.txt\n sed"
},
{
"answer_id": 5818901,
"author": "timo",
"author_id": 729327,
"author_profile": "https://Stackoverflow.com/users/729327",
"pm_score": 2,
"selected": false,
"text": "ed man 1 ed\n\nteststr='\n#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n'\n\n# for in-place file editing use \"ed -s file\" and replace \",p\" with \"w\"\n# cf. http://wiki.bash-hackers.org/howto/edit-ed\ncat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo \"$teststr\")\n H\n /# *include/i\n #include \"newfile.h\"\n .\n ,p\n q\nEOF\n"
},
{
"answer_id": 8173238,
"author": "Michael Cook",
"author_id": 1052568,
"author_profile": "https://Stackoverflow.com/users/1052568",
"pm_score": 2,
"selected": false,
"text": " sed \"1,/====RSSpermalink====/s/====RSSpermalink====/${nowms}/\" \\\n production-feed2.xml.tmp2 > production-feed2.xml.tmp.$counter\n ${nowms} $counter \\ 1,/====RSSpermalink====/ s/====RSSpermalink====/${nowms}/"
},
{
"answer_id": 9453461,
"author": "tim",
"author_id": 1233841,
"author_profile": "https://Stackoverflow.com/users/1233841",
"pm_score": 9,
"selected": false,
"text": "sed Input: Output:\n\n Apple Banana\n Apple Apple\n Orange Orange\n Apple Apple\n sed sed '0,/Apple/{s/Apple/Banana/}' input_filename\n 0 /Apple/ s/Apple/Banana/ 0 Apple Apple Banana Apple sed GNU line 0 line 1 // sed '0,/Apple/{s//Banana/}' input_filename\n s sed '0,/Apple/s//Banana/' input_filename\n sed brew install gnu-sed"
},
{
"answer_id": 10616921,
"author": "nazq",
"author_id": 1398400,
"author_profile": "https://Stackoverflow.com/users/1398400",
"pm_score": 2,
"selected": false,
"text": "ed ed include teststr='\n#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n'\n\n# using FreeBSD ed\n# to avoid ed's \"no match\" error, see\n# *emphasized text*http://codesnippets.joyent.com/posts/show/11917 \ncat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo \"$teststr\")\n H\n ,g/# *include/u\\\n u\\\n i\\\n #include \"newfile.h\"\\\n .\n ,p\n q\nEOF\n"
},
{
"answer_id": 11458836,
"author": "MikhailVS",
"author_id": 620495,
"author_profile": "https://Stackoverflow.com/users/620495",
"pm_score": 5,
"selected": false,
"text": "sed '0,/RE/s//to_that/' file\n sed -e '1s/RE/to_that/;t' -e '1,/RE/s//to_that/'\n -e '/RE/{s//to_that/;:a' -e '$!N;$!ba' -e '}'\n sed -e '/Apple/{s//Banana/;:a' -e '$!N;$!ba' -e '}' filename\n"
},
{
"answer_id": 14683337,
"author": "Andreas Panagiotidis",
"author_id": 823368,
"author_profile": "https://Stackoverflow.com/users/823368",
"pm_score": 0,
"selected": false,
"text": "sed -e 0,/'<isTag>false<\\/isTag>'/{s/'<isTag>false<\\/isTag>'//} -e 's/ *$//' -e '/^$/d' source.txt > output.txt\n <xml>\n <testdata>\n <canUseUpdate>true</canUseUpdate>\n <isTag>false</isTag>\n <moduleLocations>\n <module>esa_jee6</module>\n <isTag>false</isTag>\n </moduleLocations>\n <node>\n <isTag>false</isTag>\n </node>\n </testdata>\n</xml>\n <xml>\n <testdata>\n <canUseUpdate>true</canUseUpdate>\n <moduleLocations>\n <module>esa_jee6</module>\n <isTag>false</isTag>\n </moduleLocations>\n <node>\n <isTag>false</isTag>\n </node>\n </testdata>\n</xml>\n"
},
{
"answer_id": 17964220,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 2,
"selected": false,
"text": "sed -si '/#include/{s//& \"newfile.h\\n&/;:a;$!{n;ba}}' file1 file2 file....\n sed -si ':a;$!{N;ba};s/#include/& \"newfile.h\\n&/' file1 file2 file...\n"
},
{
"answer_id": 30420104,
"author": "Michael Edwards",
"author_id": 4933296,
"author_profile": "https://Stackoverflow.com/users/4933296",
"pm_score": 3,
"selected": false,
"text": "grep -E -m 1 -n 'old' file | sed 's/:.*$//' - | sed 's/$/s\\/old\\/new\\//' - | sed -f - file\n 5:line #include blah 5s/.*/blah/"
},
{
"answer_id": 33416489,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 6,
"selected": false,
"text": "$'...' bash ksh zsh sed sed 0,/re/ re 0,/re/ re re 1,/re/ re re // 0,/re/ s/.../.../ re sed // $ sed '0,/foo/ s//bar/' <<<$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo' \n1st bar # only 1st match of 'foo' replaced\nUnrelated\n2nd foo\n3rd foo\n sed sed sed 0,/re/ 1,/re/ re $ sed -e '1 s/foo/bar/; t' -e '1,// s//bar/' <<<$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar # only 1st match of 'foo' replaced\nUnrelated\n2nd foo\n3rd foo\n // s foo sed t -e -e 1 s/foo/bar/ foo t t s 1,// 2 1,// sed 0,/re/ sed $ sed -e '/foo/ {s//bar/; ' -e ':a' -e '$!{n;ba' -e '};}' <<<$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar\nUnrelated\n2nd foo\n3rd foo\n $ sed -e ':a' -e '$!{N;ba' -e '}; s/foo/bar/' <<<$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar\nUnrelated\n2nd foo\n3rd foo\n 1,/re/ s// sed '1,/foo/ s/foo/bar/' <<<$'1foo\\n2foo' $'1bar\\n2bar' 1 /foo/ s/foo/bar/ sed '1,/foo/ s//bar/' <<<$'1foo\\n2foo\\n3foo' sed: first RE may not be empty sed: -e expression #1, char 0: no previous regular expression 1 // sed 0,/re/ //"
},
{
"answer_id": 41687303,
"author": "Stephen Niedzielski",
"author_id": 970346,
"author_profile": "https://Stackoverflow.com/users/970346",
"pm_score": 0,
"selected": false,
"text": "sed -rn '0,/foo(bar).*/ s%%\\1%p' xwininfo -name unity-launcher xwininfo: Window id: 0x2200003 \"unity-launcher\"\n\n Absolute upper-left X: -2980\n Absolute upper-left Y: -198\n Relative upper-left X: 0\n Relative upper-left Y: 0\n Width: 2880\n Height: 98\n Depth: 24\n Visual: 0x21\n Visual Class: TrueColor\n Border width: 0\n Class: InputOutput\n Colormap: 0x20 (installed)\n Bit Gravity State: ForgetGravity\n Window Gravity State: NorthWestGravity\n Backing Store State: NotUseful\n Save Under State: no\n Map State: IsViewable\n Override Redirect State: no\n Corners: +-2980+-198 -2980+-198 -2980-1900 +-2980-1900\n -geometry 2880x98+-2980+-198\n xwininfo -name unity-launcher|sed -rn '0,/^xwininfo: Window id: (0x[0-9a-fA-F]+).*/ s%%\\1%p' 0x2200003\n"
},
{
"answer_id": 45204736,
"author": "FatihSarigol",
"author_id": 7099242,
"author_profile": "https://Stackoverflow.com/users/7099242",
"pm_score": 2,
"selected": false,
"text": "sed '/old/s/old/new/1' file\n\n-bash-4.2$ cat file\n123a456a789a\n12a34a56\na12\n-bash-4.2$ sed '/a/s/a/b/1' file\n123b456a789a\n12b34a56\nb12\n"
},
{
"answer_id": 52752923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "sed '/\\(#include\\).*/!b;//{h;s//\\1 \"newfile.h\"/;G};:1;n;b1'\n sed '\n/\\(#include\\).*/!b # Only one regex used. On lines not matching\n # the text `#include` **yet**,\n # branch to end, cause the default print. Re-start.\n//{ # On first line matching previous regex.\n h # hold the line.\n s//\\1 \"newfile.h\"/ # append ` \"newfile.h\"` to the `#include` matched.\n G # append a newline.\n } # end of replacement.\n:1 # Once **one** replacement got done (the first match)\nn # Loop continually reading a line each time\nb1 # and printing it by default.\n' # end of sed script.\n"
},
{
"answer_id": 54650952,
"author": "Socowi",
"author_id": 6770384,
"author_profile": "https://Stackoverflow.com/users/6770384",
"pm_score": 4,
"selected": false,
"text": "-z s/…/…/ s/…/…/ -z sed sed -z 's/#include/#include \"newfile.h\"\\n#include'\n s/text.*// s/text[^\\n]*// [^\\n] [^\\n]* text s/^text// s/(^|\\n)text// s/text$// s/text(\\n|$)//"
},
{
"answer_id": 58180421,
"author": "sastorsl",
"author_id": 2045924,
"author_profile": "https://Stackoverflow.com/users/2045924",
"pm_score": 1,
"selected": false,
"text": "sed '1,10s/#include/#include \"newfile.h\"\\n#include/'\n"
},
{
"answer_id": 59149068,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": " -include file\n Process file as if \"#include \"file\"\" appeared as the first line of\n the primary source file. However, the first directory searched for\n file is the preprocessor's working directory instead of the\n directory containing the main source file. If not found there, it\n is searched for in the remainder of the \"#include \"...\"\" search\n chain as normal.\n\n If multiple -include options are given, the files are included in\n the order they appear on the command line.\n\n -imacros file\n Exactly like -include, except that any output produced by scanning\n file is thrown away. Macros it defines remain defined. This\n allows you to acquire all the macros from a header without also\n processing its declarations.\n\n All files specified by -imacros are processed before all files\n specified by -include.\n -include"
},
{
"answer_id": 60410528,
"author": "warhansen",
"author_id": 5497373,
"author_profile": "https://Stackoverflow.com/users/5497373",
"pm_score": -1,
"selected": false,
"text": "sed -e 's/pattern/REPLACEMENT/1' <INPUTFILE\n"
},
{
"answer_id": 69259495,
"author": "chaytan",
"author_id": 10055600,
"author_profile": "https://Stackoverflow.com/users/10055600",
"pm_score": -1,
"selected": false,
"text": "def replace_models(file_path, pixel_model, obj_model):\n # find your file --project matches\n pattern = re.compile(r'--project.*')\n new_file = \"\"\n with open(file_path, 'r') as f:\n match = 1\n for line in f:\n # Remove line ending before we do replacement\n line = line.strip()\n # replace first --project line match with pixel\n if match == 1:\n result = re.sub(pattern, \"--project='\" + pixel_model + \"'\", line)\n # replace second --project line match with object\n elif match == 2:\n result = re.sub(pattern, \"--project='\" + obj_model + \"'\", line)\n else:\n result = line\n # Check that a substitution was actually made\n if result is not line:\n # Add a backslash to the replaced line\n result += \" \\\\\"\n print(\"\\nReplaced \", line, \" with \", result)\n # Increment number of matches found\n match += 1\n # Add the potentially modified line to our new file\n new_file = new_file + result + \"\\n\"\n # close file / save output\n f.close()\n fout = open(file_path, \"w\")\n fout.write(new_file)\n fout.close()\n"
},
{
"answer_id": 74001359,
"author": "Zebiano",
"author_id": 8234174,
"author_profile": "https://Stackoverflow.com/users/8234174",
"pm_score": 0,
"selected": false,
"text": "sed -e \"1,/pattern/s/pattern/replacement/\"\n // pattern"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
] |
148,478
|
<p>I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performance issues though, especially on Linux.</p>
<p>And Java2D has so very many ways of creating graphics buffers and drawing graphics that I just don't know if I'm doing the right thing. I've been experimenting with graphics2d.getDeviceConfiguration().createCompatibleVolatileImage, which looks promising, but I have no real proof it it's going to be any faster if I switch the drawing code to that.</p>
<p>In your experience, what is the fastest way to render 2D graphics onto the screen in Java 1.5+? Note that the game is quite far ahead, so I don't want to switch to a completely different method of drawing, like OpenGL or a game engine. I basically want to know how to get the fastest way of using a Graphics2D object to draw stuff to the screen.</p>
|
[
{
"answer_id": 200493,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 5,
"selected": false,
"text": "GraphicsConfiguration.createCompatibleImage Canvas.createBufferStrategy -Dsun.java2d.opengl=True"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] |
148,511
|
<p>Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:</p>
<pre><code>LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );
</code></pre>
<p>so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).</p>
<p>Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:</p>
<pre><code>LimitedValue< float, 0, 90 > smallAngle( 45.0 );
LimitedValue< float, 0, 360 > anyAngle( smallAngle );
</code></pre>
<p>and have that operation checked at compile-time, so this next example gives an error:</p>
<pre><code>LimitedValue< float, -90, 0 > negativeAngle( -45.0 );
LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR!
</code></pre>
<p>Is this possible? Is there some practical way of doing this, or any examples out there which approach this?</p>
|
[
{
"answer_id": 148551,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 5,
"selected": true,
"text": "template< typename T, int min, int max >class LimitedValue {\n template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other )\n {\n static_assert( min <= min2, \"Parameter minimum must be >= this minimum\" );\n static_assert( max >= max2, \"Parameter maximum must be <= this maximum\" );\n\n // logic\n }\n// rest of code\n};\n"
},
{
"answer_id": 148693,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 1,
"selected": false,
"text": "template<typename T, T min, T max>\nclass Bounded {\nprivate:\n T _value;\npublic:\n Bounded(T value) : _value(min) {\n if (value <= max && value >= min) {\n _value = value;\n } else {\n // XXX throw your runtime error/exception...\n }\n }\n Bounded(const Bounded<T, min, max>& b)\n : _value(b._value){ }\n};\n Bounded<int, 1, 5> b1(1);\nBounded<int, 1, 4> b2(b1); // <-- won't compile: type mismatch\n"
},
{
"answer_id": 7928692,
"author": "Alexis Wilke",
"author_id": 212378,
"author_profile": "https://Stackoverflow.com/users/212378",
"pm_score": 2,
"selected": false,
"text": "typedef typedef controlled_vars::limited_fauto_init<float, 0, 360> angle_t;\n CONTROLLED_VARS_DEBUG CONTROLLED_VARS_LIMITED typedef float angle_t;\n angle_t float angle_t a;\na += 35;\n a + 35 > 360 float a; double b; a = b; int c; long d; c = d;"
},
{
"answer_id": 13730310,
"author": "Useless",
"author_id": 212858,
"author_profile": "https://Stackoverflow.com/users/212858",
"pm_score": 4,
"selected": false,
"text": "unsafe_bounded_cast safe_bounded_cast #include \"bounded.hpp\"\n\nint main()\n{\n BoundedValue<int, 0, 5> inner(1);\n BoundedValue<double, 0, 4> outer(2.3);\n BoundedValue<double, -1, +1> overlap(0.0);\n\n inner = outer; // ok: [0,4] contained in [0,5]\n\n // overlap = inner;\n // ^ error: static assertion failed: \"conversion disallowed from BoundedValue with higher max\"\n\n // overlap = safe_bounded_cast<double, -1, +1>(inner);\n // ^ error: static assertion failed: \"conversion disallowed from BoundedValue with higher max\"\n\n overlap = unsafe_bounded_cast<double, -1, +1>(inner);\n // ^ compiles but throws:\n // terminate called after throwing an instance of 'BoundedValueException<int>'\n // what(): BoundedValueException: !(-1<=2<=1) - BOUNDED_VALUE_ASSERT at bounded.hpp:56\n // Aborted\n\n inner = 0;\n overlap = unsafe_bounded_cast<double, -1, +1>(inner);\n // ^ ok\n\n inner = 7;\n // terminate called after throwing an instance of 'BoundedValueException<int>'\n // what(): BoundedValueException: !(0<=7<=5) - BOUNDED_VALUE_ASSERT at bounded.hpp:75\n // Aborted\n}\n #include <stdexcept>\n#include <sstream>\n\n#define STRINGIZE(x) #x\n#define STRINGIFY(x) STRINGIZE( x )\n\n// handling for runtime value errors\n#define BOUNDED_VALUE_ASSERT(MIN, MAX, VAL) \\\n if ((VAL) < (MIN) || (VAL) > (MAX)) { \\\n bounded_value_assert_helper(MIN, MAX, VAL, \\\n \"BOUNDED_VALUE_ASSERT at \" \\\n __FILE__ \":\" STRINGIFY(__LINE__)); \\\n }\n\ntemplate <typename T>\nstruct BoundedValueException: public std::range_error\n{\n virtual ~BoundedValueException() throw() {}\n BoundedValueException() = delete;\n BoundedValueException(BoundedValueException const &other) = default;\n BoundedValueException(BoundedValueException &&source) = default;\n\n BoundedValueException(int min, int max, T val, std::string const& message)\n : std::range_error(message), minval_(min), maxval_(max), val_(val)\n {\n }\n\n int const minval_;\n int const maxval_;\n T const val_;\n};\n\ntemplate <typename T> void bounded_value_assert_helper(int min, int max, T val,\n char const *message = NULL)\n{\n std::ostringstream oss;\n oss << \"BoundedValueException: !(\"\n << min << \"<=\"\n << val << \"<=\"\n << max << \")\";\n if (message) {\n oss << \" - \" << message;\n }\n throw BoundedValueException<T>(min, max, val, oss.str());\n}\n template <typename T, int Tmin, int Tmax> class BoundedValue\n{\npublic:\n typedef T value_type;\n enum { min_value=Tmin, max_value=Tmax };\n typedef BoundedValue<value_type, min_value, max_value> SelfType;\n\n // runtime checking constructor:\n explicit BoundedValue(T runtime_value) : val_(runtime_value) {\n BOUNDED_VALUE_ASSERT(min_value, max_value, runtime_value);\n }\n // compile-time checked constructors:\n BoundedValue(SelfType const& other) : val_(other) {}\n BoundedValue(SelfType &&other) : val_(other) {}\n\n template <typename otherT, int otherTmin, int otherTmax>\n BoundedValue(BoundedValue<otherT, otherTmin, otherTmax> const &other)\n : val_(other) // will just fail if T, otherT not convertible\n {\n static_assert(otherTmin >= Tmin,\n \"conversion disallowed from BoundedValue with lower min\");\n static_assert(otherTmax <= Tmax,\n \"conversion disallowed from BoundedValue with higher max\");\n }\n\n // compile-time checked assignments:\n BoundedValue& operator= (SelfType const& other) { val_ = other.val_; return *this; }\n\n template <typename otherT, int otherTmin, int otherTmax>\n BoundedValue& operator= (BoundedValue<otherT, otherTmin, otherTmax> const &other) {\n static_assert(otherTmin >= Tmin,\n \"conversion disallowed from BoundedValue with lower min\");\n static_assert(otherTmax <= Tmax,\n \"conversion disallowed from BoundedValue with higher max\");\n val_ = other; // will just fail if T, otherT not convertible\n return *this;\n }\n // run-time checked assignment:\n BoundedValue& operator= (T const& val) {\n BOUNDED_VALUE_ASSERT(min_value, max_value, val);\n val_ = val;\n return *this;\n }\n\n operator T const& () const { return val_; }\nprivate:\n value_type val_;\n};\n template <typename dstT, int dstMin, int dstMax>\nstruct BoundedCastHelper\n{\n typedef BoundedValue<dstT, dstMin, dstMax> return_type;\n\n // conversion is checked statically, and always succeeds\n template <typename srcT, int srcMin, int srcMax>\n static return_type convert(BoundedValue<srcT, srcMin, srcMax> const& source)\n {\n return return_type(source);\n }\n\n // conversion is checked dynamically, and could throw\n template <typename srcT, int srcMin, int srcMax>\n static return_type coerce(BoundedValue<srcT, srcMin, srcMax> const& source)\n {\n return return_type(static_cast<srcT>(source));\n }\n};\n\ntemplate <typename dstT, int dstMin, int dstMax,\n typename srcT, int srcMin, int srcMax>\nauto safe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)\n -> BoundedValue<dstT, dstMin, dstMax>\n{\n return BoundedCastHelper<dstT, dstMin, dstMax>::convert(source);\n}\n\ntemplate <typename dstT, int dstMin, int dstMax,\n typename srcT, int srcMin, int srcMax>\nauto unsafe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)\n -> BoundedValue<dstT, dstMin, dstMax>\n{\n return BoundedCastHelper<dstT, dstMin, dstMax>::coerce(source);\n}\n"
},
{
"answer_id": 25771537,
"author": "Artium",
"author_id": 452483,
"author_profile": "https://Stackoverflow.com/users/452483",
"pm_score": 2,
"selected": false,
"text": "range"
},
{
"answer_id": 31735320,
"author": "David Stone",
"author_id": 852254,
"author_profile": "https://Stackoverflow.com/users/852254",
"pm_score": 2,
"selected": false,
"text": "auto x = bounded::checked_integer<0, 7>(f());\nauto y = 7_bi;\nauto z = x + y;\n// decltype(z) == bounded::checked_integer<7, 14>\nstatic_assert(z >= 7_bi);\nstatic_assert(z <= 14_bi);\n z = 10_bi;\nz = x;\nstatic_assert(!std::is_assignable<decltype((z)), decltype(0_bi)>::value);\n z = 10_bi 10 z z = x x z static_assert"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23434/"
] |
148,518
|
<p>It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.</p>
<p>What is the most efficient way to stop after the first replacement?</p>
|
[
{
"answer_id": 148526,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 6,
"selected": true,
"text": "Replace(String, String, Int32) \n"
},
{
"answer_id": 148561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "(?<!foo.*)foo"
},
{
"answer_id": 39072686,
"author": "Pini Cheyni",
"author_id": 1773972,
"author_profile": "https://Stackoverflow.com/users/1773972",
"pm_score": 2,
"selected": false,
"text": "string str =\"abc546_$defg\";\nstr = Regex.Replace(str,\"[^A-Za-z0-9]\", \"\");\n string str =\"abc546_$defg\";\nRegex regx = new Regex(\"[^A-Za-z0-9]\");\nstr = regx.Replace(str,\"\",1)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
] |
148,540
|
<p>I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.</p>
<p>I want some help working out how to create an iterator for a class I have created.</p>
<p>I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which references a Shape and defines a position for the Shape.
Piece does not have a Shape it just references a Shape.</p>
<p>I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.</p>
<p>I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.</p>
|
[
{
"answer_id": 148562,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "// Your class `Piece`\nclass Piece {\nprivate:\n Shape m_shape;\n\npublic:\n\n typedef std::vector<Point>::iterator iterator;\n typedef std::vector<Point>::const_iterator const_iterator;\n\n iterator begin() { return m_shape.container.begin(); }\n\n const_iterator begin() const { return m_shape.container.begin(); }\n\n iterator end() { return m_shape.container.end(); }\n\n const_iterator end() const { return m_shape.const_container.end(); }\n}\n vector"
},
{
"answer_id": 148565,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 1,
"selected": false,
"text": "class Shape {\n private:\n vector <Point> points;\n for (vector <Point>::iterator i = points.begin(); i != points.end(); ++i)\n /* ... */\n"
},
{
"answer_id": 44311851,
"author": "VinGarcia",
"author_id": 2905274,
"author_profile": "https://Stackoverflow.com/users/2905274",
"pm_score": 2,
"selected": false,
"text": "Piece #include <iostream>\n#include <vector>\n\n#include \"iterator_tpl.h\"\n\nstruct Point {\n int x;\n int y;\n Point() {}\n Point(int x, int y) : x(x), y(y) {}\n Point operator+(Point other) const {\n other.x += x;\n other.y += y;\n return other;\n }\n};\n\nstruct Shape {\n std::vector<Point> vec;\n};\n\nstruct Piece {\n Shape& shape;\n Point offset;\n Piece(Shape& shape, int x, int y) : shape(shape), offset(x,y) {}\n\n struct it_state {\n int pos;\n inline void next(const Piece* ref) { ++pos; }\n inline void begin(const Piece* ref) { pos = 0; }\n inline void end(const Piece* ref) { pos = ref->shape.vec.size(); }\n inline Point get(Piece* ref) { return ref->offset + ref->shape.vec[pos]; }\n inline bool equal(const it_state& s) const { return pos == s.pos; }\n };\n SETUP_ITERATORS(Piece, Point, it_state);\n};\n int main() {\n Shape shape;\n shape.vec.emplace_back(1,2);\n shape.vec.emplace_back(2,3);\n shape.vec.emplace_back(3,4);\n\n Piece piece(shape, 1, 1);\n\n for (Point p : piece) {\n std::cout << p.x << \" \" << p.y << std::endl;\n // Output:\n // 2 3\n // 3 4\n // 4 5\n }\n\n return 0;\n}\n const_iterator reverse_const_iterator"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23435/"
] |
148,568
|
<p>I'm currently working on a school project, in java, and I'm coding a database application. Something like the MySQL Monitor where you type in queries and get results / whatever.</p>
<p>In applications I've coded before, I used databases to store data, like user profiles, settings, etc. Now, obviously, I can't use a database to store data generated from this school project, otherwise what's the point?</p>
<p>I'm thinking about storing the data in files but that's the only idea I have in my mind right now and I'm kinda running dry.. and to be honest, I don't want to start banging at code and then I discover a better way of doing it.</p>
<p>So if anyone has any idea how to store the data (like CSV?), or has some kind of knowledge of how database applications work internally, can you please shed some light?</p>
<p>--
EDIT: just to be more clear, I can't use database engines to store the data, to put it this way, I'm coding a simple database engine. Ideas like what Galwegian, jkramer and Joe Skora suggested is what I'm looking for.</p>
|
[
{
"answer_id": 148827,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "Map<String,List<Record>>"
},
{
"answer_id": 148840,
"author": "shadit",
"author_id": 9925,
"author_profile": "https://Stackoverflow.com/users/9925",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM EMPLOYEES\n Employee[] result = EmployeeDataManager.select(\"LASTNAME\", \"Smith\");\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] |
148,570
|
<p>I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently?</p>
|
[
{
"answer_id": 260367,
"author": "Dave Hillier",
"author_id": 1575281,
"author_profile": "https://Stackoverflow.com/users/1575281",
"pm_score": 4,
"selected": false,
"text": "myprecompiledheaders myproject_SOURCE_FILES if (MSVC)\n\n set_source_files_properties(myprecompiledheaders.cpp\n PROPERTIES\n COMPILE_FLAGS \"/Ycmyprecompiledheaders.h\"\n )\n foreach( src_file ${myproject_SOURCE_FILES} )\n set_source_files_properties(\n ${src_file}\n PROPERTIES\n COMPILE_FLAGS \"/Yumyprecompiledheaders.h\"\n )\n endforeach( src_file ${myproject_SOURCE_FILES} )\n list(APPEND myproject_SOURCE_FILES myprecompiledheaders.cpp)\nendif (MSVC)\n"
},
{
"answer_id": 1380048,
"author": "larsmoa",
"author_id": 167251,
"author_profile": "https://Stackoverflow.com/users/167251",
"pm_score": 5,
"selected": false,
"text": "MACRO(ADD_MSVC_PRECOMPILED_HEADER PrecompiledHeader PrecompiledSource SourcesVar)\n IF(MSVC)\n GET_FILENAME_COMPONENT(PrecompiledBasename ${PrecompiledHeader} NAME_WE)\n SET(PrecompiledBinary \"${CMAKE_CURRENT_BINARY_DIR}/${PrecompiledBasename}.pch\")\n SET(Sources ${${SourcesVar}})\n\n SET_SOURCE_FILES_PROPERTIES(${PrecompiledSource}\n PROPERTIES COMPILE_FLAGS \"/Yc\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_OUTPUTS \"${PrecompiledBinary}\")\n SET_SOURCE_FILES_PROPERTIES(${Sources}\n PROPERTIES COMPILE_FLAGS \"/Yu\\\"${PrecompiledHeader}\\\" /FI\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_DEPENDS \"${PrecompiledBinary}\") \n # Add precompiled header to SourcesVar\n LIST(APPEND ${SourcesVar} ${PrecompiledSource})\n ENDIF(MSVC)\nENDMACRO(ADD_MSVC_PRECOMPILED_HEADER)\n ADD_MSVC_PRECOMPILED_HEADER(\"precompiled.h\" \"precompiled.cpp\" MySources)\nADD_LIBRARY(MyLibrary ${MySources})\n"
},
{
"answer_id": 2956392,
"author": "jari",
"author_id": 355846,
"author_profile": "https://Stackoverflow.com/users/355846",
"pm_score": 4,
"selected": false,
"text": "MACRO(ADD_MSVC_PRECOMPILED_HEADER PrecompiledHeader PrecompiledSource SourcesVar)\n IF(MSVC)\n GET_FILENAME_COMPONENT(PrecompiledBasename ${PrecompiledHeader} NAME_WE)\n SET(PrecompiledBinary \"$(IntDir)/${PrecompiledBasename}.pch\")\n SET(Sources ${${SourcesVar}})\n\n SET_SOURCE_FILES_PROPERTIES(${PrecompiledSource}\n PROPERTIES COMPILE_FLAGS \"/Yc\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_OUTPUTS \"${PrecompiledBinary}\")\n SET_SOURCE_FILES_PROPERTIES(${Sources}\n PROPERTIES COMPILE_FLAGS \"/Yu\\\"${PrecompiledHeader}\\\" /FI\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_DEPENDS \"${PrecompiledBinary}\") \n # Add precompiled header to SourcesVar\n LIST(APPEND ${SourcesVar} ${PrecompiledSource})\n ENDIF(MSVC)\nENDMACRO(ADD_MSVC_PRECOMPILED_HEADER)\n\nADD_MSVC_PRECOMPILED_HEADER(\"stdafx.h\" \"stdafx.cpp\" MY_SRCS)\nADD_EXECUTABLE(MyApp ${MY_SRCS})\n"
},
{
"answer_id": 3211026,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": 4,
"selected": false,
"text": "if (MSVC)\n set_target_properties(abc PROPERTIES COMPILE_FLAGS \"/Yustd.h\")\n set_source_files_properties(std.cpp PROPERTIES COMPILE_FLAGS \"/Ycstd.h\")\nendif(MSVC)\n"
},
{
"answer_id": 27815291,
"author": "uncletall",
"author_id": 2259878,
"author_profile": "https://Stackoverflow.com/users/2259878",
"pm_score": 0,
"selected": false,
"text": "<PrecompiledHeader>Use</PrecompiledHeader> Create MACRO(ADD_MSVC_PRECOMPILED_HEADER SourcesVar)\n SET(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} /YuStdAfx.h\")\n set_source_files_properties(StdAfx.cpp\n PROPERTIES\n COMPILE_FLAGS \"/YcStdAfx.h\"\n )\n list(APPEND ${${SourcesVar}} StdAfx.cpp)\nENDMACRO(ADD_MSVC_PRECOMPILED_HEADER)\n\nfile(GLOB_RECURSE MYDLL_SRC\n \"*.h\"\n \"*.cpp\"\n \"*.rc\")\n\nADD_MSVC_PRECOMPILED_HEADER(MYDLL_SRC)\nadd_library(MyDll SHARED ${MYDLL_SRC})\n"
},
{
"answer_id": 29672231,
"author": "Vram Vardanian",
"author_id": 1276180,
"author_profile": "https://Stackoverflow.com/users/1276180",
"pm_score": 2,
"selected": false,
"text": "# set PCH for VS project\nfunction(SET_TARGET_PRECOMPILED_HEADER Target PrecompiledHeader PrecompiledSource)\n if(MSVC)\n SET_TARGET_PROPERTIES(${Target} PROPERTIES COMPILE_FLAGS \"/Yu${PrecompiledHeader}\")\n set_source_files_properties(${PrecompiledSource} PROPERTIES COMPILE_FLAGS \"/Yc${PrecompiledHeader}\")\n endif(MSVC)\nendfunction(SET_TARGET_PRECOMPILED_HEADER)\n\n# ignore PCH for a specified list of files\nfunction(IGNORE_PRECOMPILED_HEADER SourcesVar)\n if(MSVC) \n set_source_files_properties(${${SourcesVar}} PROPERTIES COMPILE_FLAGS \"/Y-\")\n endif(MSVC)\nendfunction(IGNORE_PRECOMPILED_HEADER)\n SET_TARGET_PRECOMPILED_HEADER(MY_TARGET stdafx.h stdafx.cpp)\nIGNORE_PRECOMPILED_HEADER(IGNORE_PCH_SRC_LIST)\n"
},
{
"answer_id": 37215986,
"author": "Maks",
"author_id": 3001953,
"author_profile": "https://Stackoverflow.com/users/3001953",
"pm_score": 2,
"selected": false,
"text": "if (MSVC)\n # For precompiled header.\n # Set \n # \"Precompiled Header\" to \"Use (/Yu)\"\n # \"Precompiled Header File\" to \"stdafx.h\"\n set (CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} /Yustdafx.h /FIstdafx.h\")\nendif()\n set_source_files_properties(src/stdafx.cpp\n PROPERTIES\n COMPILE_FLAGS \"/Ycstdafx.h\"\n)\n"
},
{
"answer_id": 39387590,
"author": "schorsch_76",
"author_id": 3551285,
"author_profile": "https://Stackoverflow.com/users/3551285",
"pm_score": 0,
"selected": false,
"text": "#######################################################################\n# Makro for precompiled header\n#######################################################################\nMACRO(ADD_MSVC_PRECOMPILED_HEADER PrecompiledHeader PrecompiledSource SourcesVar)\n IF(MSVC)\n GET_FILENAME_COMPONENT(PrecompiledBasename ${PrecompiledHeader} NAME_WE)\n SET(PrecompiledBinary \"$(IntDir)/${PrecompiledBasename}.pch\")\n SET(Sources ${${SourcesVar}})\n\n # generate the precompiled header\n SET_SOURCE_FILES_PROPERTIES(${PrecompiledSource}\n PROPERTIES COMPILE_FLAGS \"/Zm500 /Yc\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_OUTPUTS \"${PrecompiledBinary}\")\n\n # set the usage of this header only to the other files than rc\n FOREACH(fname ${Sources})\n IF ( NOT ${fname} MATCHES \".*rc$\" )\n SET_SOURCE_FILES_PROPERTIES(${fname}\n PROPERTIES COMPILE_FLAGS \"/Zm500 /Yu\\\"${PrecompiledHeader}\\\" /FI\\\"${PrecompiledHeader}\\\" /Fp\\\"${PrecompiledBinary}\\\"\"\n OBJECT_DEPENDS \"${PrecompiledBinary}\")\n ENDIF( NOT ${fname} MATCHES \".*rc$\" )\n ENDFOREACH(fname)\n\n # Add precompiled header to SourcesVar\n LIST(APPEND ${SourcesVar} ${PrecompiledSource})\n ENDIF(MSVC)\nENDMACRO(ADD_MSVC_PRECOMPILED_HEADER)\n"
},
{
"answer_id": 42005139,
"author": "Roman Kruglov",
"author_id": 895077,
"author_profile": "https://Stackoverflow.com/users/895077",
"pm_score": 3,
"selected": false,
"text": "include( cmake-precompiled-header/PrecompiledHeader.cmake )\nadd_precompiled_header( targetName StdAfx.h FORCEINCLUDE SOURCE_CXX StdAfx.cpp )\n"
},
{
"answer_id": 57716534,
"author": "janisozaur",
"author_id": 653515,
"author_profile": "https://Stackoverflow.com/users/653515",
"pm_score": 6,
"selected": false,
"text": " target_precompile_headers(<target>\n <INTERFACE|PUBLIC|PRIVATE> [header1...]\n [<INTERFACE|PUBLIC|PRIVATE> [header2...] ...])\n REUSE_FROM"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23439/"
] |
148,578
|
<p>I have been doing some remote development using emacs tramp and found that it was quite slow. Every time I save a file, it takes about 10 seconds to complete the save. So, now I am using rsync to transfer the files remotely and it works much faster, it takes about a second plus the local saves from emacs are instant. Are there any configuration options within tramp to get it to run as fast as rsync does on the command line? Are there any advantages to using tramp instead of rsync even though I am seeing such poor performance?</p>
|
[
{
"answer_id": 148718,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "While rsync performs much better than scp when transferring files that \nexist on both hosts, this advantage is lost if the file exists only on one side \nof the connection.\n\nThe rsync based method may be considerably faster than the rcp based\nmethods when writing to the remote system. Reading files to the local\nmachine is no faster than with a direct copy.\n\nThis method supports the ‘-p’ hack.\n"
},
{
"answer_id": 148760,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "ControlMaster auto"
},
{
"answer_id": 10661141,
"author": "Ryan C. Thompson",
"author_id": 125921,
"author_profile": "https://Stackoverflow.com/users/125921",
"pm_score": 0,
"selected": false,
"text": "sftp tramp-gvfs-methods"
},
{
"answer_id": 10661439,
"author": "phils",
"author_id": 324105,
"author_profile": "https://Stackoverflow.com/users/324105",
"pm_score": 3,
"selected": false,
"text": "tramp-methods rsyncc scpc tramp-default-method shell rgrep find-grep-dired"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
] |
148,587
|
<p>I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?</p>
|
[
{
"answer_id": 148639,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 2,
"selected": false,
"text": "lock void AddItemToList(object o)\n{\n lock(myBindingList)\n {\n myBindingList.Add(o);\n }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23385/"
] |
148,594
|
<p>Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks.</p>
<p>The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed?</p>
<p>Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?</p>
|
[
{
"answer_id": 148608,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 2,
"selected": false,
"text": "var worker = new BackgroundWorker();\nworker.DoWork += delegate {\n Thread.Sleep(30000); \n DoStuff();\n} \nworker.RunWorkerAsync();\n"
},
{
"answer_id": 148649,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 4,
"selected": true,
"text": "public Timer(\n TimerCallback callback,\n Object state,\n TimeSpan dueTime,\n TimeSpan period\n)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
148,601
|
<p>Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?</p>
<p>I would like to be able to write something like this:</p>
<pre><code>#if ($a lt Long.MAX_VALUE)
</code></pre>
<p>but this is apparently not the right syntax.</p>
|
[
{
"answer_id": 148650,
"author": "Angelo van der Sijpt",
"author_id": 19144,
"author_profile": "https://Stackoverflow.com/users/19144",
"pm_score": 3,
"selected": false,
"text": "context.put(\"MaxLong\", Long.MAX_VALUE);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4728/"
] |
148,648
|
<p>i work with sql server, but i must migrate to an application with Oracle DB.
for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle?</p>
|
[
{
"answer_id": 148691,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "explain plan explain plan for <sql query>\n"
},
{
"answer_id": 22371322,
"author": "JaMeEL",
"author_id": 1321316,
"author_profile": "https://Stackoverflow.com/users/1321316",
"pm_score": 2,
"selected": false,
"text": "create table sql_exec_before as\nselect executions,hash_value\nfrom v$sqlarea\n/\n create table sql_exec_after as\nselect executions, hash_value\nfrom v$sqlarea\n/\n select aft.hash_value\nfrom sql_exec_after aft\nleft outer join sql_exec_before bef\n on aft.hash_value = bef.hash_value \nwhere aft.executions > bef.executions\n or bef.executions is null;\n/\n select hash_value, sql_text\nfrom v$sqltext\nwhere hash_value in (\n select aft.hash_value\n from sql_exec_after aft\n left outer join sql_exec_before bef\n on aft.hash_value = bef.hash_value\n where aft.executions > bef.executions\n or bef.executions is null;\n)\norder by\n hash_value, piece\n/\n drop table sql_exec_before\n/\n\ndrop table sql_exec_after\n/\n"
},
{
"answer_id": 23002169,
"author": "q3kep",
"author_id": 3521805,
"author_profile": "https://Stackoverflow.com/users/3521805",
"pm_score": 4,
"selected": false,
"text": "alter system set timed_statistics=true\n alter session set timed_statistics=true --if want to trace your own session\n select value from v$parameter p\nwhere name='max_dump_file_size' \n select sid, serial# from v$session\n where ...your_search_params...\n begin\n sys.dbms_system.set_ev(sid, serial#, 10046, 12, '');\n end;\n begin\n sys.dbms_system.set_ev(sid, serial#, 10046, 0, '');\nend;\n alter session set events '10046 trace name context forever, level 12';\n alter session set events '10046 trace name context off';\n select value from v$parameter p\n where name='user_dump_dest'\n select p.spid from v$session s, v$process p\n where s.paddr=p.addr\n and ...your_search_params...\n alter session set tracefile_identifier='UniqueString'; \n TKPROF C:\\ORACLE\\admin\\databaseSID\\udump>\nC:\\ORACLE\\admin\\databaseSID\\udump>tkprof my_trace_file.trc output=my_file.prf\nTKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004\nCopyright (c) 1982, 2002, Oracle Corporation. All rights reserved.\nC:\\ORACLE\\admin\\databaseSID\\udump>\n set serveroutput on size 30000;\ndeclare\n ALevel binary_integer;\nbegin\n SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel);\n if ALevel = 0 then\n DBMS_OUTPUT.Put_Line('sql_trace is off');\n else\n DBMS_OUTPUT.Put_Line('sql_trace is on');\n end if;\nend;\n/\n"
},
{
"answer_id": 23989219,
"author": "sergiu",
"author_id": 3256708,
"author_profile": "https://Stackoverflow.com/users/3256708",
"pm_score": 5,
"selected": false,
"text": "SELECT \n S.LAST_ACTIVE_TIME, \n S.MODULE,\n S.SQL_FULLTEXT, \n S.SQL_PROFILE,\n S.EXECUTIONS,\n S.LAST_LOAD_TIME,\n S.PARSING_USER_ID,\n S.SERVICE \nFROM\n SYS.V_$SQL S, \n SYS.ALL_USERS U\nWHERE\n S.PARSING_USER_ID=U.USER_ID \n AND UPPER(U.USERNAME) IN ('oracle user name here') \nORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19261/"
] |
148,662
|
<p>Suppose I have one list:</p>
<pre><code>IList<int> originalList = new List<int>();
originalList.add(1);
originalList.add(5);
originalList.add(10);
</code></pre>
<p>And another list... </p>
<pre><code>IList<int> newList = new List<int>();
newList.add(1);
newList.add(5);
newList.add(7);
newList.add(11);
</code></pre>
<p>How can I update originalList so that: </p>
<ol>
<li>If the int appears in newList, keep</li>
<li>If the int does not appear in newList, remove</li>
<li>Add any ints from newList into originalList that aren't there already</li>
</ol>
<p>Thus - making the contents of originalList:</p>
<pre><code>{ 1, 5, 7, 11 }
</code></pre>
<p>The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new.</p>
<p>EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!</p>
|
[
{
"answer_id": 148684,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "originalList = newList;\n originalList = new List<int>(newList);\n"
},
{
"answer_id": 148711,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 0,
"selected": false,
"text": "List<int> firstList = new List<int>() {1, 2, 3, 4, 5};\nList<int> secondList = new List<int>() {1, 3, 5, 7, 9};\n\nList<int> newList = new List<int>();\n\nforeach (int i in firstList)\n{\n newList.Add(i);\n}\n\nforeach (int i in secondList)\n{\n if (!newList.Contains(i))\n {\n newList.Add(i);\n }\n}\n"
},
{
"answer_id": 148716,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": true,
"text": "for(int i = originalList.length-1; i >=0; --i)\n{\n if (!newList.Contains(originalList[i])\n originalList.RemoveAt(i);\n}\n\nforeach(int n in newList)\n{\n if (!originaList.Contains(n))\n originalList.Add(n);\n}\n"
},
{
"answer_id": 148722,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "originalList = new List<int>(\n from x in newList\n join y in originalList on x equals y into z\n from y in z.DefaultIfEmpty()\n select x);\n"
},
{
"answer_id": 148820,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 0,
"selected": false,
"text": "public class IEnumerableDiff<T>\n{\n private delegate bool Compare(T x, T y);\n\n private List<T> _inXAndY;\n private List<T> _inXNotY;\n private List<T> _InYNotX;\n\n /// <summary>\n /// Compare two IEnumerables.\n /// </summary>\n /// <param name=\"x\"></param>\n /// <param name=\"y\"></param>\n /// <param name=\"compareKeys\">True to compare objects by their keys using Data.GetObjectKey(); false to use object.Equals comparison.</param>\n public IEnumerableDiff(IEnumerable<T> x, IEnumerable<T> y, bool compareKeys)\n {\n _inXAndY = new List<T>();\n _inXNotY = new List<T>();\n _InYNotX = new List<T>();\n Compare comparer = null;\n bool hit = false;\n\n if (compareKeys)\n {\n comparer = CompareKeyEquality;\n }\n else\n {\n comparer = CompareObjectEquality;\n }\n\n\n foreach (T xItem in x)\n {\n hit = false;\n foreach (T yItem in y)\n {\n if (comparer(xItem, yItem))\n {\n _inXAndY.Add(xItem);\n hit = true;\n break;\n }\n }\n if (!hit)\n {\n _inXNotY.Add(xItem);\n }\n }\n\n foreach (T yItem in y)\n {\n hit = false;\n foreach (T xItem in x)\n {\n if (comparer(yItem, xItem))\n {\n hit = true;\n break;\n }\n }\n if (!hit)\n {\n _InYNotX.Add(yItem);\n }\n }\n }\n\n /// <summary>\n /// Adds and removes items from the x (current) list so that the contents match the y (new) list.\n /// </summary>\n /// <param name=\"x\"></param>\n /// <param name=\"y\"></param>\n /// <param name=\"compareKeys\"></param>\n public static void SyncXList(IList<T> x, IList<T> y, bool compareKeys)\n {\n var diff = new IEnumerableDiff<T>(x, y, compareKeys);\n foreach (T item in diff.InXNotY)\n {\n x.Remove(item);\n }\n foreach (T item in diff.InYNotX)\n {\n x.Add(item);\n }\n }\n\n public IList<T> InXAndY\n {\n get { return _inXAndY; }\n }\n\n public IList<T> InXNotY\n {\n get { return _inXNotY; }\n }\n\n public IList<T> InYNotX\n {\n get { return _InYNotX; }\n }\n\n public bool ContainSameItems\n {\n get { return _inXNotY.Count == 0 && _InYNotX.Count == 0; }\n }\n\n private bool CompareObjectEquality(T x, T y)\n {\n return x.Equals(y);\n }\n\n private bool CompareKeyEquality(T x, T y)\n {\n object xKey = Data.GetObjectKey(x);\n object yKey = Data.GetObjectKey(y);\n return xKey.Equals(yKey);\n }\n\n}\n"
},
{
"answer_id": 149368,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "originalList.RemoveAll(x => !newList.Contains(x));\noriginalList.AddRange(newList.Where(x => !originalList.Contains(x)));\n class EqualThingTester : IEqualityComparer<Thing>\n{\n public bool Equals(Thing x, Thing y)\n {\n return x.ParentID.Equals(y.ParentID);\n }\n\n public int GetHashCode(Thing obj)\n {\n return obj.ParentID.GetHashCode();\n }\n}\n originalList.RemoveAll(x => !newList.Contains(x, new EqualThingTester()));\noriginalList.AddRange(newList.Where(x => !originalList.Contains(x, new EqualThingTester())));\n originalList.RemoveAll(x => !newList.Contains(x, new EqualThingTester()));\noriginalList.AddRange(newList.Except(originalList, new EqualThingTester()));\n"
},
{
"answer_id": 149721,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "var List3 = List1.Intersect(List2);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] |
148,669
|
<p>This <strike>is clearly not</strike> appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.</p>
<pre><code>//The constructor
public Page_Index() {
//create a local value
string currentValue = "This is the FIRST value";
//use the local variable in a delegate that fires later
this.Load += delegate(object sender, EventArgs e) {
Response.Write(currentValue);
};
//change it again
currentValue = "This is the MODIFIED value";
}
</code></pre>
<p>The value that is output is the second value <em>"Modified"</em>. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?</p>
<p>[Edit]: Given some of the comments, changing the original sentence some...</p>
|
[
{
"answer_id": 148688,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "class Foo {\n public string currentValue; // yes, it is a field\n\n public void SomeMethod(object sender, EventArgs e) {\n Response.Write(currentValue);\n }\n}\n...\npublic Page_Index() {\n Foo foo = new Foo();\n foo.currentValue = \"This is the FIRST value\";\n this.Load += foo.SomeMethod;\n\n foo.currentValue = \"This is the MODIFIED value\";\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091/"
] |
148,676
|
<p>I'm writing a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application which is supposed to play three sound files and at the end of each sound file, it's to change the source of an image.</p>
<p>I can get it to play the sounds using <code>System.Media.SoundPlayer</code>. However, it seems to play the sound in a different thread, continuing on.</p>
<p>The net effect of this is that only the last sound is played and all the images are changed.</p>
<p>I've tried <code>Thread.Sleep</code>, but it sleeps the whole GUI and after the sleep period everything happens at once and the last sound it played.</p>
<p><strong>UPDATE</strong></p>
<p>I thought PlaySynch was working, but it seems to freeze my GUI which is less than ideal. What else can I do?</p>
|
[
{
"answer_id": 865861,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"WinMM.dll\")]\npublic static extern bool PlaySound(byte[]wfname, int fuSound);\n\n// flag values for SoundFlags argument on PlaySound\npublic static int SND_SYNC = 0x0000; // Play synchronously (default).\npublic static int SND_ASYNC = 0x0001; // Play asynchronously.\npublic static int SND_NODEFAULT = 0x0002; // Silence (!default) if sound not found.\npublic static int SND_MEMORY = 0x0004; // PszSound points to a memory file.\npublic static int SND_LOOP = 0x0008; // Loop the sound until next sndPlaySound.\npublic static int SND_NOSTOP = 0x0010; // Don't stop any currently playing sound.\npublic static int SND_NOWAIT = 0x00002000; // Don't wait if the driver is busy.\npublic static int SND_ALIAS = 0x00010000; // Name is a registry alias.\npublic static int SND_ALIAS_ID = 0x00110000; // Alias is a predefined ID.\npublic static int SND_FILENAME = 0x00020000; // Name is file name.\npublic static int SND_RESOURCE = 0x00040004; // Name is resource name or atom.\npublic static int SND_PURGE = 0x0040; // Purge non-static events for task.\npublic static int SND_APPLICATION = 0x0080; // Look for application-specific association.\nprivate Thread t; // used for pausing\nprivate string bname;\nprivate int soundFlags;\n\n//-----------------------------------------------------------------\npublic void Play(string wfname, int SoundFlags)\n{\n byte[] bname = new Byte[256]; //Max path length\n bname = System.Text.Encoding.ASCII.GetBytes(wfname);\n this.bname = bname;\n this.soundFlags = SoundFlags;\n t = new Thread(play);\n t.Start();\n}\n//-----------------------------------------------------------------\n\nprivate void play()\n{\n PlaySound(bname, soundFlags)\n}\n\npublic void StopPlay()\n{\n t.Stop();\n}\n\npublic void Pause()\n{\n t.Suspend(); // Yeah, I know it's obsolete, but it works.\n}\n\npublic void Resume()\n{\n t.Resume(); // Yeah, I know it's obsolete, but it works.\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
148,681
|
<p>I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We also have version problems if we don't load the classes dynamically at run time from the AppServer library.</p>
<p>Now, I just hit a problem where I need to talk to two different AppServers and found that depending on whose classes I load first I might break badly... Is there any way to force the unloading of the class without actually killing the JVM?</p>
<p>Hope this makes sense</p>
|
[
{
"answer_id": 148762,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 6,
"selected": false,
"text": "java.x sun.x"
},
{
"answer_id": 46758814,
"author": "Aleksander Drozd",
"author_id": 7454847,
"author_profile": "https://Stackoverflow.com/users/7454847",
"pm_score": -1,
"selected": false,
"text": "java.lang.System.gc()"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469/"
] |
148,689
|
<p>Is there an iSeries command to export the data in a table to CSV format?</p>
<p>I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program.</p>
|
[
{
"answer_id": 148915,
"author": "Chris Smith",
"author_id": 9073,
"author_profile": "https://Stackoverflow.com/users/9073",
"pm_score": 1,
"selected": false,
"text": "Comma Separated Variable (CSV)"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23447/"
] |
148,704
|
<p>I've got the following user control:</p>
<pre><code><TabItem
x:Name="Self"
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
>
<TabItem.Header>
<!-- This works -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
</TabItem.Header>
<TabItem.ContentTemplate>
<DataTemplate>
<!-- This binds to "Self" in the surrounding window's namespace -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
</code></pre>
<p>This custom TabItem defines a <code>DependencyProperty</code> 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the <code>TabItem</code>'s <code>DataTemplate</code>. But due to strange interactions, the <code>TextBlock</code> within the <code>DataTemplate</code> gets bound to the <strong>parent container</strong> of the <code>TabItem</code>, which also is called "Self", but defined in another Xaml file.</p>
<h2>Question</h2>
<p>Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate?</p>
<h2>What I already tried</h2>
<ul>
<li><code>TemplateBinding</code>: Tries to bind to the ContentPresenter within the guts of the <code>TabItem</code>.</li>
<li><code>FindAncestor, AncestorType={x:Type TabItem}</code>: Doesn't find the <code>TabItem</code> parent. This doesn't work either, when I specify the <code>MyTabItem</code> type.</li>
<li><code>ElementName=Self</code>: Tries to bind to a control with that name in the wrong scope (parent container, not <code>TabItem</code>). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container.</li>
</ul>
<p>I assume I could replace the whole <code>ControlTemplate</code> to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the <code>TabItem</code> without having to maintain the whole <code>ControlTemplate</code>, I'm very reluctant to do so.</p>
<h2>Edit</h2>
<p>Meanwhile I have found out that the problem is: <code>TabControl</code>s can't have (any) <code>ItemsTemplate</code> (that includes the <code>DisplayMemberPath</code>) if the <code>ItemsSource</code> contains <code>Visual</code>s. There <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/" rel="nofollow noreferrer">a thread on MSDN Forum explaining why</a>. </p>
<p>Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!</p>
|
[
{
"answer_id": 184582,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 1,
"selected": false,
"text": "<TabItem \n x:Name=\"Self\"\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n >\n <TabItem.ContentTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding Path=ShortLabel}\"/>\n </DataTemplate>\n </TabItem.ContentTemplate>\n</TabItem>\n DataContext=\"{Binding RelativeSource={RelativeSource self}}\"\n"
},
{
"answer_id": 255593,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 2,
"selected": false,
"text": "<TabItem\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n Header=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\"\n Content=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\" />\n <TabItem\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n Header=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\"\n Content=\"{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}\">\n <TabItem.ContentTemplate>\n <DataTemplate TargetType=\"{x:Type ComplexType}\">\n <TextBlock Text=\"{Binding Property}\" />\n </DataTemplate>\n </TabItem.ContentTemplate>\n</TabItem>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
148,728
|
<p>I'd like to add scrolling capability to a <code>javax.swing.JDesktopPane</code>. But wrapping in a <code>javax.swing.JScrollPane</code> does not produce the desired behavior.</p>
<p><a href="http://www.google.com/search?q=scrollable+jdesktoppane" rel="nofollow noreferrer">Searching the web</a> shows that this has been an issue for quite some time. There are <a href="http://jscroll.sourceforge.net" rel="nofollow noreferrer">some</a> <a href="http://www.javaworld.com/javaworld/jw-11-2001/jw-1130-jscroll.html" rel="nofollow noreferrer">solutions</a> out there, but they seem to be pretty old, and I'm not not completely satisfied with them.</p>
<p>What <strong>actively maintained</strong> solutions do you know?</p>
|
[
{
"answer_id": 148743,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 3,
"selected": false,
"text": "JScrollableDesktopPane."
},
{
"answer_id": 30873083,
"author": "Atta",
"author_id": 5016182,
"author_profile": "https://Stackoverflow.com/users/5016182",
"pm_score": 2,
"selected": false,
"text": "JScrollableDesktopPane public class Window extends Frame {\n JScrollPane scrollContainer = new JScrollPane();\n JDesktopPane mainWorkingPane = new JDesktopPane();\n\n public Window() {\n scrollContainer.setViewportView(mainWorkingPane);\n\n addComponentListener(new ComponentAdapter() {\n public void componentResized(ComponentEvent evt) {\n revalidateDesktopPane();\n }\n });\n }\n\n private void revalidateDesktopPane() {\n Dimension dim = new Dimension(0,0);\n Component[] com = mainWorkingPane.getComponents();\n for (int i=0 ; i<com.length ; i++) {\n int w = (int) dim.getWidth()+com[i].getWidth();\n int h = (int) dim.getHeight()+com[i].getHeight();\n dim.setSize(new Dimension(w,h));\n }\n mainWorkingPane.setPreferredSize(dim);\n mainWorkingPane.revalidate();\n revalidate();\n repaint(); \n }\n}\n JDesktopPane JScrollPane JDesktopPane"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13940/"
] |
148,729
|
<p>I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel.</p>
<p>However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus.</p>
<p>On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still <em>exist</em>, just not <em>display</em> in the way it does now.</p>
<p>Any suggestions? :-)</p>
|
[
{
"answer_id": 148848,
"author": "Michael L Perry",
"author_id": 7668,
"author_profile": "https://Stackoverflow.com/users/7668",
"pm_score": 5,
"selected": false,
"text": "public class NoFocusCueButton : Button\n{\n protected override bool ShowFocusCues\n {\n get\n {\n return false;\n }\n }\n}\n"
},
{
"answer_id": 360846,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "NotifyDefault() void myButton_GotFocus(object sender, EventArgs e)\n{\n myButton.NotifyDefault(false);\n}\n"
},
{
"answer_id": 1570320,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "button1.focus();"
},
{
"answer_id": 1832466,
"author": "Marcus Rex",
"author_id": 222864,
"author_profile": "https://Stackoverflow.com/users/222864",
"pm_score": 4,
"selected": false,
"text": "public partial class CustomButton: Button\n{\n public ButtonPageButton()\n {\n InitializeComponent();\n\n this.SetStyle(ControlStyles.Selectable, false);\n }\n}\n"
},
{
"answer_id": 4339623,
"author": "ketchup201",
"author_id": 411254,
"author_profile": "https://Stackoverflow.com/users/411254",
"pm_score": -1,
"selected": false,
"text": "<Button HorizontalAlignment=\"Left\" Margin=\"0,2\" \n Command=\"{Binding OpenSuspendedJobCommand, Mode=OneWay}\" \n Focusable=\"False\"\n Style=\"{StaticResource ActionButton}\" Content=\"Open Job...\" />\n"
},
{
"answer_id": 4798842,
"author": "Josh Stribling",
"author_id": 464386,
"author_profile": "https://Stackoverflow.com/users/464386",
"pm_score": 5,
"selected": false,
"text": "public class CustomButton : Button\n{\n public CustomButton()\n : base()\n {\n // Prevent the button from drawing its own border\n FlatAppearance.BorderSize = 0;\n FlatStyle = System.Windows.Forms.FlatStyle.Flat;\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n base.OnPaint(e);\n\n // Draw Border using color specified in Flat Appearance\n Pen pen = new Pen(FlatAppearance.BorderColor, 1);\n Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);\n e.Graphics.DrawRectangle(pen, rectangle);\n pen.Dispose();\n }\n}\n public class ToolButton : Button\n{\n private bool ShowBorder { get; set; }\n\n public ToolButton()\n : base()\n {\n // Prevent the button from drawing its own border\n FlatAppearance.BorderSize = 0;\n\n // Set up a blue border and back colors for the button\n FlatAppearance.BorderColor = Color.FromArgb(51, 153, 255);\n FlatAppearance.CheckedBackColor = Color.FromArgb(153, 204, 255);\n FlatAppearance.MouseDownBackColor = Color.FromArgb(153, 204, 255);\n FlatAppearance.MouseOverBackColor = Color.FromArgb(194, 224, 255);\n FlatStyle = System.Windows.Forms.FlatStyle.Flat;\n\n // Set the size for the button to be the same as a ToolStripButton\n Size = new System.Drawing.Size(23, 22);\n }\n\n protected override void OnMouseEnter(EventArgs e)\n {\n base.OnMouseEnter(e);\n\n // Show the border when you hover over the button\n ShowBorder = true;\n }\n\n protected override void OnMouseLeave(EventArgs e)\n {\n base.OnMouseLeave(e);\n\n // Hide the border when you leave the button\n ShowBorder = false;\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n base.OnPaint(e);\n\n // The DesignMode check here causes the border to always draw in the Designer\n // This makes it easier to place your button\n if (DesignMode || ShowBorder)\n {\n Pen pen = new Pen(FlatAppearance.BorderColor, 1);\n Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);\n e.Graphics.DrawRectangle(pen, rectangle);\n pen.Dispose();\n }\n }\n\n\n\n // Prevent Text from being set on the button (since it will be an icon)\n [Browsable(false)]\n public override string Text { get { return \"\"; } set { base.Text = \"\"; } }\n\n [Browsable(false)]\n public override ContentAlignment TextAlign { get { return base.TextAlign; } set { base.TextAlign = value; } }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
148,733
|
<p>I want to be able to intercept the shutdown event in C# for Windows Vista. Due to the advanced security features with Vista, any applications that are running after the shutdown command is called are halted and displayed in a list, prompting the user to do something with them.</p>
<p>Does anybody know how to overcome this and what events I need to be using in Vista.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 148771,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "System.Environment.HasShutdownStarted\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
148,742
|
<p>In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?</p>
|
[
{
"answer_id": 148753,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 2,
"selected": false,
"text": "DriveInfo[] allDrives = DriveInfo.GetDrives();\n\nforeach (DriveInfo d in allDrives)\n{\n Console.WriteLine(\"Drive {0}\", d.Name);\n Console.WriteLine(\" File type: {0}\", d.DriveType);\n}\n"
},
{
"answer_id": 148811,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 5,
"selected": true,
"text": "public enum DriveType\n{\n Unknown, // The type of drive is unknown. \n NoRootDirectory, // The drive does not have a root directory. \n Removable, // The drive is a removable storage device, \n // such as a floppy disk drive or a USB flash drive. \n Fixed, // The drive is a fixed disk. \n Network, // The drive is a network drive. \n CDRom, // The drive is an optical disc device, such as a CD \n // or DVD-ROM. \n Ram // The drive is a RAM disk. \n}\n DriveInfo[] allDrives = DriveInfo.GetDrives();\n foreach (DriveInfo d in allDrives)\n {\n Console.WriteLine(\"Drive {0}, Type {1}\", d.Name, d.DriveType);\n }\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13341/"
] |
148,747
|
<p>What is the difference between a <strong><em>framework</em></strong> and a <strong><em>library</em></strong>? </p>
<p>I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development.</p>
|
[
{
"answer_id": 66808163,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 0,
"selected": false,
"text": ".jar Library your code ->(has) Library API\n Framework Inversion of Control(IoC) container IoC your code ->(has) and ->(implements) Framework API\n"
},
{
"answer_id": 69122217,
"author": "David Callanan",
"author_id": 1541397,
"author_profile": "https://Stackoverflow.com/users/1541397",
"pm_score": -1,
"selected": false,
"text": "map filter sort reduce"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023/"
] |
148,764
|
<p>In the vxWorks shell, there are a number of routines you can use to display information about the system. </p>
<p>These routines are usually referred to as <strong>show</strong> routines because they tend to have the form of "xxxShow".</p>
<p>Is there a list of these routines available?</p>
|
[
{
"answer_id": 809782,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "> lkup \"Show\"\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
148,786
|
<p>I have an array of items that are time sensitive. After an amount of time, the last item needs to fall off and a new item is put at the beginning.</p>
<p>What is the best way to do this?</p>
|
[
{
"answer_id": 148814,
"author": "user7375",
"author_id": 7375,
"author_profile": "https://Stackoverflow.com/users/7375",
"pm_score": 0,
"selected": false,
"text": "original = new[] { newItem }.Concat(\n original.Take(original.Count() - 1)).ToArray()\n"
},
{
"answer_id": 148829,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "Queue Insert(0, x) RemoveAt(0)"
},
{
"answer_id": 149578,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "int queue[SIZE];\nint ndx=0; // start at the beginning of the array\nint end=SIZE-1;\nint newitem;\nwhile(1){\n cin >> newitem;\n if(!newitem) // quit if it's a 0\n break;\n if(ndx>end) // need to loop around the end of the array\n ndx=0;\n queue[ndx] = newitem;\n ndx++\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
148,790
|
<p>I've inherited a VB.net project that generates 2 DLLS: one for the web app, and another for the "business layer". This is for a sub-app of a larger web site. (Using VS2005).</p>
<p>The problem is that that something doesn't smell right with the DLL & namespace structure, and I'd like to know if there are any performance impacts.</p>
<p>The main web app is "Foo", and generates Foo.dll. Foo.dll contains namespace App.Foo, which contains the classes for all the pages, user controls, etc.</p>
<p>There's also a project "FooLib" that generates FooLib.dll. FooLib.dll also contains an App.Foo namespace, which contains a bunch of class definitions. There are a few other namespaces like App.Foo.Data, App.Foo.Logic, etc.</p>
<p>Is there anything wrong with this? How does the runtime find a class across multiple DLLs?</p>
|
[
{
"answer_id": 148861,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 1,
"selected": false,
"text": "using Foo.App.Foo;\nusing FooLib = FooLib.App.Foo;\n bar x = new bar();\n FooLib.bar x = new FooLib.bar();\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4782/"
] |
148,795
|
<p>Selecting the union:</p>
<pre><code>select * from table1
union
select * from table1_backup
</code></pre>
<p>What is the query to select the intersection?</p>
|
[
{
"answer_id": 148803,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "select * from table1 \nintersect\nselect * from table1_backup\n"
},
{
"answer_id": 148837,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "select distinct * from (select * from table1 union select * from table1_backup) \n"
},
{
"answer_id": 148846,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 3,
"selected": false,
"text": "SELECT *\nFROM table1\nWHERE EXISTS\n(SELECT *\nFROM table1_backup\nWHERE table1.pk = table1_backup.pk)\n"
},
{
"answer_id": 1242088,
"author": "cesar",
"author_id": 152993,
"author_profile": "https://Stackoverflow.com/users/152993",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE table1(\nid INT(10),\nfk_id INT(10),\nPRIMARY KEY (id, fk_id),\nFOREIGN KEY table1(id) REFERENCES another_table(id),\nFOREIGN KEY table1(fk_id) REFERENCES other_table(id)\n);\n\nSELECT table1.* FROM table1 as t0\nINNER JOIN table1 as a ON (t0.id = a.id and fk_id=1)\nINNER JOIN table1 as b ON (t0.id = b.id and fk_id=2)\nINNER JOIN table1 as c ON (t0.id = c.id and fk_id=3)\nORDER BY table1.id;\n"
},
{
"answer_id": 1974831,
"author": "Stephen Wuebker",
"author_id": 240226,
"author_profile": "https://Stackoverflow.com/users/240226",
"pm_score": -1,
"selected": false,
"text": "SELECT * FROM table1, table2 WHERE table1.pk=table2.pk;\n"
},
{
"answer_id": 3487193,
"author": "ovais.tariq",
"author_id": 345383,
"author_profile": "https://Stackoverflow.com/users/345383",
"pm_score": 0,
"selected": false,
"text": "SELECT a.id, a.name\nFROM a INNER JOIN b\nUSING (id, name)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
148,807
|
<p>Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.</p>
<p>Thanks,<br>
Florian </p>
<p><strong>Edit:</strong> nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.</p>
|
[
{
"answer_id": 148883,
"author": "user7375",
"author_id": 7375,
"author_profile": "https://Stackoverflow.com/users/7375",
"pm_score": -1,
"selected": false,
"text": " WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE MethodCa == 0 AND \n !IsPublic AND !IsEntryPoint AND !IsExplicitInterfaceImpl AND \n !IsClassConstructor AND !IsFinalizer\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4445/"
] |
148,817
|
<p>Is there a component available list FileUpload which shows files on the server, not the client? </p>
<p>I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.</p>
|
[
{
"answer_id": 148913,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 1,
"selected": false,
"text": "public sub file_DatabindListbox(directoryPath as string)\n for each fName as string in io.directory(directorypath).getfilenames()\n dim li as new listitem \n li.text = io.path.getfilename(fName)\n li.value = fName\n myFileListbox.Items.Add(li)\n next\nend sub \n"
},
{
"answer_id": 150455,
"author": "Jacob T. Nielsen",
"author_id": 20032,
"author_profile": "https://Stackoverflow.com/users/20032",
"pm_score": 0,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n SetChildFolders(trvFiles.Nodes, @\"C:\\MyFolder\");\n}\n\n private void SetChildFolders(TreeNodeCollection nodes, string path)\n {\n foreach (string directory in Directory.GetDirectories(path))\n {\n DirectoryInfo dirInfo = new DirectoryInfo(directory);\n TreeNode node = new TreeNode(dirInfo.Name, dirInfo.FullName);\n\n SetChildFolders(node.ChildNodes, dirInfo.FullName);\n SetChildFiles(node.ChildNodes, dirInfo.FullName);\n\n trvFiles.Nodes.Add(node);\n }\n }\n\n private void SetChildFiles(TreeNodeCollection nodes, string path)\n {\n foreach (string file in Directory.GetFiles(path))\n {\n FileInfo fileInfo = new FileInfo(file);\n nodes.Add(new TreeNode(fileInfo.Name, fileInfo.FullName));\n }\n }\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836/"
] |
148,828
|
<p>There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the <code>as</code> operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?</p>
|
[
{
"answer_id": 148841,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": false,
"text": "instanceof is as if(myThing instanceof Foo) {\n Foo myFoo = (Foo)myThing; //Never throws ClassCastException\n ...\n}\n"
},
{
"answer_id": 148844,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 5,
"selected": false,
"text": "return (x instanceof Foo) ? (Foo) x : null;\n interface Foo {\n public void doBar();\n}\nclass NullFoo implements Foo {\n public void doBar() {} // do nothing\n}\nclass FooUtils {\n public static Foo asFoo(Object o) {\n return (o instanceof Foo) ? (Foo) o : new NullFoo();\n }\n}\nclass Client {\n public void process() {\n Object o = ...;\n Foo foo = FooUtils.asFoo(o);\n foo.doBar(); // don't need to check for null in client\n }\n}\n"
},
{
"answer_id": 148851,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": -1,
"selected": false,
"text": "as<T,Type> (left, right) \nwhich evaluates to \nif (typeof(left) == right)\n return (right)left\nelse\n return null\n"
},
{
"answer_id": 148932,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 4,
"selected": false,
"text": "package com.stackoverflow.examples;\npublic class Utils {\n @SuppressWarnings(\"unchecked\")\n public static <T> T safeCast(Object obj, Class<T> type) {\n if (type.isInstance(obj)) {\n return (T) obj;\n }\n return null;\n }\n}\n package com.stackoverflow.examples;\nimport static com.stackoverflow.examples.Utils.safeCast;\nimport static junit.framework.Assert.assertNotNull;\nimport static junit.framework.Assert.assertNull;\n\nimport org.junit.Test;\n\npublic class UtilsTest {\n\n @Test\n public void happyPath() {\n Object x = \"abc\";\n String y = safeCast(x, String.class);\n assertNotNull(y);\n }\n\n @Test\n public void castToSubclassShouldFail() {\n Object x = new Object();\n String y = safeCast(x, String.class);\n assertNull(y);\n }\n\n @Test\n public void castToUnrelatedTypeShouldFail() {\n Object x = \"abc\";\n Integer y = safeCast(x, Integer.class);\n assertNull(y);\n }\n}\n"
},
{
"answer_id": 148949,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 7,
"selected": true,
"text": "public static <T> T as(Class<T> clazz, Object o){\n if(clazz.isInstance(o)){\n return clazz.cast(o);\n }\n return null;\n}\n\nas(A.class, new Object()) --> null\nas(B.class, new B()) --> B\n"
},
{
"answer_id": 35357496,
"author": "Dmitry Klochkov",
"author_id": 960626,
"author_profile": "https://Stackoverflow.com/users/960626",
"pm_score": 2,
"selected": false,
"text": "Object o = new Integer(1);\n\nOptional.ofNullable(o)\n .filter(Number.class::isInstance)\n .map(Number.class::cast)\n .ifPresent(n -> System.out.print(\"o is a number\"));\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23424/"
] |
148,838
|
<p>I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails.</p>
<p>Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?</p>
|
[
{
"answer_id": 148947,
"author": "Dave Nolan",
"author_id": 9474,
"author_profile": "https://Stackoverflow.com/users/9474",
"pm_score": 5,
"selected": true,
"text": "LoadModule proxy_module modules/mod_proxy.so\nLoadModule proxy_http_module modules/mod_proxy_http.so\n<VirtualHost localhost:80>\n ServerName www.myapp.comm\n DocumentRoot \"C:/web/myapp/public\"\n ProxyPass / http://www.myapp.com:3000/\n ProxyPassReverse / http://www.myapp.com:3000/\n ProxyPreserveHost On\n</VirtualHost>\n httpd.conf httpd-vhost.conf C:\\web\\myapp mongrel_rails start -p 3000 -e production\n -p 3000 mongrel_service"
},
{
"answer_id": 2546975,
"author": "danny",
"author_id": 305293,
"author_profile": "https://Stackoverflow.com/users/305293",
"pm_score": 2,
"selected": false,
"text": "gem install mongrel_service\n gem install mongrel_service --platform x86-mswin32\n mongrel_rails service::install --name MyApp -e production -p 3001 -a 0.0.0.0\n mongrel_rails service::remove --name MyApp\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
] |
148,853
|
<p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
|
[
{
"answer_id": 149917,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 4,
"selected": true,
"text": "class cache(object):\n def __init__(self, fun):\n self.fun = fun\n self.cache = {}\n\n def __call__(self, *args, **kwargs):\n key = str(args) + str(kwargs)\n try:\n return self.cache[key]\n except KeyError:\n self.cache[key] = rval = self.fun(*args, **kwargs)\n return rval\n except TypeError: # incase key isn't a valid key - don't cache\n return self.fun(*args, **kwargs)\n @cache\ndef get_url_src(url):\n return urllib.urlopen(url).read()\n"
},
{
"answer_id": 549017,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "if __name__ == \"__main__\": #!/usr/bin/env python\n\"\"\"\nurllib2 caching handler\nModified from http://code.activestate.com/recipes/491261/ by dbr\n\"\"\"\n\nimport os\nimport time\nimport httplib\nimport urllib2\nimport StringIO\nfrom hashlib import md5\n\ndef calculate_cache_path(cache_location, url):\n \"\"\"Checks if [cache_location]/[hash_of_url].headers and .body exist\n \"\"\"\n thumb = md5(url).hexdigest()\n header = os.path.join(cache_location, thumb + \".headers\")\n body = os.path.join(cache_location, thumb + \".body\")\n return header, body\n\ndef check_cache_time(path, max_age):\n \"\"\"Checks if a file has been created/modified in the [last max_age] seconds.\n False means the file is too old (or doesn't exist), True means it is\n up-to-date and valid\"\"\"\n if not os.path.isfile(path):\n return False\n cache_modified_time = os.stat(path).st_mtime\n time_now = time.time()\n if cache_modified_time < time_now - max_age:\n # Cache is old\n return False\n else:\n return True\n\ndef exists_in_cache(cache_location, url, max_age):\n \"\"\"Returns if header AND body cache file exist (and are up-to-date)\"\"\"\n hpath, bpath = calculate_cache_path(cache_location, url)\n if os.path.exists(hpath) and os.path.exists(bpath):\n return(\n check_cache_time(hpath, max_age)\n and check_cache_time(bpath, max_age)\n )\n else:\n # File does not exist\n return False\n\ndef store_in_cache(cache_location, url, response):\n \"\"\"Tries to store response in cache.\"\"\"\n hpath, bpath = calculate_cache_path(cache_location, url)\n try:\n outf = open(hpath, \"w\")\n headers = str(response.info())\n outf.write(headers)\n outf.close()\n\n outf = open(bpath, \"w\")\n outf.write(response.read())\n outf.close()\n except IOError:\n return True\n else:\n return False\n\nclass CacheHandler(urllib2.BaseHandler):\n \"\"\"Stores responses in a persistant on-disk cache.\n\n If a subsequent GET request is made for the same URL, the stored\n response is returned, saving time, resources and bandwidth\n \"\"\"\n def __init__(self, cache_location, max_age = 21600):\n \"\"\"The location of the cache directory\"\"\"\n self.max_age = max_age\n self.cache_location = cache_location\n if not os.path.exists(self.cache_location):\n os.mkdir(self.cache_location)\n\n def default_open(self, request):\n \"\"\"Handles GET requests, if the response is cached it returns it\n \"\"\"\n if request.get_method() is not \"GET\":\n return None # let the next handler try to handle the request\n\n if exists_in_cache(\n self.cache_location, request.get_full_url(), self.max_age\n ):\n return CachedResponse(\n self.cache_location,\n request.get_full_url(),\n set_cache_header = True\n )\n else:\n return None\n\n def http_response(self, request, response):\n \"\"\"Gets a HTTP response, if it was a GET request and the status code\n starts with 2 (200 OK etc) it caches it and returns a CachedResponse\n \"\"\"\n if (request.get_method() == \"GET\"\n and str(response.code).startswith(\"2\")\n ):\n if 'x-local-cache' not in response.info():\n # Response is not cached\n set_cache_header = store_in_cache(\n self.cache_location,\n request.get_full_url(),\n response\n )\n else:\n set_cache_header = True\n #end if x-cache in response\n\n return CachedResponse(\n self.cache_location,\n request.get_full_url(),\n set_cache_header = set_cache_header\n )\n else:\n return response\n\nclass CachedResponse(StringIO.StringIO):\n \"\"\"An urllib2.response-like object for cached responses.\n\n To determine if a response is cached or coming directly from\n the network, check the x-local-cache header rather than the object type.\n \"\"\"\n def __init__(self, cache_location, url, set_cache_header=True):\n self.cache_location = cache_location\n hpath, bpath = calculate_cache_path(cache_location, url)\n\n StringIO.StringIO.__init__(self, file(bpath).read())\n\n self.url = url\n self.code = 200\n self.msg = \"OK\"\n headerbuf = file(hpath).read()\n if set_cache_header:\n headerbuf += \"x-local-cache: %s\\r\\n\" % (bpath)\n self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf))\n\n def info(self):\n \"\"\"Returns headers\n \"\"\"\n return self.headers\n\n def geturl(self):\n \"\"\"Returns original URL\n \"\"\"\n return self.url\n\n def recache(self):\n new_request = urllib2.urlopen(self.url)\n set_cache_header = store_in_cache(\n self.cache_location,\n new_request.url,\n new_request\n )\n CachedResponse.__init__(self, self.cache_location, self.url, True)\n\n\nif __name__ == \"__main__\":\n def main():\n \"\"\"Quick test/example of CacheHandler\"\"\"\n opener = urllib2.build_opener(CacheHandler(\"/tmp/\"))\n response = opener.open(\"http://google.com\")\n print response.headers\n print \"Response:\", response.read()\n\n response.recache()\n print response.headers\n print \"After recache:\", response.read()\n main()\n"
},
{
"answer_id": 4138778,
"author": "Jason R. Coombs",
"author_id": 70170,
"author_profile": "https://Stackoverflow.com/users/70170",
"pm_score": 3,
"selected": false,
"text": "easy_install jaraco.net>=1.3 caching.quick_test() \"\"\"Quick test/example of CacheHandler\"\"\"\nimport logging\nimport urllib2\nfrom httplib2 import FileCache\nfrom jaraco.net.http.caching import CacheHandler\n\nlogging.basicConfig(level=logging.DEBUG)\nstore = FileCache(\".cache\")\nopener = urllib2.build_opener(CacheHandler(store))\nurllib2.install_opener(opener)\nresponse = opener.open(\"http://www.google.com/\")\nprint response.headers\nprint \"Response:\", response.read()[:100], '...\\n'\n\nresponse.reload(store)\nprint response.headers\nprint \"After reload:\", response.read()[:100], '...\\n'\n"
},
{
"answer_id": 4379976,
"author": "Olivier Berger",
"author_id": 648140,
"author_profile": "https://Stackoverflow.com/users/648140",
"pm_score": 1,
"selected": false,
"text": "def https_response(self, request, response):\n return self.http_response(request,response)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17865/"
] |
148,854
|
<p>I have a <code>DataGridView</code> with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears.</p>
<p>What am I doing wrong?</p>
<p>The code is as follows:</p>
<pre><code>foreach (SaleItem item in this.Invoice.SaleItems)
{
DataGridViewRow row = new DataGridViewRow();
gridViewParts.Rows.Add(row);
DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
cellQuantity.Value = item.Quantity;
row.Cells["colQuantity"] = cellQuantity;
DataGridViewCell cellDescription = new DataGridViewTextBoxCell();
cellDescription.Value = item.Part.Description;
row.Cells["colDescription"] = cellDescription;
DataGridViewCell cellCost = new DataGridViewTextBoxCell();
cellCost.Value = item.Price;
row.Cells["colUnitCost1"] = cellCost;
DataGridViewCell cellTotal = new DataGridViewTextBoxCell();
cellTotal.Value = item.Quantity * item.Price;
row.Cells["colTotal"] = cellTotal;
DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell();
cellPartNumber.Value = item.Part.Number;
row.Cells["colPartNumber"] = cellPartNumber;
}
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 887025,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "int i;\ni = gridViewParts.Rows.Add( new DataGridViewRow());\n\nDataGridViewCell cellQuantity = new DataGridViewTextBoxCell();\ncellQuantity.Value = item.Quantity;\ngridViewParts.Rows[i].Cells[\"colQuantity\"] = cellQuantity;\n"
},
{
"answer_id": 1600477,
"author": "Bobby",
"author_id": 180239,
"author_profile": "https://Stackoverflow.com/users/180239",
"pm_score": 3,
"selected": false,
"text": "DataGridView object[] buffer = new object[5];\nList<DataGridViewRow> rows = new List<DataGridViewRow>();\nforeach (SaleItem item in this.Invoice.SaleItems)\n{\n buffer[0] = item.Quantity;\n buffer[1] = item.Part.Description;\n buffer[2] = item.Price;\n buffer[3] = item.Quantity * item.Price;\n buffer[4] = item.Part.Number;\n\n rows.Add(new DataGridViewRow());\n rows[rows.Count - 1].CreateCells(gridViewParts, buffer);\n}\ngridViewParts.Rows.AddRange(rows.ToArray());\n List<DataGridViewRow> rows = new List<DataGridViewRow>();\nforeach (SaleItem item in this.Invoice.SaleItems)\n{\n rows.Add(new DataGridViewRow());\n rows[rows.Count - 1].CreateCells(gridViewParts,\n item.Quantity,\n item.Part.Description,\n item.Price,\n item.Quantity * item.Price,\n item.Part.Number\n );\n}\ngridViewParts.Rows.AddRange(rows.ToArray());\n DataGridView DataSource if(gridViewParts.CurrentRow != null)\n{\n SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem);\n // You can use item here without problems.\n}\n System.ComponentModel.INotifyPropertyChanged"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086/"
] |
148,857
|
<p>I have a function, parseQuery, that parses a SQL query into an abstract representation of that query.</p>
<p>I'm about to write a function that takes an abstract representation of a query and returns a SQL query string.</p>
<p>What should I call the second function?</p>
|
[
{
"answer_id": 149343,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 3,
"selected": false,
"text": "parseAbstract"
},
{
"answer_id": 1596671,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 2,
"selected": false,
"text": "DateTime.Parse( DateTime.Parse( myDate.ToString() ).ToString() );\n"
},
{
"answer_id": 5671933,
"author": "Xaqron",
"author_id": 313421,
"author_profile": "https://Stackoverflow.com/users/313421",
"pm_score": 0,
"selected": false,
"text": ".GetSqlQuery()"
},
{
"answer_id": 9656480,
"author": "Herman Junge",
"author_id": 699490,
"author_profile": "https://Stackoverflow.com/users/699490",
"pm_score": 2,
"selected": false,
"text": "> a = 'html': { 'head': {'title': 'My Page'}, 'body': { 'h1': 'Hello World', 'p': 'This is a Paragraph' } }\n\n> b = render(a)\n\n> console.log(b)\n\n<html>\n <head>\n <title>My Page</title>\n </head>\n <body>\n <h1>Hello World</h1>\n <p>This is a Paragraph</p>\n </body>\n</html>\n > c = parse(b)\n\n{ 'html': {\n 'head': {\n 'title': 'My Page'\n }\n 'body': {\n 'h1': 'Hello World',\n 'p': 'This is a Paragraph'\n }\n}\n"
},
{
"answer_id": 23025419,
"author": "David Paulo",
"author_id": 1631435,
"author_profile": "https://Stackoverflow.com/users/1631435",
"pm_score": 2,
"selected": false,
"text": "public class FooBarParser{\n\n public Foo parse(Bar bar);\n public Bar parse(Foo foo); \n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
148,867
|
<p>I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. </p>
<p>I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) </p>
<p>does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#? </p>
|
[
{
"answer_id": 149071,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 4,
"selected": false,
"text": "Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace();\nworkspace.PendRename( oldPath, newPath );\n"
},
{
"answer_id": 149096,
"author": "Jason Diller",
"author_id": 2187,
"author_profile": "https://Stackoverflow.com/users/2187",
"pm_score": 3,
"selected": false,
"text": "using Microsoft.TeamFoundation.Client; \nusing Microsoft.TeamFoundation.VersionControl.Client; \n\n\npublic void MoveFile( string tfsServer, string oldPath, string newPath )\n{\n TeamFoundationServer server = TeamFoundationServerFactory.GetServer( tfsServer, new UICredentialsProvider() ); \n server.EnsureAuthenticated(); \n VersionControlServer vcserver = server.GetService( typeof( VersionControlServer ); \n string currentUserName = server.AuthenticatedUserName;\n string currentComputerName = Environment.MachineName;\n Workspace[] wss = vcserver.QueryWorkspaces(null, currentUserName, currentComputerName);\n foreach (Workspace ws in wss)\n {\n\n foreach ( WorkingFolder wf in wfs )\n {\n bool bFound = false; \n if ( wf.LocalItem != null )\n {\n if ( oldPath.StartsWith( wf.LocalItem ) )\n {\n bFound = true; \n ws.PendRename( oldPath, newPath ); \n break; \n }\n }\n if ( bFound )\n break; \n }\n }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23460/"
] |
148,875
|
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level.</p>
<pre><code>DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)
</code></pre>
<p>I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.</p>
|
[
{
"answer_id": 148897,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 6,
"selected": true,
"text": "EXCEPT(\n{DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)},\n{DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)}\n)\n EXCEPT({the set i want}, {a set of members i dont want})\n"
},
{
"answer_id": 26279547,
"author": "Stan Bashtavenko",
"author_id": 806601,
"author_profile": "https://Stackoverflow.com/users/806601",
"pm_score": 2,
"selected": false,
"text": "select\n{[Module].[Hierarchy].[Module].Members - [Module].[Hierarchy].[Module].[Unknown]} on rows,\n{[Date].[Month-day].[Day Of Month].Members - [Date].[Month-day].[Day Of Month].[Unknown]} on columns\nfrom [StatsView]\nwhere {[Measures].[Maintainability Index]}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
148,879
|
<p>My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive?</p>
<p>I tried checking for "Full trust" like so:</p>
<pre><code>try
{
// Demand full trust permissions
PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted );
fullTrust.Demand();
// Perform normal application logic
}
catch( SecurityException )
{
// Report that permissions were not full trust
MessageBox.Show( "This application requires full-trust security permissions to execute." );
}
</code></pre>
<p>However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas?</p>
|
[
{
"answer_id": 148898,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 4,
"selected": false,
"text": "cd c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\nCasPol.exe -m -ag 1.2 -url file:///N:/your/network/path/* FullTrust\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23461/"
] |
148,882
|
<p>I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. </p>
<pre><code>resource = AllocateLotsOfMemory();
if (SomeCondition())
{
OnOddError(new OddErrorEventArgs(resource.StatusProperty));
resource.FreeLotsOfMemory();
return;
}
</code></pre>
<p>This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!).</p>
<p>The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. </p>
<p>Which makes some kind of sense. </p>
<p>The alternative might be something like</p>
<pre><code>resource = AllocateLotsOfMemory();
if (SomeCondition())
{
BigObject temporary = resource.StatusProperty;
resource.FreeLotsOfMemory();
throw new OddException(temporary);
}
</code></pre>
<p>My questions are:</p>
<ol>
<li><p>As this "<code>BigObject</code>" is freed when the exception object is released, do we need this pattern?</p></li>
<li><p>Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there?</p></li>
</ol>
<p>Thanks!</p>
|
[
{
"answer_id": 148920,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": false,
"text": "using(var resource = AllocateLotsOfMemory())\n{\n if(something_bad_happened) \n {\n throw new SomeThingBadException();\n }\n}\n"
},
{
"answer_id": 149023,
"author": "user7375",
"author_id": 7375,
"author_profile": "https://Stackoverflow.com/users/7375",
"pm_score": 3,
"selected": true,
"text": "public class DomainEventStorage<ActionType>\n{\n public List<ActionType> Actions\n {\n get\n {\n var k = string.Format(\"Domain.Event.DomainEvent.{0}.{1}\",\n GetType().Name,\n GetType().GetGenericArguments()[0]);\n if (Local.Data[k] == null)\n Local.Data[k] = new List<ActionType>();\n\n return (List<ActionType>) Local.Data[k];\n }\n }\n\n public IDisposable Register(ActionType callback)\n {\n Actions.Add(callback);\n return new DomainEventRegistrationRemover(() => Actions.Remove(callback)\n );\n }\n}\n\npublic class DomainEvent<T1> : IDomainEvent where T1 : class\n{\n private readonly DomainEventStorage<Action<T1>> _impl = new DomainEventStorage<Action<T1>>();\n\n internal List<Action<T1>> Actions { get { return _impl.Actions; } }\n\n public IDisposable Register(Action<T1> callback)\n {\n return _impl.Register(callback);\n }\n\n public void Raise(T1 args)\n {\n foreach (var action in Actions)\n {\n action.Invoke(args);\n }\n }\n}\n var fail = false;\nusing(var ev = DomainErrors.SomethingHappened.Register(c => fail = true) \n{\n //Do something with your domain here\n}\n"
},
{
"answer_id": 1747288,
"author": "Dan Berindei",
"author_id": 55870,
"author_profile": "https://Stackoverflow.com/users/55870",
"pm_score": 1,
"selected": false,
"text": "resource = AllocateLotsOfMemory();\nif (SomeCondition())\n{\n try\n {\n OnOddError(new OddErrorEventArgs(resource.StatusProperty));\n return;\n }\n finally\n {\n resource.FreeLotsOfMemory();\n }\n}\n resource.FreeLotsOfMemory() resource.StatusProperty null"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3546/"
] |
148,901
|
<p>I've always handled optional parameters in JavaScript like this:</p>
<pre><code>function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
</code></pre>
<p>Is there a better way to do it?</p>
<p>Are there any cases where using <code>||</code> like that is going to fail?</p>
|
[
{
"answer_id": 148918,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 11,
"selected": true,
"text": "if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }\n optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;\n"
},
{
"answer_id": 148933,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 4,
"selected": false,
"text": "function myFunc(requiredArg, optionalArg){\n optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg;\n\n ...\n"
},
{
"answer_id": 148941,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 6,
"selected": false,
"text": "NULL function myFunction (argArray) {\n var defaults = {\n 'arg1' : \"value 1\",\n 'arg2' : \"value 2\",\n 'arg3' : \"value 3\",\n 'arg4' : \"value 4\"\n }\n\n for(var i in defaults) \n if(typeof argArray[i] == \"undefined\") \n argArray[i] = defaults[i];\n\n // ...\n}\n"
},
{
"answer_id": 151158,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "/**\n * Updates an object's properties with other objects' properties. All\n * additional non-falsy arguments will have their properties copied to the\n * destination object, in the order given.\n */\nfunction extend(dest) {\n for (var i = 1, l = arguments.length; i < l; i++) {\n var src = arguments[i]\n if (!src) {\n continue\n }\n for (var property in src) {\n if (src.hasOwnProperty(property)) {\n dest[property] = src[property]\n }\n }\n }\n return dest\n}\n\n/**\n * Inherit another function's prototype without invoking the function.\n */\nfunction inherits(child, parent) {\n var F = function() {}\n F.prototype = parent.prototype\n child.prototype = new F()\n child.prototype.constructor = child\n return child\n}\n function Field(kwargs) {\n kwargs = extend({\n required: true, widget: null, label: null, initial: null,\n helpText: null, errorMessages: null\n }, kwargs)\n this.required = kwargs.required\n this.label = kwargs.label\n this.initial = kwargs.initial\n // ...and so on...\n}\n\nfunction CharField(kwargs) {\n kwargs = extend({\n maxLength: null, minLength: null\n }, kwargs)\n this.maxLength = kwargs.maxLength\n this.minLength = kwargs.minLength\n Field.call(this, kwargs)\n}\ninherits(CharField, Field)\n undefined CharField Field"
},
{
"answer_id": 8128312,
"author": "trusktr",
"author_id": 454780,
"author_profile": "https://Stackoverflow.com/users/454780",
"pm_score": 7,
"selected": false,
"text": "if (typeof myVariable === 'undefined') { myVariable = 'default'; }\n//use myVariable here\n"
},
{
"answer_id": 9363769,
"author": "user56reinstatemonica8",
"author_id": 568458,
"author_profile": "https://Stackoverflow.com/users/568458",
"pm_score": 5,
"selected": false,
"text": "undefined undefined undefined function myFunc( requiredA, requiredB, optionalA, optionalB, optionalC ) {\n\n switch (arguments.length - 2) { // 2 is the number of required arguments\n case 0: optionalA = 'Some default';\n case 1: optionalB = 'Another default';\n case 2: optionalC = 'Some other default';\n // no breaks between cases: each case implies the next cases are also needed\n }\n\n}\n arguments Function.arguments optionalC optionalB _.defaults(object, defaults) function myFunc( args ) {\n var defaults = {\n optionalA: 'Some default',\n optionalB: 'Another default',\n optionalC: 'Some other default'\n };\n args = $.extend({}, defaults, args);\n}\n"
},
{
"answer_id": 10609053,
"author": "Vitim.us",
"author_id": 938822,
"author_profile": "https://Stackoverflow.com/users/938822",
"pm_score": 3,
"selected": false,
"text": "function usageExemple(a,b,c,d){\n //defaults\n a=defaultValue(a,1);\n b=defaultValue(b,2);\n c=defaultValue(c,4);\n d=defaultValue(d,8);\n\n var x = a+b+c+d;\n return x;\n}\n function defaultValue(variable,defaultValue){\n return(typeof variable!=='undefined')?(variable):(defaultValue);\n}\n fruit = defaultValue(fruit,'Apple'); defaultValue default"
},
{
"answer_id": 14958435,
"author": "Lachlan Hunt",
"author_id": 132537,
"author_profile": "https://Stackoverflow.com/users/132537",
"pm_score": 8,
"selected": false,
"text": "function myFunc(requiredArg, optionalArg = 'defaultValue') {\n // do stuff\n}\n"
},
{
"answer_id": 14993387,
"author": "Brian McCutchon",
"author_id": 2093695,
"author_profile": "https://Stackoverflow.com/users/2093695",
"pm_score": 0,
"selected": false,
"text": "function myFunction(Required,Optional)\n{\n if (arguments.length<2) Optional = \"Default\";\n //Your code\n}\n"
},
{
"answer_id": 15975465,
"author": "zVictor",
"author_id": 599991,
"author_profile": "https://Stackoverflow.com/users/599991",
"pm_score": -1,
"selected": false,
"text": "function myFunc(){\n arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})\n\n //do stuff, using arguments.requiredArg and arguments.optionalArg\n // to access your arguments\n\n}\n undefined function myFunc(){\n arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})\n\n //do stuff, using arguments.requiredArg and arguments.optionalArg\n // to access your arguments\n\n}\n"
},
{
"answer_id": 16420369,
"author": "Arman",
"author_id": 1847185,
"author_profile": "https://Stackoverflow.com/users/1847185",
"pm_score": 2,
"selected": false,
"text": "null var a1; function overLoad(p1){\n alert(p1 == null); // Caution, don't use the strict comparison: === won't work.\n alert(typeof p1 === 'undefined');\n}\n\noverLoad(); // true, true\noverLoad(undefined); // true, true. Yes, undefined is treated as null for equality operator.\noverLoad(10); // false, false\n\n\nfunction overLoad(p1){\n if (p1 == null) p1 = 'default value goes here...';\n //...\n}\n typeof variable === 'undefined' in arguments function foo(a, b) {\n // Both a and b will evaluate to undefined when used in an expression\n alert(a); // undefined\n alert(b); // undefined\n\n alert(\"0\" in arguments); // true\n alert(\"1\" in arguments); // false\n}\n\nfoo (undefined);\n"
},
{
"answer_id": 19043188,
"author": "slartibartfast",
"author_id": 1203126,
"author_profile": "https://Stackoverflow.com/users/1203126",
"pm_score": 2,
"selected": false,
"text": "function PaulDixonSolution(required, optionalArg){\n optionalArg = (typeof optionalArg === \"undefined\") ? \"defaultValue\" : optionalArg;\n console.log(optionalArg);\n};\nPaulDixonSolution(\"required\");\nPaulDixonSolution(\"required\", \"provided\");\nPaulDixonSolution(\"required\", null);\nPaulDixonSolution(\"required\", false);\n defaultValue\nprovided\nnull\nfalse\n function bulletproof(required, optionalArg){\n optionalArg = optionalArg ? optionalArg : \"defaultValue\";;\n console.log(optionalArg);\n};\nbulletproof(\"required\");\nbulletproof(\"required\", \"provided\");\nbulletproof(\"required\", null);\nbulletproof(\"required\", false);\n defaultValue\nprovided\ndefaultValue\ndefaultValue\n"
},
{
"answer_id": 19843391,
"author": "Mmmh mmh",
"author_id": 1582182,
"author_profile": "https://Stackoverflow.com/users/1582182",
"pm_score": 0,
"selected": false,
"text": "function foo(a, b) {\n a !== undefined || (a = 'defaultA');\n if(b === undefined) b = 'defaultB';\n ...\n}\n"
},
{
"answer_id": 20293344,
"author": "NinjaFart",
"author_id": 1772200,
"author_profile": "https://Stackoverflow.com/users/1772200",
"pm_score": 1,
"selected": false,
"text": "function WhoLikesCake(options) {\n options = options || {};\n var defaultOptions = {\n a : options.a || \"Huh?\",\n b : options.b || \"I don't like cake.\"\n }\n console.log('a: ' + defaultOptions.b + ' - b: ' + defaultOptions.b);\n\n // Do more stuff here ...\n}\n WhoLikesCake({ b : \"I do\" });\n"
},
{
"answer_id": 22370734,
"author": "Matt Montag",
"author_id": 264970,
"author_profile": "https://Stackoverflow.com/users/264970",
"pm_score": 3,
"selected": false,
"text": "function foo(a, b, c) {\n a = a || \"default\"; // Matches 0, \"\", null, undefined, NaN, false.\n a || (a = \"default\"); // Matches 0, \"\", null, undefined, NaN, false.\n\n if (b == null) { b = \"default\"; } // Matches null, undefined.\n\n if (typeof c === \"undefined\") { c = \"default\"; } // Matches undefined.\n}\n a"
},
{
"answer_id": 22951497,
"author": "Dustin Poissant",
"author_id": 2082141,
"author_profile": "https://Stackoverflow.com/users/2082141",
"pm_score": -1,
"selected": false,
"text": "function foo(requiredArg){\n if(arguments.length>1) var optionalArg = arguments[1];\n}\n"
},
{
"answer_id": 23048325,
"author": "Mark Funk",
"author_id": 3529909,
"author_profile": "https://Stackoverflow.com/users/3529909",
"pm_score": 1,
"selected": false,
"text": "function person(firstname, lastname, age, eyecolor)\n{\nthis.firstname = firstname;\nthis.lastname = lastname;\nthis.age = age;\nthis.eyecolor = eyecolor;\n// if(null==eyecolor)\n// this.eyecolor = \"unknown1\";\n//if(typeof(eyecolor)==='undefined') \n// this.eyecolor = \"unknown2\";\n// if(!eyecolor)\n// this.eyecolor = \"unknown3\";\nthis.eyecolor = this.eyecolor || \"unknown4\";\n}\n\nvar myFather = new person(\"John\", \"Doe\", 60);\nvar myMother = new person(\"Sally\", \"Rally\", 48, \"green\");\n\nvar elem = document.getElementById(\"demo\");\nelem.innerHTML = \"My father \" +\n myFather.firstname + \" \" +\n myFather.lastname + \" is \" +\n myFather.age + \" with \" +\n myFather.eyecolor + \" eyes.<br/>\" +\n \"My mother \" +\n myMother.firstname + \" \" +\n myMother.lastname + \" is \" +\n myMother.age + \" with \" +\n myMother.eyecolor + \" eyes.\"; \n"
},
{
"answer_id": 24305438,
"author": "JDC",
"author_id": 256532,
"author_profile": "https://Stackoverflow.com/users/256532",
"pm_score": 2,
"selected": false,
"text": "Function executed Operations/sec Statistics\nTypeofFunction('test'); 92,169,505 ±1.55% 9% slower\nSwitchFuntion('test'); 2,904,685 ±2.91% 97% slower\nObjectFunction({param1: 'test'}); 924,753 ±1.71% 99% slower\nLogicalOrFunction('test'); 101,205,173 ±0.92% fastest\nTypeofFunction2('test'); 35,636,836 ±0.59% 65% slower\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"></script>\n<script>\n Benchmark.prototype.setup = function() {\n function TypeofFunction(param1, optParam1, optParam2, optParam3) {\n optParam1 = (typeof optParam1 === \"undefined\") ? \"Some default\" : optParam1;\n optParam2 = (typeof optParam2 === \"undefined\") ? \"Another default\" : optParam2;\n optParam3 = (typeof optParam3 === \"undefined\") ? \"Some other default\" : optParam3;\n }\n\n function TypeofFunction2(param1, optParam1, optParam2, optParam3) {\n optParam1 = defaultValue(optParam1, \"Some default\");\n optParam2 = defaultValue(optParam2, \"Another default\");\n optParam3 = defaultValue(optParam3, \"Some other default\");\n }\n\n function defaultValue(variable, defaultValue) {\n return (typeof variable !== 'undefined') ? (variable) : (defaultValue);\n }\n\n function SwitchFuntion(param1, optParam1, optParam2, optParam3) {\n switch (arguments.length - 1) { // <-- 1 is number of required arguments\n case 0:\n optParam1 = 'Some default';\n case 1:\n optParam2 = 'Another default';\n case 2:\n optParam3 = 'Some other default';\n }\n }\n\n function ObjectFunction(args) {\n var defaults = {\n optParam1: 'Some default',\n optParam2: 'Another default',\n optParam3: 'Some other default'\n }\n args = $.extend({}, defaults, args);\n }\n\n function LogicalOrFunction(param1, optParam1, optParam2, optParam3) {\n optParam1 || (optParam1 = 'Some default');\n optParam2 || (optParam1 = 'Another default');\n optParam3 || (optParam1 = 'Some other default');\n }\n };\n</script>\n"
},
{
"answer_id": 25984851,
"author": "actual_kangaroo",
"author_id": 2377920,
"author_profile": "https://Stackoverflow.com/users/2377920",
"pm_score": 2,
"selected": false,
"text": "_.defaults(optionalArg, 'defaultValue');\n"
},
{
"answer_id": 26176506,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "function Default(variable, new_value)\n{\n if(new_value === undefined) { return (variable === undefined) ? null : variable; }\n return (variable === undefined) ? new_value : variable;\n}\n\nvar a = 2, b = \"hello\", c = true, d;\n\nvar test = Default(a, 0),\ntest2 = Default(b, \"Hi\"),\ntest3 = Default(c, false),\ntest4 = Default(d, \"Hello world\");\n\nwindow.alert(test + \"\\n\" + test2 + \"\\n\" + test3 + \"\\n\" + test4);\n"
},
{
"answer_id": 30261130,
"author": "Petr Hurtak",
"author_id": 2955574,
"author_profile": "https://Stackoverflow.com/users/2955574",
"pm_score": 3,
"selected": false,
"text": "0 '' false null undefined function myFunc(requiredArg, optionalArg) {\n optionalArg = optionalArg || 'defaultValue';\n}\n undefined function myFunc(requiredArg, optionalArg) {\n optionalArg = typeof optionalArg !== 'undefined' ? optionalArg : 'defaultValue';\n}\n function myFunc(requiredArg, optionalArg1, optionalArg2) {\n optionalArg1 = arguments.length > 1 ? optionalArg1 : 'defaultValue';\n optionalArg2 = arguments.length > 2 ? optionalArg2 : 'defaultValue';\n}\n function myFunc(requiredArg, optionalArg = 'defaultValue') {\n\n}\n"
},
{
"answer_id": 33040641,
"author": "Kulbhushan Singh",
"author_id": 1178918,
"author_profile": "https://Stackoverflow.com/users/1178918",
"pm_score": 2,
"selected": false,
"text": "function doSomething(optionalParam = \"defaultValue\"){\n console.log(optionalParam);//not required to check for falsy values\n}\n\ndoSomething(); //\"defaultValue\"\ndoSomething(\"myvalue\"); //\"myvalue\"\n"
},
{
"answer_id": 35129017,
"author": "Yann Bertrand",
"author_id": 3215167,
"author_profile": "https://Stackoverflow.com/users/3215167",
"pm_score": 3,
"selected": false,
"text": "Object.assign $.extend() _.defaults() function myFunc(requiredArg, options = {}) {\n const defaults = {\n message: 'Hello',\n color: 'red',\n importance: 1\n };\n\n const settings = Object.assign({}, defaults, options);\n\n // do stuff\n}\n function myFunc(requiredArg, { message: 'Hello', color: 'red', importance: 1 } = {}) {\n // do stuff\n}\n"
},
{
"answer_id": 36176166,
"author": "Bart Wttewaall",
"author_id": 6103561,
"author_profile": "https://Stackoverflow.com/users/6103561",
"pm_score": 2,
"selected": false,
"text": "var myCar = new Car('VW', {gearbox:'automatic', options:['radio', 'airbags 2x']});\nvar myOtherCar = new Car('Toyota');\n\nfunction Car(brand, settings) {\n this.brand = brand;\n\n // readable and adjustable code\n settings = DefaultValue.object(settings, {});\n this.wheels = DefaultValue.number(settings.wheels, 4);\n this.hasBreaks = DefaultValue.bool(settings.hasBreaks, true);\n this.gearbox = DefaultValue.string(settings.gearbox, 'manual');\n this.options = DefaultValue.array(settings.options, []);\n\n // instead of doing this the hard way\n settings = settings || {};\n this.wheels = (!isNaN(settings.wheels)) ? settings.wheels : 4;\n this.hasBreaks = (typeof settings.hasBreaks !== 'undefined') ? (settings.hasBreaks === true) : true;\n this.gearbox = (typeof settings.gearbox === 'string') ? settings.gearbox : 'manual';\n this.options = (typeof settings.options !== 'undefined' && Array.isArray(settings.options)) ? settings.options : [];\n}\n (function(ns) {\n\n var DefaultValue = {\n\n object: function(input, defaultValue) {\n if (typeof defaultValue !== 'object') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? input : defaultValue;\n },\n\n bool: function(input, defaultValue) {\n if (typeof defaultValue !== 'boolean') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? (input === true) : defaultValue;\n },\n\n number: function(input, defaultValue) {\n if (isNaN(defaultValue)) throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined' && !isNaN(input)) ? parseFloat(input) : defaultValue;\n },\n\n // wrap the input in an array if it is not undefined and not an array, for your convenience\n array: function(input, defaultValue) {\n if (typeof defaultValue === 'undefined') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? (Array.isArray(input) ? input : [input]) : defaultValue;\n },\n\n string: function(input, defaultValue) {\n if (typeof defaultValue !== 'string') throw new Error('invalid defaultValue type');\n return (typeof input === 'string') ? input : defaultValue;\n },\n\n };\n\n ns.DefaultValue = DefaultValue;\n\n}(this));\n"
},
{
"answer_id": 36550696,
"author": "Duco L",
"author_id": 2886150,
"author_profile": "https://Stackoverflow.com/users/2886150",
"pm_score": 1,
"selected": false,
"text": "function YourFunction(optionalArguments) {\n //var scope = this;\n\n //set the defaults\n var _value1 = 'defaultValue1';\n var _value2 = 'defaultValue2';\n var _value3 = null;\n var _value4 = false;\n\n //check the optional arguments if they are set to override defaults...\n if (typeof optionalArguments !== 'undefined') {\n\n if (typeof optionalArguments.param1 !== 'undefined')\n _value1 = optionalArguments.param1;\n\n if (typeof optionalArguments.param2 !== 'undefined')\n _value2 = optionalArguments.param2;\n\n if (typeof optionalArguments.param3 !== 'undefined')\n _value3 = optionalArguments.param3;\n\n if (typeof optionalArguments.param4 !== 'undefined')\n //use custom parameter validation if needed, in this case for javascript boolean\n _value4 = (optionalArguments.param4 === true || optionalArguments.param4 === 'true');\n }\n\n console.log('value summary of function call:');\n console.log('value1: ' + _value1);\n console.log('value2: ' + _value2);\n console.log('value3: ' + _value3);\n console.log('value4: ' + _value4);\n console.log('');\n }\n\n\n //call your function in any way you want. You can leave parameters. Order is not important. Here some examples:\n YourFunction({\n param1: 'yourGivenValue1',\n param2: 'yourGivenValue2',\n param3: 'yourGivenValue3',\n param4: true,\n });\n\n //order is not important\n YourFunction({\n param4: false,\n param1: 'yourGivenValue1',\n param2: 'yourGivenValue2',\n });\n\n //uses all default values\n YourFunction();\n\n //keeps value4 false, because not a valid value is given\n YourFunction({\n param4: 'not a valid bool'\n });\n"
},
{
"answer_id": 36959351,
"author": "mcfedr",
"author_id": 859027,
"author_profile": "https://Stackoverflow.com/users/859027",
"pm_score": 1,
"selected": false,
"text": "arg || 'default' false 0 NaN \"\" undefined"
},
{
"answer_id": 39284226,
"author": "Pavan Varanasi",
"author_id": 2590817,
"author_profile": "https://Stackoverflow.com/users/2590817",
"pm_score": 1,
"selected": false,
"text": "function myFunc(requiredArg, optionalArg) {\n optionalArg = optionalArg || 'defaultValue';\n console.log(optionalArg);\n // Do stuff\n}\nmyFunc(requiredArg);\nmyFunc(requiredArg, null);\nmyFunc(requiredArg, undefined);\nmyFunc(requiredArg, \"\");\nmyFunc(requiredArg, 0);\nmyFunc(requiredArg, false);\n"
},
{
"answer_id": 40315838,
"author": "Bekim Bacaj",
"author_id": 5896426,
"author_profile": "https://Stackoverflow.com/users/5896426",
"pm_score": -1,
"selected": false,
"text": " function myFunc(requiredArg, optionalArg){\n optionalArg = 1 in arguments ? optionalArg : 'defaultValue';\n //do stuff\n }\n function argCheck( arg1, arg2, arg3 ){\n\n arg1 = 0 in arguments || undefined;\n arg2 = 1 in arguments || false;\n arg3 = 2 in arguments || 0;\n var arg4 = 3 in arguments || null;\n\n console.log( arg1, arg2, arg3, arg4 ) \n}\n argCheck( \"\", 0, false, null );\n>> true true true true\n argCheck( );\n>> undefined false 0 null\n argCheck(\"a\",,22,{});\n function argCheck( ) {\n var _default = [undefined, 0, false, null ],\n _arg = arguments;\n\n for( var x in _default ) {\n x in _arg ? 1 : _arg[x] = _default[x];\n }\n console.log( _arg[0],_arg[1],_arg[2],_arg[3] );\n}\n argCheck();\n>>undefined 0 false null\n argCheck({})\n>>Object { } 0 false null\n\nargCheck({}, [])\n>>Object { } Array [ ] false null\n argCheck(\"a\",,,22);\n >>SyntaxError: expected expression, got ','\n >>a 0 false 22\n function argCheck( arg, opt ) {\n 1 in arguments ? 1 : opt = \"default\";\n console.log( arg, opt );\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
148,902
|
<p>I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later?</p>
<p>Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?</p>
|
[
{
"answer_id": 149396,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 0,
"selected": false,
"text": "svn copy trunk branch # create your branch while preserving history\nsvn copy trunk@100 trunk #replace current revision with revision 100 \n svn switch branch workdir\n"
},
{
"answer_id": 150098,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 5,
"selected": true,
"text": "svn copy -r100 svn://repos/trunk svn://repos/branches/newbranch\nsvn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch\n svn merge -r130:100 .\nsvn ci -m 'reverting to r100 (undoing changes in r100-130)' . \n svn switch svn://repos/branches/newbranch workdir\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
148,908
|
<p>I am thinking about using Microsoft Unity for my Dependency Injection tool in our User Interface.</p>
<p>Our Middle Tier already uses Castle Windsor, but I am thinking I should stick with Microsoft.</p>
<p>Does anyone have any thoughts about what the best Dependency Injection tool is? </p>
<ul>
<li><a href="http://www.autofac.org/" rel="noreferrer">Autofac</a></li>
<li><a href="http://www.castleproject.org/index.html" rel="noreferrer">Castle MicroKernel/Windsor</a></li>
<li><a href="http://picocontainer.org/" rel="noreferrer">PicoContainer.NET</a></li>
<li>Puzzle.NFactory</li>
<li><a href="http://www.springframework.net/" rel="noreferrer">Spring.NET</a></li>
<li><a href="http://structuremap.net/structuremap/" rel="noreferrer">StructureMap</a></li>
<li><a href="http://ninject.org/" rel="noreferrer">Ninject</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd203101.aspx" rel="noreferrer">Unity</a></li>
<li><a href="http://simpleinjector.codeplex.com" rel="noreferrer">Simple Injector</a></li>
<li><a href="https://www.ohloh.net/p/5670" rel="noreferrer">NauckIT.MicroKernel</a></li>
<li><a href="http://www.winter4.net/" rel="noreferrer">WINTER4NET</a></li>
<li><a href="http://objectbuilder.codeplex.com/" rel="noreferrer">ObjectBuilder</a></li>
</ul>
|
[
{
"answer_id": 346403,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 6,
"selected": false,
"text": "ILogger -> typeof(FileLogger) ILogger -> new FileLogger() IDisposable BasePage IDisposable BasePage"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
148,945
|
<p>We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel.</p>
<p>What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.</p>
|
[
{
"answer_id": 148962,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 4,
"selected": true,
"text": "//for demo purpose, lets create a small datatable & populate it with dummy data\nSystem.Data.DataTable workTable = new System.Data.DataTable();\n\n//The tablename specified here will be set as the worksheet name of the generated Excel file. \nworkTable.TableName = \"Customers\";\nworkTable.Columns.Add(\"Id\");\nworkTable.Columns.Add(\"Name\");\nSystem.Data.DataRow workRow;\n\nfor (int i = 0; i <= 9; i++)\n{\nworkRow = workTable.NewRow();\nworkRow[0] = i;\nworkRow[1] = \"CustName\" + i.ToString();\nworkTable.Rows.Add(workRow);\n}\n\n//...and lets put DataTable2ExcelString to work\nstring strBody = DataTable2ExcelString(workTable);\n\nResponse.AppendHeader(\"Content-Type\", \"application/vnd.ms-excel\");\nResponse.AppendHeader(\"Content-disposition\", \"attachment; filename=my.xls\");\nResponse.Write(strBody);\n"
},
{
"answer_id": 149019,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 1,
"selected": false,
"text": "Response.ContentType = \"application/vnd.ms-excel\";\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=somefilename.xls\");\n"
},
{
"answer_id": 149079,
"author": "Alexandre Brisebois",
"author_id": 18619,
"author_profile": "https://Stackoverflow.com/users/18619",
"pm_score": 0,
"selected": false,
"text": " //write the column headers\n for (int cIndex = 1; cIndex < 1 + columns; cIndex++)\n sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);\n if (rows > 0)\n {\n\n //select the range where the data will be pasted\n Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);\n\n //Convert the datatable to an object array\n object[,] workingValues = new object[rows, columns];\n\n for (int rIndex = 0; rIndex < rows; rIndex++)\n for (int cIndex = 0; cIndex < columns; cIndex++)\n workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();\n\n r.Value2 = workingValues;\n }\n"
},
{
"answer_id": 150387,
"author": "SpoiledTechie.com",
"author_id": 7644,
"author_profile": "https://Stackoverflow.com/users/7644",
"pm_score": 1,
"selected": false,
"text": " public static void DataTabletoXLS(DataTable DT, string fileName)\n {\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.Charset = \"utf-16\";\n HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(\"windows-1250\");\n HttpContext.Current.Response.AddHeader(\"content-disposition\", string.Format(\"attachment; filename={0}.xls\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n string tab = \"\";\n foreach (DataColumn dc in DT.Columns)\n {\n HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n\n int i;\n foreach (DataRow dr in DT.Rows)\n {\n tab = \"\";\n for (i = 0; i < DT.Columns.Count; i++)\n {\n HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n }\n HttpContext.Current.Response.End();\n }\n"
},
{
"answer_id": 1057481,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " grdSrcRequestExport.RenderControl(oHtmlTextWriter);\n string s = \"\";\n s=oStringWriter.ToString().Replace(\"<table cellspacing=\\\"0\\\" rules=\\\"all\\\" border=\\\"1\\\" style=\\\"border-collapse:collapse;\\\">\", \"\");\n s=\"<html xmlns:o=\\\"urn:schemas-microsoft-com:office:office\\\" xmlns:x=\\\"urn:schemas-microsoft-com:office:excel\\\" xmlns=\\\"http://www.w3.org/TR/REC-html40\\\"><head><meta http-equiv=Content-Type content=\\\"text/html; charset=us-ascii\\\"><meta name=ProgId content=Excel.Sheet><meta name=Generator content=\\\"Microsoft Excel 11\\\"><table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'>\"+s.ToString()+\"</table></body></html>\";\n //Byte[] bContent = System.Text.Encoding.GetEncoding(\"utf-8\").GetBytes();\n Response.Write(s);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
148,951
|
<p>I'm trying to use <code>mysqldump</code> to dump a schema, and it mostly works but I ran into one curiosity: the <code>-p</code> or <code>--password</code> option seems like it is doing something other than setting the password (as the <code>man</code> page and <code>--help</code> output say it should).</p>
<p>Specifically, it looks like it's doing what is indicated here: <a href="http://snippets.dzone.com/posts/show/360" rel="noreferrer">http://snippets.dzone.com/posts/show/360</a> - that is, setting the database to dump.</p>
<p>To support my somewhat outlandish claim, I can tell you that if I do not specify the <code>--password</code> (or <code>-p</code>) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the <code>--password</code> option is dumped (or an error is given in the usual case that a password not matching any database name was specified).</p>
<p>Here's a transcript:</p>
<pre>
$ mysqldump -u test -h myhost --no-data --tables --password lose
Enter password:
-- MySQL dump 10.10
mysqldump: Got error: 1044: Access denied for user 'test'@'%' to
database 'lose' when selecting the database
</pre>
<p>So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using <code>expect</code>???</p>
<p>I'm using <code>mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486)</code>.</p>
|
[
{
"answer_id": 148984,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 7,
"selected": true,
"text": "mysqldump lose --password=lose -plose -p --password"
},
{
"answer_id": 148989,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 2,
"selected": false,
"text": "--password=lose\n"
},
{
"answer_id": 149009,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "[client]\npassword=lose\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
] |
148,963
|
<p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks" rel="noreferrer">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
|
[
{
"answer_id": 378778,
"author": "uhz",
"author_id": 1369629,
"author_profile": "https://Stackoverflow.com/users/1369629",
"pm_score": 2,
"selected": false,
"text": "delayedresult"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
148,968
|
<p>As I understand it, <code>.bat</code> is the old 16-bit naming convention, and <code>.cmd</code> is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some <strong>gotcha</strong> awaiting me by using the wrong suffix?</p>
|
[
{
"answer_id": 149007,
"author": "Waldo",
"author_id": 21687,
"author_profile": "https://Stackoverflow.com/users/21687",
"pm_score": -1,
"selected": false,
"text": "COMMAND.COM CMD.EXE"
},
{
"answer_id": 149810,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": false,
"text": "%SystemRoot%system32\\cmd.exe .BAT .CMD"
},
{
"answer_id": 149918,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 9,
"selected": false,
"text": "command.com cmd.exe cmd.exe cmd start cmd cmd ComSpec .bat .cmd cmd.exe cmd.exe command.com cmd.exe .cmd cmd.exe command.com ^ \\ & | > < ^ PUSHD POPD SET /A i+=1 SET %varname:expression% FOR /F CALL :label"
},
{
"answer_id": 12011048,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 7,
"selected": false,
"text": ".cmd .cmd .cmd .bat .cmd .cmd"
},
{
"answer_id": 27080075,
"author": "tvCa",
"author_id": 4282156,
"author_profile": "https://Stackoverflow.com/users/4282156",
"pm_score": 4,
"selected": false,
"text": "C:\\>echo %PATHEXT%\n.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\n\nC:\\Temp>echo echo bat > test.bat\n\nC:\\Temp>echo echo cmd > test.cmd\n\nC:\\Temp>test\n\nC:\\Temp>echo bat\nbat\n\nC:\\Temp>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
148,977
|
<p>What is the keyboard-shortcut that expands the menu, from the little red line, and offers the option to have the necessary <code>using</code> statement appended to the top of the file?</p>
|
[
{
"answer_id": 58354338,
"author": "Slobodan Stanković",
"author_id": 4426286,
"author_profile": "https://Stackoverflow.com/users/4426286",
"pm_score": 0,
"selected": false,
"text": "List <"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3268/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.