qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
127,001
|
<p>I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.</p>
|
[
{
"answer_id": 127011,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 5,
"selected": true,
"text": ".addRequestHeader(\"Accept-Encoding\",\"gzip,deflate\");\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] |
127,006
|
<p>Could anyone recommend to me a good online guide to PowerPoint VBA? Also, does anyone has advice on how to record a macro in PowerPoint? </p>
|
[
{
"answer_id": 7265123,
"author": "Bruno Leite",
"author_id": 858857,
"author_profile": "https://Stackoverflow.com/users/858857",
"pm_score": 2,
"selected": false,
"text": "dim ppt as powerpoint.Presentation\n\nset ppt =activepresentation\n Private WithEvents ppt As PowerPoint.Application\n set x= new class1\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
127,009
|
<p>Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way.</p>
<p>The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator...</p>
<p>I tried this:</p>
<pre><code>class Arc;
typedef std::iterator<std::random_access_iterator_tag, Arc*> ArcIterator; // Wrong!
class Node {
public:
ArcIterator incomingArcsBegin() const {
return _incomingArcs.begin();
}
private:
std::vector<Arc*> _incomingArcs;
};
</code></pre>
<p>But this is not correct because a vector::const_iterator can't be used to create an ArcIterator. So what can be this ArcIterator?</p>
<p>I found this paper about <a href="http://www.oonumerics.org/tmpw00/becker.html" rel="nofollow noreferrer">Custom Iterators for the STL</a> but it did not help. I must be a bit heavy today... ;)</p>
|
[
{
"answer_id": 127231,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": 3,
"selected": false,
"text": "class Arc;\nclass Node {\nprivate:\n std::vector<Arc*> incoming_;\npublic:\n typedef std::vector<Arc*>::iterator iterator;\n iterator incoming_arcs_begin()\n { return incoming_.begin(); }\n};\n"
},
{
"answer_id": 127282,
"author": "TonJ",
"author_id": 11537,
"author_profile": "https://Stackoverflow.com/users/11537",
"pm_score": 0,
"selected": false,
"text": "vector<Arc*>::const_iterator\n allocator<Arc*>::const_pointer\n typedef allocator<Arc*>::const_pointer ArcIterator;\n"
},
{
"answer_id": 127348,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "std::vector<Arc*>::iterator std::vector<Arc*>::iterator std::iterator std::iterator iterator_category value_type boost::indirect_iterator Arc Arc*"
},
{
"answer_id": 127446,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 0,
"selected": false,
"text": "class Arc {};\n\ntemplate<\n template<class T, class U> class Container = std::vector,\n class Allocator = std::allocator<Arc*>\n>\nclass Node\n{\n public:\n typedef typename Container<Arc*, Allocator>::iterator ArcIterator;\n typedef typename Container<Arc*, Allocator>::Const_iterator constArcIterator;\n\n constArcIterator incomingArcsBegin() const {\n return _incomingArcs.begin();\n }\n\n ArcIterator incomingArcsBegin() {\n return _incomingArcs.begin();\n }\n private:\n Container<Arc*, Allocator> _incomingArcs;\n};\n"
},
{
"answer_id": 127604,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "for (vector::const_iterator itr = myvec.begin(); itr != myvec.end(); ++itr for (auto itr = myvec.begin(); itr != myvec.end(); ++itr) auto begin() next()"
},
{
"answer_id": 128320,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "any_iterator any_iterator"
},
{
"answer_id": 135202,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "std::vector class Arc;\ntypedef Arc* ArcIterator;\n\nclass Node {\npublic:\n ArcIterator incomingArcsBegin() const {\n return &_incomingArcs[0]\n }\n\n ArcIterator incomingArcsEnd() const {\n return &_incomingArcs[_incomingArcs.size()]\n }\nprivate:\n std::vector<Arc*> _incomingArcs;\n};\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4177/"
] |
127,027
|
<p>I use a byte to store some flag like <code>10101010</code>, and I would like to know how to verify that a specific bit is at <code>1</code> or <code>0</code>.</p>
|
[
{
"answer_id": 127049,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 1,
"selected": false,
"text": "byte THIRDBIT = 4; // 4 = 00000100 i.e third bit is set\n\nint isThirdBitSet(byte in) {\n return in & THIRDBIT; // Returns 1 if the third bit is set, 0 otherwise\n}\n"
},
{
"answer_id": 127062,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 7,
"selected": true,
"text": "bit bool is_bit_set(unsigned value, unsigned bitindex)\n{\n return (value & (1 << bitindex)) != 0;\n}\n << (1 << 0) 00000001 (1 << 1) 00000010 (1 << 3) 00001000 0 31 & 1 1111 & 0001 0001 1111 & 0010 0010 0000 & 0001 0000 (value & (1 << bitindex))\n bitindex 1 0 1 bitindex zero Result > 0 true 1 bitindex false 0 bitindex != 0"
},
{
"answer_id": 127068,
"author": "mdec",
"author_id": 15534,
"author_profile": "https://Stackoverflow.com/users/15534",
"pm_score": 3,
"selected": false,
"text": "& unsigned char a = 0xAA; // 10101010 in hex\nunsigned char b = (1 << bitpos); // Where bitpos is the position you want to check\n\nif(a & b) {\n //bit set\n}\n\nelse {\n //not set\n}\n"
},
{
"answer_id": 127069,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 0,
"selected": false,
"text": "if (var & 0x08) {\n /* The fourth bit is set */\n}\n"
},
{
"answer_id": 127075,
"author": "Zach Lute",
"author_id": 21374,
"author_profile": "https://Stackoverflow.com/users/21374",
"pm_score": 1,
"selected": false,
"text": "int MY_FLAG = 0x0001;\nif ((value & MY_FLAG) == MY_FLAG)\n doSomething();\n"
},
{
"answer_id": 127079,
"author": "Evan Shaw",
"author_id": 510,
"author_profile": "https://Stackoverflow.com/users/510",
"pm_score": 2,
"selected": false,
"text": "int checkBit( byte in, int bit )\n{\n return in & ( 1 << bit );\n}\n"
},
{
"answer_id": 127506,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "#include <bitset>\n//...\nstd::bitset<8> flags(someVariable);\n"
},
{
"answer_id": 127568,
"author": "wandercoder",
"author_id": 21655,
"author_profile": "https://Stackoverflow.com/users/21655",
"pm_score": 2,
"selected": false,
"text": "struct fieldsample\n{\n unsigned short field1 : 1;\n unsigned short field2 : 1;\n unsigned short field3 : 1;\n unsigned short field4 : 1;\n}\n void codesample()\n{\n //Declare the struct on the stack.\n fieldsample fields;\n //Initialize values.\n fields.f1 = 1;\n fields.f2 = 0;\n fields.f3 = 0;\n fields.f4 = 1;\n ...\n //Check the value of a field.\n if(fields.f1 == 1) {}\n ...\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
127,029
|
<p>Our application takes significantly more time to launch after a reboot (cold start) than if it was already opened once (warm start). </p>
<p>Most (if not all) the difference seems to come from loading DLLs, when the DLLs' are in cached memory pages they load much faster. We tried using <a href="http://mypchell.com/content/view/40/1/" rel="noreferrer">ClearMem</a> to simulate rebooting (since its much less time consuming than actually rebooting) and got mixed results, on some machines it seemed to simulate a reboot very consistently and in some not.</p>
<p>To sum up my questions are:</p>
<ol>
<li>Have you experienced differences in launch time between cold and warm starts?</li>
<li>How have you delt with such differences? </li>
<li>Do you know of a way to dependably simulate a reboot?</li>
</ol>
<p><strong>Edit:</strong></p>
<p>Clarifications for comments:</p>
<ul>
<li>The application is mostly native C++ with some .NET (the first .NET assembly that's loaded pays for the CLR).</li>
<li>We're looking to improve load time, obviously we did our share of profiling and improved the hotspots in our code.</li>
</ul>
<p>Something I forgot to mention was that we got some improvement by re-basing all our binaries so the loader doesn't have to do it at load time.</p>
|
[
{
"answer_id": 653865,
"author": "Baiyan Huang",
"author_id": 70198,
"author_profile": "https://Stackoverflow.com/users/70198",
"pm_score": 1,
"selected": false,
"text": "#pragma code_seg(\".startUp\")\n //...\n#pragma code_seg\n\n#pragma data_seg(\".startUp\")\n //...\n#pragma data_seg\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
127,040
|
<p>In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?</p>
|
[
{
"answer_id": 127064,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 6,
"selected": false,
"text": "function copyIntoClipboard(text) {\n\n var flashId = 'flashId-HKxmj5';\n\n /* Replace this with your clipboard.swf location */\n var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';\n\n if(!document.getElementById(flashId)) {\n var div = document.createElement('div');\n div.id = flashId;\n document.body.appendChild(div);\n }\n document.getElementById(flashId).innerHTML = '';\n var content = '<embed src=\"' +\n clipboardSWF +\n '\" FlashVars=\"clipboard=' + encodeURIComponent(text) +\n '\" width=\"0\" height=\"0\" type=\"application/x-shockwave-flash\"></embed>';\n document.getElementById(flashId).innerHTML = content;\n}\n"
},
{
"answer_id": 5420967,
"author": "David Barrett",
"author_id": 675107,
"author_profile": "https://Stackoverflow.com/users/675107",
"pm_score": 1,
"selected": false,
"text": "var memory = ''; // Outside the functions but within the script tag.\n\nfunction moz_stringCopy(DOMEle, firstPos, secondPos) {\n\n var copiedString = DOMEle.value.slice(firstPos, secondPos);\n memory = copiedString;\n}\n\nfunction moz_stringPaste(DOMEle, newpos) {\n\n DOMEle.value = DOMEle.value.slice(0, newpos) + memory + DOMEle.value.slice(newpos);\n}\n"
},
{
"answer_id": 18341824,
"author": "User",
"author_id": 2700706,
"author_profile": "https://Stackoverflow.com/users/2700706",
"pm_score": 1,
"selected": false,
"text": "window.clipboardData.clearData(DataFormat);"
},
{
"answer_id": 31945909,
"author": "a coder",
"author_id": 721073,
"author_profile": "https://Stackoverflow.com/users/721073",
"pm_score": 3,
"selected": false,
"text": "<button id='markup-copy'>Copy Button</button>\n\n<script>\ndocument.getElementById('markup-copy').addEventListener('click', function() {\n clipboard.copy({\n 'text/plain': 'Markup text. Paste me into a rich text editor.',\n 'text/html': '<i>here</i> is some <b>rich text</b>'\n }).then(\n function(){console.log('success'); },\n function(err){console.log('failure', err);\n });\n\n});\n</script>\n"
},
{
"answer_id": 34050374,
"author": "pythonHelpRequired",
"author_id": 5090468,
"author_profile": "https://Stackoverflow.com/users/5090468",
"pm_score": 6,
"selected": true,
"text": "document.execCommand('copy');\n document.getElementById('myText').select();\n function copier(){\n document.getElementById('myText').select();\n document.execCommand('copy');\n} <button onclick=\"copier()\">Copy</button>\n<textarea id=\"myText\">Copy me PLEASE!!!</textarea>"
},
{
"answer_id": 36611121,
"author": "Trevor",
"author_id": 269061,
"author_profile": "https://Stackoverflow.com/users/269061",
"pm_score": 1,
"selected": false,
"text": "document.execCommand('copy') function copyText(text){\n function selectElementText(element) {\n if (document.selection) {\n var range = document.body.createTextRange();\n range.moveToElementText(element);\n range.select();\n } else if (window.getSelection) {\n var range = document.createRange();\n range.selectNode(element);\n window.getSelection().removeAllRanges();\n window.getSelection().addRange(range);\n }\n }\n var element = document.createElement('DIV');\n element.textContent = text;\n document.body.appendChild(element);\n selectElementText(element);\n document.execCommand('copy');\n element.remove();\n}\n\n\nvar txt = document.getElementById('txt');\nvar btn = document.getElementById('btn');\nbtn.addEventListener('click', function(){\n copyText(txt.value);\n}) <input id=\"txt\" value=\"Hello World!\" />\n<button id=\"btn\">Copy To Clipboard</button>"
},
{
"answer_id": 41546309,
"author": "David from Studio.201",
"author_id": 3350621,
"author_profile": "https://Stackoverflow.com/users/3350621",
"pm_score": 2,
"selected": false,
"text": "var ClipboardHelper = { // As Object\n\n copyElement: function ($element)\n {\n this.copyText($element.text())\n },\n copyText:function(text) // Linebreaks with \\n\n {\n var $tempInput = $(\"<textarea>\");\n $(\"body\").append($tempInput);\n $tempInput.val(text).select();\n document.execCommand(\"copy\");\n $tempInput.remove();\n }\n};\n ClipboardHelper.copyText('Hello\\nWorld');\nClipboardHelper.copyElement($('body h1').first());\n // jQuery document\n;(function ( $, window, document, undefined ) {\n\n var ClipboardHelper = {\n\n copyElement: function ($element)\n {\n this.copyText($element.text())\n },\n copyText:function(text) // Linebreaks with \\n\n {\n var $tempInput = $(\"<textarea>\");\n $(\"body\").append($tempInput);\n\n //todo prepare Text: remove double whitespaces, trim\n\n $tempInput.val(text).select();\n document.execCommand(\"copy\");\n $tempInput.remove();\n }\n };\n\n $(document).ready(function()\n {\n var $body = $('body');\n\n $body.on('click', '*[data-copy-text-to-clipboard]', function(event)\n {\n var $btn = $(this);\n var text = $btn.attr('data-copy-text-to-clipboard');\n ClipboardHelper.copyText(text);\n });\n\n $body.on('click', '.js-copy-element-to-clipboard', function(event)\n {\n ClipboardHelper.copyElement($(this));\n });\n });\n})( jQuery, window, document ); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n\n<span data-copy-text-to-clipboard=\n \"Hello\n World\">\n Copy Text\n</span>\n\n<br><br>\n<span class=\"js-copy-element-to-clipboard\">\n Hello\n World\n Element\n</span>"
},
{
"answer_id": 43483323,
"author": "Chad Scira",
"author_id": 103696,
"author_profile": "https://Stackoverflow.com/users/103696",
"pm_score": 3,
"selected": false,
"text": "function copyStringToClipboard (string) {\n function handler (event){\n event.clipboardData.setData('text/plain', string);\n event.preventDefault();\n document.removeEventListener('copy', handler, true);\n }\n\n document.addEventListener('copy', handler, true);\n document.execCommand('copy');\n}\n copyStringToClipboard('Hello, World!') setData"
},
{
"answer_id": 54503704,
"author": "vhs",
"author_id": 712334,
"author_profile": "https://Stackoverflow.com/users/712334",
"pm_score": 1,
"selected": false,
"text": "document.execCommand const permalink = document.querySelector('[rel=\"bookmark\"]');\nconst output = document.querySelector('output');\npermalink.onclick = evt => {\n evt.preventDefault();\n window.navigator.clipboard.writeText(\n permalink.href\n ).then(() => {\n output.textContent = 'Copied';\n }, () => {\n output.textContent = 'Not copied';\n });\n}; <a href=\"https://stackoverflow.com/questions/127040/\" rel=\"bookmark\">Permalink</a>\n<output></output> Permissions"
},
{
"answer_id": 58633512,
"author": "Crashalot",
"author_id": 144088,
"author_profile": "https://Stackoverflow.com/users/144088",
"pm_score": 1,
"selected": false,
"text": "textarea // ================================================================================\n// ClipboardClass\n// ================================================================================\nvar ClipboardClass = (function() {\n\n function copyText(text) {\n // Create temp element off-screen to hold text.\n var tempElem = $('<textarea style=\"position: absolute; top: -8888px; left: -8888px\">');\n $(\"body\").append(tempElem);\n\n tempElem.val(text).select();\n document.execCommand(\"copy\");\n tempElem.remove();\n }\n\n\n // ============================================================================\n // Class API\n // ============================================================================\n return {\n copyText: copyText\n };\n})();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11492/"
] |
127,042
|
<p>I've found an <a href="http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx" rel="noreferrer">article</a> on how to elevate a COM object written in C++ by calling
<code>CoCreateInstanceAsAdmin</code>. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the <a href="http://msdn.microsoft.com/en-us/library/bb756990.aspx" rel="noreferrer">admin COM object model</a>.</p>
<p>I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the <a href="http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html" rel="noreferrer">post from Daniel Moth</a>, but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it.</p>
<p>Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the <code>CoCreateInstanceAsAdmin</code> API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs.</p>
<p>Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines:</p>
<pre><code>// in a dedicated assembly, marked with the following attributes:
[assembly: ComVisible (true)]
[assembly: Guid ("....")]
public class ElevatedClass
{
public void X() { /* do something */ }
}
</code></pre>
<p>and then have my main application just instanciate <code>ElevatedClass</code> through the <code>CoCreateInstanceAsAdmin</code> call. But maybe I am just dreaming.</p>
|
[
{
"answer_id": 311824,
"author": "Ryan",
"author_id": 20198,
"author_profile": "https://Stackoverflow.com/users/20198",
"pm_score": 3,
"selected": false,
"text": "[return: MarshalAs(UnmanagedType.Interface)]\nstatic internal object LaunchElevatedCOMObject(Guid Clsid, Guid InterfaceID)\n {\n string CLSID = Clsid.ToString(\"B\"); // B formatting directive: returns {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} \n string monikerName = \"Elevation:Administrator!new:\" + CLSID;\n\n NativeMethods.BIND_OPTS3 bo = new NativeMethods.BIND_OPTS3();\n bo.cbStruct = (uint)Marshal.SizeOf(bo);\n bo.hwnd = IntPtr.Zero;\n bo.dwClassContext = (int)NativeMethods.CLSCTX.CLSCTX_ALL;\n\n object retVal = UnsafeNativeMethods.CoGetObject(monikerName, ref bo, InterfaceID);\n\n return (retVal);\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597/"
] |
127,055
|
<p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
|
[
{
"answer_id": 127089,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 1,
"selected": false,
"text": "def num_of_groups(regexp):\n rg = re.compile(r'(?<!\\\\)\\(')\n return len(rg.findall(regexp))\n"
},
{
"answer_id": 127097,
"author": "miracle2k",
"author_id": 15677,
"author_profile": "https://Stackoverflow.com/users/15677",
"pm_score": 2,
"selected": false,
"text": ">>> import sre_parse\n>>> sre_parse.parse('(\\d)\\d(\\d)')\n[('subpattern', (1, [('in', [('category', 'category_digit')])])), \n('in', [('category', 'category_digit')]), \n('subpattern', (2, [('in', [('category', 'category_digit')])]))]\n import sre_parse\n\ndef count_patterns(regex):\n \"\"\"\n >>> count_patterns('foo: \\d')\n 0\n >>> count_patterns('foo: (\\d)')\n 1\n >>> count_patterns('foo: (\\d(\\s))')\n 1\n \"\"\"\n parsed = sre_parse.parse(regex)\n return len([token for token in parsed if token[0] == 'subpattern'])\n"
},
{
"answer_id": 127392,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 1,
"selected": false,
"text": "def groups(regexp, s):\n \"\"\" Returns the first result of re.findall, or an empty default\n\n >>> groups(r'(\\d)(\\d)(\\d)', '123')\n ('1', '2', '3')\n >>> groups(r'(\\d)(\\d)(\\d)', 'abc')\n ('', '', '')\n \"\"\"\n import re\n m = re.search(regexp, s)\n if m:\n return m.groups()\n return ('',) * len(m.groups())\n"
},
{
"answer_id": 136215,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 7,
"selected": true,
"text": "def num_groups(regex):\n return re.compile(regex).groups\n"
},
{
"answer_id": 28284530,
"author": "vestronge",
"author_id": 3845408,
"author_profile": "https://Stackoverflow.com/users/3845408",
"pm_score": 5,
"selected": false,
"text": "f_x = re.search(...)\nlen_groups = len(f_x.groups())\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] |
127,076
|
<p>In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?</p>
<p>i.e.</p>
<pre><code>dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
</code></pre>
<p>On Row Select</p>
<pre><code>Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub
</code></pre>
|
[
{
"answer_id": 127114,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "dim x as object = foo(e.row.selectedIndex)\n"
},
{
"answer_id": 127123,
"author": "kristian",
"author_id": 20377,
"author_profile": "https://Stackoverflow.com/users/20377",
"pm_score": 0,
"selected": false,
"text": "foo(CInt(e.CommandArgument))"
},
{
"answer_id": 127265,
"author": "Jared",
"author_id": 7388,
"author_profile": "https://Stackoverflow.com/users/7388",
"pm_score": 3,
"selected": true,
"text": "<asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateSelectButton=\"True\" \n DataKeyNames=\"Name\" onrowcommand=\"GridView1_RowCommand1\" \n onselectedindexchanged=\"GridView1_SelectedIndexChanged\">\n</asp:GridView>\n protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n // Value is the Name property of the selected row's bound object.\n string foo = GridView1.SelectedDataKey.Value as string; \n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
127,095
|
<p>I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:</p>
<pre><code>/// <summary>
/// Method to calculate distance between two points
/// </summary>
///
/// <param name="pointA">First point</param>
/// <param name="pointB">Second point</param>
///
function calculatePointDistance(pointA, pointB) { ... }
</code></pre>
<p>Recently I've been looking into other third-party JavaScript libraries and I see syntax like:</p>
<pre><code>/*
* some comment here
* another comment here
* ...
*/
function blahblah() { ... }
</code></pre>
<p>As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style?</p>
|
[
{
"answer_id": 127106,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 8,
"selected": true,
"text": "/**\n * Shape is an abstract base class. It is defined simply\n * to have something to inherit from for geometric \n * subclasses\n * @constructor\n */\nfunction Shape(color){\n this.color = color;\n}\n"
},
{
"answer_id": 127600,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": false,
"text": "var Namespace = {};\n Namespace.AnotherNamespace = {};\n\nNamespace.AnotherNamespace.annoyingAlert = function(_message)\n{\n /// <param name=\"_message\">The message you want alerted two times</param>\n /// <summary>This is really annoying!!</summary>\n\n alert(_message);\n alert(_message);\n};\n"
},
{
"answer_id": 14419647,
"author": "molokoloco",
"author_id": 174449,
"author_profile": "https://Stackoverflow.com/users/174449",
"pm_score": 5,
"selected": false,
"text": "var something = 10; // My comment\n\n/*\nLorem ipsum dolor sit amet, consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco\nnisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\nin reprehenderit in voluptate velit esse cillum dolore eu\nfugiat nulla pariatur.\n*/\n\nfunction bigThing() {\n // ...\n}\n /**\n * Adds two numbers.\n * @param {number} num1 The first number to add.\n * @param {number} num2 The second number to add.\n * @return {number} The result of adding num1 and num2.\n */\nfunction bigThing() {\n // ...\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] |
127,116
|
<p>I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.</p>
<p>For example 5 would be converted to "101" and stored as a varchar.</p>
|
[
{
"answer_id": 127371,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 5,
"selected": true,
"text": "declare @intvalue int\nset @intvalue=5\n\ndeclare @vsresult varchar(64)\ndeclare @inti int\nselect @inti = 64, @vsresult = ''\nwhile @inti>0\n begin\n select @vsresult=convert(char(1), @intvalue % 2)+@vsresult\n select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1\n end\nselect @vsresult\n"
},
{
"answer_id": 128233,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "declare @i int /* input */\nset @i = 42\n\ndeclare @result varchar(32) /* SQL Server int is 32 bits wide */\nset @result = ''\nwhile 1 = 1 begin\n select @result = convert(char(1), @i % 2) + @result,\n @i = convert(int, @i / 2)\n if @i = 0 break\nend\n\nselect @result\n"
},
{
"answer_id": 1103900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "declare @intVal Int \nset @intVal = power(2,12)+ power(2,5) + power(2,1);\nWith ComputeBin (IntVal, BinVal,FinalBin)\nAs\n (\n Select @IntVal IntVal, @intVal %2 BinVal , convert(nvarchar(max),(@intVal %2 )) FinalBin\n Union all\n Select IntVal /2, (IntVal /2) %2, convert(nvarchar(max),(IntVal /2) %2) + FinalBin FinalBin\n From ComputeBin\n Where IntVal /2 > 0\n)\nselect FinalBin from ComputeBin where intval = ( select min(intval) from ComputeBin);\n"
},
{
"answer_id": 6750799,
"author": "Juan Jimenez",
"author_id": 679569,
"author_profile": "https://Stackoverflow.com/users/679569",
"pm_score": 3,
"selected": false,
"text": "select reverse(dbo.ConvertToBase(5, 2)) -- 101\n"
},
{
"answer_id": 11273122,
"author": "Mathew Frank",
"author_id": 1276573,
"author_profile": "https://Stackoverflow.com/users/1276573",
"pm_score": 5,
"selected": false,
"text": " select t.Number\n , cast(t.Number & 64 as bit) as bit7\n , cast(t.Number & 32 as bit) as bit6\n , cast(t.Number & 16 as bit) as bit5\n , cast(t.Number & 8 as bit) as bit4\n , cast(t.Number & 4 as bit) as bit3\n , cast(t.Number & 2 as bit) as bit2\n ,cast(t.Number & 1 as bit) as bit1\n\n , cast(cast(t.Number & 64 as bit) as CHAR(1)) \n +cast( cast(t.Number & 32 as bit) as CHAR(1))\n +cast( cast(t.Number & 16 as bit) as CHAR(1))\n +cast( cast(t.Number & 8 as bit) as CHAR(1))\n +cast( cast(t.Number & 4 as bit) as CHAR(1))\n +cast( cast(t.Number & 2 as bit) as CHAR(1))\n +cast(cast(t.Number & 1 as bit) as CHAR(1)) as binary_string\n --to explicitly answer the question, on MSSQL without using REGEXP (which would make it simple)\n ,SUBSTRING(cast(cast(t.Number & 64 as bit) as CHAR(1)) \n +cast( cast(t.Number & 32 as bit) as CHAR(1))\n +cast( cast(t.Number & 16 as bit) as CHAR(1))\n +cast( cast(t.Number & 8 as bit) as CHAR(1))\n +cast( cast(t.Number & 4 as bit) as CHAR(1))\n +cast( cast(t.Number & 2 as bit) as CHAR(1))\n +cast(cast(t.Number & 1 as bit) as CHAR(1))\n ,\n PATINDEX('%1%', cast(cast(t.Number & 64 as bit) as CHAR(1)) \n +cast( cast(t.Number & 32 as bit) as CHAR(1))\n +cast( cast(t.Number & 16 as bit) as CHAR(1))\n +cast( cast(t.Number & 8 as bit) as CHAR(1))\n +cast( cast(t.Number & 4 as bit) as CHAR(1))\n +cast( cast(t.Number & 2 as bit) as CHAR(1))\n +cast(cast(t.Number & 1 as bit) as CHAR(1) )\n )\n,99)\n\n\nfrom (select 1 as Number union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 \n union all select 7 union all select 8 union all select 9 union all select 10) as t\n num bit7 bit6 bit5 bit4 bit3 bit2 bit1 binary_string binary_string_trimmed \n1 0 0 0 0 0 0 1 0000001 1\n2 0 0 0 0 0 1 0 0000010 10\n3 0 0 0 0 0 1 1 0000011 11\n4 0 0 0 1 0 0 0 0000100 100\n5 0 0 0 0 1 0 1 0000101 101\n6 0 0 0 0 1 1 0 0000110 110\n7 0 0 0 0 1 1 1 0000111 111\n8 0 0 0 1 0 0 0 0001000 1000\n9 0 0 0 1 0 0 1 0001001 1001\n10 0 0 0 1 0 1 0 0001010 1010\n"
},
{
"answer_id": 28909115,
"author": "Rob",
"author_id": 4642846,
"author_profile": "https://Stackoverflow.com/users/4642846",
"pm_score": -1,
"selected": false,
"text": "SELECT number_value\n,MOD(number_value / 32768, 2) AS BIT15\n,MOD(number_value / 16384, 2) AS BIT14\n,MOD(number_value / 8192, 2) AS BIT13\n,MOD(number_value / 4096, 2) AS BIT12\n,MOD(number_value / 2048, 2) AS BIT11\n,MOD(number_value / 1024, 2) AS BIT10\n,MOD(number_value / 512, 2) AS BIT9 \n,MOD(number_value / 256, 2) AS BIT8 \n,MOD(number_value / 128, 2) AS BIT7 \n,MOD(number_value / 64, 2) AS BIT6 \n,MOD(number_value / 32, 2) AS BIT5 \n,MOD(number_value / 16, 2) AS BIT4 \n,MOD(number_value / 8, 2) AS BIT3 \n,MOD(number_value / 4, 2) AS BIT2 \n,MOD(number_value / 2, 2) AS BIT1 \n,MOD(number_value , 2) AS BIT0 \nFROM your_table;\n"
},
{
"answer_id": 35707978,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "FOR XML DECLARE @my_int INT = 5\n\n;WITH CTE_Binary AS\n(\n SELECT 1 AS seq, 1 AS val\n UNION ALL\n SELECT seq + 1 AS seq, power(2, seq)\n FROM CTE_Binary\n WHERE\n seq < 8\n)\nSELECT\n(\n SELECT\n CAST(CASE WHEN B2.seq IS NOT NULL THEN 1 ELSE 0 END AS CHAR(1))\n FROM\n CTE_Binary B1\n LEFT OUTER JOIN CTE_Binary B2 ON\n B2.seq = B1.seq AND\n @my_int & B2.val = B2.val\n ORDER BY\n B1.seq DESC\n FOR XML PATH('')\n) AS val\n"
},
{
"answer_id": 36548099,
"author": "hkravitz",
"author_id": 2919045,
"author_profile": "https://Stackoverflow.com/users/2919045",
"pm_score": 2,
"selected": false,
"text": " CREATE FUNCTION dbo.udf_DecimalToBinary \n (\n @Decimal VARCHAR(32)\n )\n\n RETURNS TABLE AS RETURN\n\n WITH Tally (n) AS\n (\n --32 Rows\n SELECT TOP 30 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1\n FROM (VALUES (0),(0),(0),(0)) a(n)\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\n\n ) \n\n , Anchor (n, divisor , Result) as \n (\n SELECT t.N , \n CONVERT(BIGINT, @Decimal) / POWER(2,T.N) , \n CONVERT(BIGINT, @Decimal) / POWER(2,T.N) % 2 \n FROM Tally t \n WHERE CONVERT(bigint,@Decimal) >= POWER(2,t.n)\n )\n\n\n SELECT TwoBaseBinary = '' +\n (SELECT Result \n FROM Anchor\n ORDER BY N DESC \n FOR XML PATH ('') , TYPE).value('.','varchar(200)')\n\n /*How to use*/\n SELECT TwoBaseBinary \n FROM dbo.udf_DecimalToBinary ('1234')\n\n /*result -> 10011010010*/\n"
},
{
"answer_id": 37763062,
"author": "user6453285",
"author_id": 6453285,
"author_profile": "https://Stackoverflow.com/users/6453285",
"pm_score": 1,
"selected": false,
"text": "with t as (select * from (values (0),(1)) as t(c)),\n\nt0 as (table t),\nt1 as (table t),\nt2 as (table t),\nt3 as (table t),\nt4 as (table t),\nt5 as (table t),\nt6 as (table t),\nt7 as (table t),\nt8 as (table t),\nt9 as (table t),\nta as (table t),\ntb as (table t),\ntc as (table t),\ntd as (table t),\nte as (table t),\ntf as (table t)\n\nselect '' || t0.c || t1.c || t2.c || t3.c || t4.c || t5.c || t6.c || t7.c || t8.c || t9.c || ta.c || tb.c || tc.c || td.c || te.c || tf.c as n\nfrom t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,ta,tb,tc,td,te,tf\norder by n \n\nlimit 1 offset 5\n"
},
{
"answer_id": 43757497,
"author": "Evandro",
"author_id": 7684390,
"author_profile": "https://Stackoverflow.com/users/7684390",
"pm_score": 1,
"selected": false,
"text": "DECLARE @Int int = 321\n\nSELECT @Int\n,CONCAT\n(CAST(@Int & power(2,15) AS bit)\n,CAST(@Int & power(2,14) AS bit)\n,CAST(@Int & power(2,13) AS bit)\n,CAST(@Int & power(2,12) AS bit)\n,CAST(@Int & power(2,11) AS bit)\n,CAST(@Int & power(2,10) AS bit)\n,CAST(@Int & power(2,9) AS bit)\n,CAST(@Int & power(2,8) AS bit)\n,CAST(@Int & power(2,7) AS bit)\n,CAST(@Int & power(2,6) AS bit)\n,CAST(@Int & power(2,5) AS bit)\n,CAST(@Int & power(2,4) AS bit)\n,CAST(@Int & power(2,3) AS bit)\n,CAST(@Int & power(2,2) AS bit)\n,CAST(@Int & power(2,1) AS bit)\n,CAST(@Int & power(2,0) AS bit) ) AS BitString\n\n,CAST(@Int & power(2,15) AS bit) AS BIT15\n,CAST(@Int & power(2,14) AS bit) AS BIT14\n,CAST(@Int & power(2,13) AS bit) AS BIT13\n,CAST(@Int & power(2,12) AS bit) AS BIT12\n,CAST(@Int & power(2,11) AS bit) AS BIT11\n,CAST(@Int & power(2,10) AS bit) AS BIT10\n,CAST(@Int & power(2,9) AS bit) AS BIT9 \n,CAST(@Int & power(2,8) AS bit) AS BIT8 \n,CAST(@Int & power(2,7) AS bit) AS BIT7 \n,CAST(@Int & power(2,6) AS bit) AS BIT6 \n,CAST(@Int & power(2,5) AS bit) AS BIT5 \n,CAST(@Int & power(2,4) AS bit) AS BIT4 \n,CAST(@Int & power(2,3) AS bit) AS BIT3 \n,CAST(@Int & power(2,2) AS bit) AS BIT2 \n,CAST(@Int & power(2,1) AS bit) AS BIT1 \n,CAST(@Int & power(2,0) AS bit) AS BIT0 \n"
},
{
"answer_id": 46224410,
"author": "Bohden M",
"author_id": 5535984,
"author_profile": "https://Stackoverflow.com/users/5535984",
"pm_score": 2,
"selected": false,
"text": "Create function f_DecimalToBinaryString\n (\n @Dec int,\n @MaxLength int = null\n )\nReturns varchar(max)\nas Begin\n\n Declare @BinStr varchar(max) = '';\n\n -- Perform the translation from Dec to Bin\n While @Dec > 0 Begin\n\n Set @BinStr = Convert(char(1), @Dec % 2) + @BinStr;\n Set @Dec = Convert(int, @Dec /2);\n\n End;\n\n -- Either pad or trim the output to match the number of digits specified.\n If (@MaxLength is not null) Begin\n If @MaxLength <= Len(@BinStr) Begin -- Trim down\n Set @BinStr = SubString(@BinStr, Len(@BinStr) - (@MaxLength - 1), @MaxLength);\n End Else Begin -- Pad up\n Set @BinStr = Replicate('0', @MaxLength - Len(@BinStr)) + @BinStr;\n End;\n End;\n\n Return @BinStr;\n\nEnd;\n"
},
{
"answer_id": 58844263,
"author": "Alan Burstein",
"author_id": 2647342,
"author_profile": "https://Stackoverflow.com/users/2647342",
"pm_score": 1,
"selected": false,
"text": "dbo.rangeAB SELECT r.RN\nFROM dbo.rangeAB(0,30,1,0) AS r\nORDER BY r.RN;\n SELECT r.RN, r.OP\nFROM dbo.rangeAB(0,30,1,0) AS r\nORDER BY r.RN;\n RN OP\n----- -------\n0 30\n1 29\n2 28\n3 27\n....\n27 3\n28 2\n29 1\n30 0\n CREATE FUNCTION dbo.NumberToBinary(@input INT)\nRETURNS TABLE WITH SCHEMABINDING AS RETURN\n/* Created By Alan Burstein 20191112, Requires RangeAB (code below) */\nSELECT BIN = (\n SELECT @input/f.Np2%2\n FROM dbo.rangeAB(0,30,1,0) AS r\n CROSS APPLY (VALUES(POWER(2,r.Op))) AS f(NP2)\n WHERE (@input = 0 AND f.Np2 = 1) OR @input >= f.Np2\n ORDER BY ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\n FOR XML PATH(''));\n CREATE FUNCTION dbo.rangeAB\n(\n @low bigint, \n @high bigint, \n @gap bigint,\n @row1 bit\n)\n/****************************************************************************************\n[Purpose]:\n Creates up to 531,441,000,000 sequentia1 integers numbers beginning with @low and ending \n with @high. Used to replace iterative methods such as loops, cursors and recursive CTEs \n to solve SQL problems. Based on Itzik Ben-Gan's getnums function with some tweeks and \n enhancements and added functionality. The logic for getting rn to begin at 0 or 1 is \n based comes from Jeff Moden's fnTally function. \n\n The name range because it's similar to clojure's range function. The name \"rangeAB\" as \n used because \"range\" is a reserved SQL keyword.\n\n[Author]: Alan Burstein\n\n[Compatibility]: \n SQL Server 2008+ and Azure SQL Database\n\n[Syntax]:\n SELECT r.RN, r.OP, r.N1, r.N2\n FROM dbo.rangeAB(@low,@high,@gap,@row1) AS r;\n\n[Parameters]:\n @low = a bigint that represents the lowest value for n1.\n @high = a bigint that represents the highest value for n1.\n @gap = a bigint that represents how much n1 and n2 will increase each row; @gap also\n represents the difference between n1 and n2.\n @row1 = a bit that represents the first value of rn. When @row = 0 then rn begins\n at 0, when @row = 1 then rn will begin at 1.\n\n[Returns]:\n Inline Table Valued Function returns:\n rn = bigint; a row number that works just like T-SQL ROW_NUMBER() except that it can \n start at 0 or 1 which is dictated by @row1.\n op = bigint; returns the \"opposite number that relates to rn. When rn begins with 0 and\n ends with 10 then 10 is the opposite of 0, 9 the opposite of 1, etc. When rn begins\n with 1 and ends with 5 then 1 is the opposite of 5, 2 the opposite of 4, etc...\n n1 = bigint; a sequential number starting at the value of @low and incrimentingby the\n value of @gap until it is less than or equal to the value of @high.\n n2 = bigint; a sequential number starting at the value of @low+@gap and incrimenting \n by the value of @gap.\n\n[Dependencies]:\nN/A\n\n[Developer Notes]:\n\n 1. The lowest and highest possible numbers returned are whatever is allowable by a \n bigint. The function, however, returns no more than 531,441,000,000 rows (8100^3). \n 2. @gap does not affect rn, rn will begin at @row1 and increase by 1 until the last row\n unless its used in a query where a filter is applied to rn.\n 3. @gap must be greater than 0 or the function will not return any rows.\n 4. Keep in mind that when @row1 is 0 then the highest row-number will be the number of\n rows returned minus 1\n 5. If you only need is a sequential set beginning at 0 or 1 then, for best performance\n use the RN column. Use N1 and/or N2 when you need to begin your sequence at any \n number other than 0 or 1 or if you need a gap between your sequence of numbers. \n 6. Although @gap is a bigint it must be a positive integer or the function will\n not return any rows.\n 7. The function will not return any rows when one of the following conditions are true:\n * any of the input parameters are NULL\n * @high is less than @low \n * @gap is not greater than 0\n To force the function to return all NULLs instead of not returning anything you can\n add the following code to the end of the query:\n\n UNION ALL \n SELECT NULL, NULL, NULL, NULL\n WHERE NOT (@high&@low&@gap&@row1 IS NOT NULL AND @high >= @low AND @gap > 0)\n\n This code was excluded as it adds a ~5% performance penalty.\n 8. There is no performance penalty for sorting by rn ASC; there is a large performance \n penalty for sorting in descending order WHEN @row1 = 1; WHEN @row1 = 0\n If you need a descending sort the use op in place of rn then sort by rn ASC. \n\nBest Practices:\n--===== 1. Using RN (rownumber)\n -- (1.1) The best way to get the numbers 1,2,3...@high (e.g. 1 to 5):\n SELECT RN FROM dbo.rangeAB(1,5,1,1);\n -- (1.2) The best way to get the numbers 0,1,2...@high-1 (e.g. 0 to 5):\n SELECT RN FROM dbo.rangeAB(0,5,1,0);\n\n--===== 2. Using OP for descending sorts without a performance penalty\n -- (2.1) The best way to get the numbers 5,4,3...@high (e.g. 5 to 1):\n SELECT op FROM dbo.rangeAB(1,5,1,1) ORDER BY rn ASC;\n -- (2.2) The best way to get the numbers 0,1,2...@high-1 (e.g. 5 to 0):\n SELECT op FROM dbo.rangeAB(1,6,1,0) ORDER BY rn ASC;\n\n--===== 3. Using N1\n -- (3.1) To begin with numbers other than 0 or 1 use N1 (e.g. -3 to 3):\n SELECT N1 FROM dbo.rangeAB(-3,3,1,1);\n -- (3.2) ROW_NUMBER() is built in. If you want a ROW_NUMBER() include RN:\n SELECT RN, N1 FROM dbo.rangeAB(-3,3,1,1);\n -- (3.3) If you wanted a ROW_NUMBER() that started at 0 you would do this:\n SELECT RN, N1 FROM dbo.rangeAB(-3,3,1,0);\n\n--===== 4. Using N2 and @gap\n -- (4.1) To get 0,10,20,30...100, set @low to 0, @high to 100 and @gap to 10:\n SELECT N1 FROM dbo.rangeAB(0,100,10,1);\n -- (4.2) Note that N2=N1+@gap; this allows you to create a sequence of ranges.\n -- For example, to get (0,10),(10,20),(20,30).... (90,100):\n SELECT N1, N2 FROM dbo.rangeAB(0,90,10,1);\n -- (4.3) Remember that a rownumber is included and it can begin at 0 or 1:\n SELECT RN, N1, N2 FROM dbo.rangeAB(0,90,10,1);\n\n[Examples]:\n--===== 1. Generating Sample data (using rangeAB to create \"dummy rows\")\n -- The query below will generate 10,000 ids and random numbers between 50,000 and 500,000\n SELECT\n someId = r.rn,\n someNumer = ABS(CHECKSUM(NEWID())%450000)+50001 \n FROM rangeAB(1,10000,1,1) r;\n\n--===== 2. Create a series of dates; rn is 0 to include the first date in the series\n DECLARE @startdate DATE = '20180101', @enddate DATE = '20180131';\n\n SELECT r.rn, calDate = DATEADD(dd, r.rn, @startdate)\n FROM dbo.rangeAB(1, DATEDIFF(dd,@startdate,@enddate),1,0) r;\n GO\n\n--===== 3. Splitting (tokenizing) a string with fixed sized items\n -- given a delimited string of identifiers that are always 7 characters long\n DECLARE @string VARCHAR(1000) = 'A601225,B435223,G008081,R678567';\n\n SELECT\n itemNumber = r.rn, -- item's ordinal position \n itemIndex = r.n1, -- item's position in the string (it's CHARINDEX value)\n item = SUBSTRING(@string, r.n1, 7) -- item (token)\n FROM dbo.rangeAB(1, LEN(@string), 8,1) r;\n GO\n\n--===== 4. Splitting (tokenizing) a string with random delimiters\n DECLARE @string VARCHAR(1000) = 'ABC123,999F,XX,9994443335';\n\n SELECT\n itemNumber = ROW_NUMBER() OVER (ORDER BY r.rn), -- item's ordinal position \n itemIndex = r.n1+1, -- item's position in the string (it's CHARINDEX value)\n item = SUBSTRING\n (\n @string,\n r.n1+1,\n ISNULL(NULLIF(CHARINDEX(',',@string,r.n1+1),0)-r.n1-1, 8000)\n ) -- item (token)\n FROM dbo.rangeAB(0,DATALENGTH(@string),1,1) r\n WHERE SUBSTRING(@string,r.n1,1) = ',' OR r.n1 = 0;\n -- logic borrowed from: http://www.sqlservercentral.com/articles/Tally+Table/72993/\n\n--===== 5. Grouping by a weekly intervals\n -- 5.1. how to create a series of start/end dates between @startDate & @endDate\n DECLARE @startDate DATE = '1/1/2015', @endDate DATE = '2/1/2015';\n SELECT \n WeekNbr = r.RN,\n WeekStart = DATEADD(DAY,r.N1,@StartDate), \n WeekEnd = DATEADD(DAY,r.N2-1,@StartDate)\n FROM dbo.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) r;\n GO\n\n -- 5.2. LEFT JOIN to the weekly interval table\n BEGIN\n DECLARE @startDate datetime = '1/1/2015', @endDate datetime = '2/1/2015';\n -- sample data \n DECLARE @loans TABLE (loID INT, lockDate DATE);\n INSERT @loans SELECT r.rn, DATEADD(dd, ABS(CHECKSUM(NEWID())%32), @startDate)\n FROM dbo.rangeAB(1,50,1,1) r;\n\n -- solution \n SELECT \n WeekNbr = r.RN,\n WeekStart = dt.WeekStart, \n WeekEnd = dt.WeekEnd,\n total = COUNT(l.lockDate)\n FROM dbo.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) r\n CROSS APPLY (VALUES (\n CAST(DATEADD(DAY,r.N1,@StartDate) AS DATE), \n CAST(DATEADD(DAY,r.N2-1,@StartDate) AS DATE))) dt(WeekStart,WeekEnd)\n LEFT JOIN @loans l ON l.lockDate BETWEEN dt.WeekStart AND dt.WeekEnd\n GROUP BY r.RN, dt.WeekStart, dt.WeekEnd ;\n END;\n\n--===== 6. Identify the first vowel and last vowel in a along with their positions\n DECLARE @string VARCHAR(200) = 'This string has vowels';\n\n SELECT TOP(1) position = r.rn, letter = SUBSTRING(@string,r.rn,1)\n FROM dbo.rangeAB(1,LEN(@string),1,1) r\n WHERE SUBSTRING(@string,r.rn,1) LIKE '%[aeiou]%'\n ORDER BY r.rn;\n\n -- To avoid a sort in the execution plan we'll use op instead of rn\n SELECT TOP(1) position = r.op, letter = SUBSTRING(@string,r.op,1)\n FROM dbo.rangeAB(1,LEN(@string),1,1) r\n WHERE SUBSTRING(@string,r.rn,1) LIKE '%[aeiou]%'\n ORDER BY r.rn;\n\n---------------------------------------------------------------------------------------\n[Revision History]:\n Rev 00 - 20140518 - Initial Development - Alan Burstein\n Rev 01 - 20151029 - Added 65 rows to make L1=465; 465^3=100.5M. Updated comment section\n - Alan Burstein\n Rev 02 - 20180613 - Complete re-design including opposite number column (op)\n Rev 03 - 20180920 - Added additional CROSS JOIN to L2 for 530B rows max - Alan Burstein\n****************************************************************************************/\nRETURNS TABLE WITH SCHEMABINDING AS RETURN\nWITH L1(N) AS \n(\n SELECT 1\n FROM (VALUES\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0)) T(N) -- 90 values \n),\nL2(N) AS (SELECT 1 FROM L1 a CROSS JOIN L1 b CROSS JOIN L1 c),\niTally AS (SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM L2 a CROSS JOIN L2 b)\nSELECT\n r.RN,\n r.OP,\n r.N1,\n r.N2\nFROM\n(\n SELECT\n RN = 0,\n OP = (@high-@low)/@gap,\n N1 = @low,\n N2 = @gap+@low\n WHERE @row1 = 0\n UNION ALL -- ISNULL required in the TOP statement below for error handling purposes\n SELECT TOP (ABS((ISNULL(@high,0)-ISNULL(@low,0))/ISNULL(@gap,0)+ISNULL(@row1,1)))\n RN = i.rn,\n OP = (@high-@low)/@gap+(2*@row1)-i.rn,\n N1 = (i.rn-@row1)*@gap+@low,\n N2 = (i.rn-(@row1-1))*@gap+@low\n FROM iTally AS i\n ORDER BY i.rn\n) AS r\nWHERE @high&@low&@gap&@row1 IS NOT NULL AND @high >= @low AND @gap > 0;\nGO\n"
},
{
"answer_id": 61551508,
"author": "Sandro Herrera",
"author_id": 4051128,
"author_profile": "https://Stackoverflow.com/users/4051128",
"pm_score": 0,
"selected": false,
"text": "WITH DecimalTable AS (SELECT 10 decimal_num UNION SELECT 20),\n DtoB AS (SELECT decimal_num\n ,1 n\n ,CAST(CAST(decimal_num%2 AS bit) AS VARCHAR(16)) binary_num\n FROM DecimalTable \n UNION ALL\n SELECT decimal_num\n ,n*2 n\n ,CAST(CONCAT(CAST(decimal_num&n as bit), binary_num)\n AS VARCHAR(16)) binary_num\n FROM DtoB\n WHERE n<POWER(2,16))\n\n SELECT decimal_num, binary_num\n FROM DtoB\n"
},
{
"answer_id": 65727886,
"author": "kpkpkp",
"author_id": 746054,
"author_profile": "https://Stackoverflow.com/users/746054",
"pm_score": 0,
"selected": false,
"text": "-- specify a string and numbering system Base value, for example 16 for hexadecimal\nCREATE FUNCTION udf_IntToBaseXStr(@baseVal BIGINT,\n @baseX BIGINT)\nreturns VARCHAR(63)\nAS\n BEGIN\n --bigint : -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) \n -- or 63 ones (1111111,11111111,11111111,11111111,11111111,11111111,11111111,11111111) in binary\n DECLARE @val BIGINT -- value from all\n DECLARE @cv BIGINT -- value from a single char\n DECLARE @baseStr VARCHAR(63)\n SET @baseStr = '';\n -- assumes a numbering method of 0123456789ABCDEF..... \n SET @val = @baseVal\n WHILE ( @val > 0 )\n BEGIN\n SET @cv = @val % @basex -- calculate the right most char's value\n SET @baseStr = -- add it to (any existing) string\n CASE\n WHEN @cv < 10 THEN Char(Ascii('0') + @cv)\n ELSE Char(Ascii('A') + ( @cv - 10 ))\n END\n + @baseStr\n SET @val = ( @val - @cv ) / @basex\n END\n RETURN @baseStr\n END\nGO\n -- specify a string and numbering system Base value, for example, 16 for hexadecimal\n-- prepends LEADING ZEROS to force length of returned string to be AT LEAST minLength chars\nCREATE FUNCTION udf_IntToBaseXStr_MinLength(@baseVal BIGINT,\n @baseX BIGINT,\n @minLength INT)\nreturns VARCHAR(63)\nAS\n BEGIN\n DECLARE @baseStr VARCHAR(63)\n SET @baseStr = dbo.udf_IntToBaseXStr(@baseVal, @baseX)\n IF Len(@baseStr) < @minLength\n SET @baseStr = Replicate('0', @minLength - Len(@baseStr))\n + @baseStr\n RETURN @baseStr\n END\nGO\n ;with CTE as \n(\n SELECT BaseX = 2, AKA = 'binary' \n UNION SELECT 8, 'octal' \n UNION SELECT 10, 'decimal' \n UNION SELECT 15, 'pentadecimal' \n UNION SELECT 16, 'hexadecimal' \n)\nSELECT BaseX, AKA, Result = dbo.udf_IntToBaseXStr(328239523, BaseX) FROM CTE\n ;with CTE as \n(\n SELECT BaseX = 2, AKA = 'binary' \n UNION SELECT 8, 'octal' \n UNION SELECT 10, 'decimal' \n UNION SELECT 15, 'pentadecimal' \n UNION SELECT 16, 'hexadecimal' \n)\nSELECT BaseX, AKA, Result = dbo.udf_IntToBaseXStr_MinLength(328239523, BaseX, 24) FROM CTE\n"
},
{
"answer_id": 67607735,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION dbo.BinaryRep (@val INT)\nRETURNS VARCHAR(32)\nWITH EXECUTE AS CALLER\nAS\n\nBEGIN\n DECLARE @ret VARCHAR(32)\n DECLARE @cnt INT = 30; -- 30 to 0 inclusive in loop\n \n -- handle negative (we're using signed magnitude because that's simple)\n SET @ret = IIF(@val < 0, '1', '0');\n SET @val = ABS(@val); -- totally cheating here.\n \n -- bitwise masking madness, one digit at a time. \n WHILE @cnt > -1\n BEGIN\n SET @ret = CONCAT(@ret, IIF(@val & POWER(2, @cnt) = 0, 0, 1));\n SET @cnt = @cnt - 1;\n END;\n \n RETURN @ret;\nEND\n 1 -123 123 select dbo.BinaryRep(123) as plus, dbo.BinaryRep(-123) as minus\n\nplus minus\n-------------------------------- --------------------------------\n00000000000000000000000001111011 10000000000000000000000001111011\n INT"
},
{
"answer_id": 68118805,
"author": "ChrisD",
"author_id": 8472728,
"author_profile": "https://Stackoverflow.com/users/8472728",
"pm_score": -1,
"selected": false,
"text": "declare @num int = 75\n\nselect\n@num [Dec]\n, convert (varchar(1), @num / 128 % 2)\n+ convert (varchar(1), @num / 64 % 2)\n+ convert (varchar(1), @num / 32 % 2)\n+ convert (varchar(1), @num / 16 % 2)\n+ convert (varchar(1), @num / 8 % 2)\n+ convert (varchar(1), @num / 4 % 2)\n+ convert (varchar(1), @num / 2 % 2)\n+ convert (varchar(1), @num % 2) as [Bin]\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4779/"
] |
127,124
|
<p>How do you resolve an NT style device path, e.g. <code>\Device\CdRom0</code>, to its logical drive letter, e.g. <code>G:\</code> ?</p>
<p>Edit: A Volume Name isn't the same as a Device Path so unfortunately <code>GetVolumePathNamesForVolumeName()</code> won't work.</p>
|
[
{
"answer_id": 132048,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 4,
"selected": true,
"text": "typedef basic_string<TCHAR> tstring;\ntypedef map<tstring, tstring> HardDiskCollection;\n\nvoid Initialise( HardDiskCollection &_hardDiskCollection )\n{\n TCHAR tszLinkName[MAX_PATH] = { 0 };\n TCHAR tszDevName[MAX_PATH] = { 0 };\n TCHAR tcDrive = 0;\n\n _tcscpy_s( tszLinkName, MAX_PATH, _T(\"a:\") );\n for ( tcDrive = _T('a'); tcDrive < _T('z'); ++tcDrive )\n {\n tszLinkName[0] = tcDrive;\n if ( QueryDosDevice( tszLinkName, tszDevName, MAX_PATH ) )\n {\n _hardDiskCollection.insert( pair<tstring, tstring>( tszLinkName, tszDevName ) );\n }\n }\n}\n"
},
{
"answer_id": 38232030,
"author": "Alex",
"author_id": 3936509,
"author_profile": "https://Stackoverflow.com/users/3936509",
"pm_score": 1,
"selected": false,
"text": "BOOL GetWin32FileName(const TCHAR* pszNativeFileName, TCHAR *pszWin32FileName)\n{\n BOOL bFound = FALSE;\n\n // Translate path with device name to drive letters.\n TCHAR szTemp[MAX_PATH];\n szTemp[0] = '\\0';\n\n if (GetLogicalDriveStrings(MAX_PATH - 1, szTemp))\n {\n TCHAR szName[MAX_PATH];\n TCHAR szDrive[3] = TEXT(\" :\");\n TCHAR* p = szTemp;\n\n do\n {\n // Copy the drive letter to the template string\n *szDrive = *p;\n\n // Look up each device name\n if (QueryDosDevice(szDrive, szName, MAX_PATH))\n {\n size_t uNameLen = _tcslen(szName);\n\n if (uNameLen < MAX_PATH)\n {\n bFound = _tcsnicmp(pszNativeFileName, szName, uNameLen) == 0\n && *(pszNativeFileName + uNameLen) == _T('\\\\');\n\n if (bFound)\n {\n // Replace device path with DOS path\n StringCchPrintf(pszWin32FileName,\n MAX_PATH,\n TEXT(\"%s%s\"),\n szDrive,\n pszNativeFileName + uNameLen);\n }\n }\n }\n // Go to the next NULL character.\n while (*p++);\n } while (!bFound && *p);\n }\n\n return(bFound);\n}\n"
},
{
"answer_id": 51372466,
"author": "VictorV",
"author_id": 6119813,
"author_profile": "https://Stackoverflow.com/users/6119813",
"pm_score": 1,
"selected": false,
"text": "int DeviceNameToVolumePathName(WCHAR *filepath) {\n WCHAR fileDevName[MAX_PATH];\n WCHAR devName[MAX_PATH];\n WCHAR fileName[MAX_PATH];\n HANDLE FindHandle = INVALID_HANDLE_VALUE;\n WCHAR VolumeName[MAX_PATH];\n DWORD Error = ERROR_SUCCESS;\n size_t Index = 0;\n DWORD CharCount = MAX_PATH + 1;\n\n int index = 0;\n // \\Device\\HarddiskVolume1\\windows,locate \\windows.\n for (int i = 0; i < lstrlenW(filepath); i++) {\n if (!memcmp(&filepath[i], L\"\\\\\", 2)) {\n index++;\n if (index == 3) {\n index = i;\n break;\n }\n }\n }\n filepath[index] = L'\\0';\n\n memcpy(fileDevName, filepath, (index + 1) * sizeof(WCHAR));\n\n FindHandle = FindFirstVolumeW(VolumeName, ARRAYSIZE(VolumeName));\n\n if (FindHandle == INVALID_HANDLE_VALUE)\n {\n Error = GetLastError();\n wprintf(L\"FindFirstVolumeW failed with error code %d\\n\", Error);\n return FALSE;\n }\n for (;;)\n {\n // Skip the \\\\?\\ prefix and remove the trailing backslash.\n Index = wcslen(VolumeName) - 1;\n\n if (VolumeName[0] != L'\\\\' ||\n VolumeName[1] != L'\\\\' ||\n VolumeName[2] != L'?' ||\n VolumeName[3] != L'\\\\' ||\n VolumeName[Index] != L'\\\\')\n {\n Error = ERROR_BAD_PATHNAME;\n wprintf(L\"FindFirstVolumeW/FindNextVolumeW returned a bad path: %s\\n\", VolumeName);\n break;\n }\n VolumeName[Index] = L'\\0';\n CharCount = QueryDosDeviceW(&VolumeName[4], devName, 100);\n if (CharCount == 0)\n {\n Error = GetLastError();\n wprintf(L\"QueryDosDeviceW failed with error code %d\\n\", Error);\n break;\n }\n if (!lstrcmpW(devName, filepath)) {\n VolumeName[Index] = L'\\\\';\n Error = GetVolumePathNamesForVolumeNameW(VolumeName, fileName, CharCount, &CharCount);\n if (!Error) {\n Error = GetLastError();\n wprintf(L\"GetVolumePathNamesForVolumeNameW failed with error code %d\\n\", Error);\n break;\n }\n\n // concat drive letter to path\n lstrcatW(fileName, &filepath[index + 1]);\n lstrcpyW(filepath, fileName);\n\n Error = ERROR_SUCCESS;\n break;\n }\n\n Error = FindNextVolumeW(FindHandle, VolumeName, ARRAYSIZE(VolumeName));\n\n if (!Error)\n {\n Error = GetLastError();\n\n if (Error != ERROR_NO_MORE_FILES)\n {\n wprintf(L\"FindNextVolumeW failed with error code %d\\n\", Error);\n break;\n }\n\n //\n // Finished iterating\n // through all the volumes.\n Error = ERROR_BAD_PATHNAME;\n break;\n }\n }\n\n FindVolumeClose(FindHandle);\n if (Error != ERROR_SUCCESS)\n return FALSE;\n return TRUE;\n\n}\n"
},
{
"answer_id": 59908355,
"author": "Alex P.",
"author_id": 964478,
"author_profile": "https://Stackoverflow.com/users/964478",
"pm_score": 0,
"selected": false,
"text": "std::map<std::wstring, std::wstring> GetDosPathDevicePathMap()\n{\n // It's not really related to MAX_PATH, but I guess it should be enough.\n // Though the docs say \"The first null-terminated string stored into the buffer is the current mapping for the device.\n // The other null-terminated strings represent undeleted prior mappings for the device.\"\n wchar_t devicePath[MAX_PATH] = { 0 };\n std::map<std::wstring, std::wstring> result;\n std::wstring dosPath = L\"A:\";\n\n for (wchar_t letter = L'A'; letter <= L'Z'; ++letter)\n {\n dosPath[0] = letter;\n if (QueryDosDeviceW(dosPath.c_str(), devicePath, MAX_PATH)) // may want to properly handle errors instead ... e.g. check ERROR_INSUFFICIENT_BUFFER\n {\n result[dosPath] = devicePath;\n }\n }\n return result;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
] |
127,137
|
<p>Does anyone know a good online resource for example of R code?</p>
<p>The programs do not have to be written for illustrative purposes, I am really just looking for some places where a bunch of R code has been written to give me a sense of the syntax and capabilities of the language?</p>
<p><strong>Edit:</strong> I have read the basic documentation on the main site, but was wondering if there was some code samples or even programs that show how R is used by different people.</p>
|
[
{
"answer_id": 574365,
"author": "Chang Chung",
"author_id": 69117,
"author_profile": "https://Stackoverflow.com/users/69117",
"pm_score": 3,
"selected": false,
"text": "r"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
127,144
|
<p>i was wondering how you deal with permalinks on international sites. By permalink i mean some link which is unique and human readable. </p>
<p>E.g. for english phrases its no problem e.g. <strong>/product/some-title/</strong></p>
<p>but what do you do if the product title is in e.g chinese language??
how do you deal with this problem? </p>
<p>i am implementing an international site and one requirement is to have human readable URLs.
Thanks for every comment</p>
|
[
{
"answer_id": 127295,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<DOMAIN>/<LANGUAGE>/DIR/<PRODUCT_TRANSLATED> http://www.example.com/en/products/cat/\nhttp://www.example.com/fr/products/chat/\n RewriteRule ^([a-z]+)/product/([a-z]+)? product_lookup.php?lang=$1&product=$2\n product_lookup.php?lang=en&product=cat lang en"
},
{
"answer_id": 128046,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "$ echo täst | iconv -t 'ascii//translit'\ntaest\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21672/"
] |
127,151
|
<p>This is an exercise for the CS guys to shine with the theory.</p>
<p>Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.</p>
<p>What is AN algorithm to calculate the added and the removed?</p>
<p><strong>Notice</strong>: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.</p>
<p><strong>Edit</strong>: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?</p>
|
[
{
"answer_id": 127207,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 1,
"selected": false,
"text": "sort left-list and right-list\nadds = {}\ndeletes = {}\nget first right-item from right-list\nget first left-item from left-list\nwhile (either list has items)\n if left-item < right-item or right-list is empty\n add left-item to deletes\n get new left-item from left-list\n else if left-item > right-item or left-list is empty\n add right-item to adds\n get new right-item from right-list\n else\n get new right-item from right-list\n get new left-item from left-list\n"
},
{
"answer_id": 127227,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 4,
"selected": true,
"text": "foreach( A ) { \n if( eleA NOT IN B ) {\n DELETED\n }\n}\nforeach( B ) {\n if( eleB NOT IN A ) {\n ADDED\n }\n}\n"
},
{
"answer_id": 127393,
"author": "Manrico Corazzi",
"author_id": 4690,
"author_profile": "https://Stackoverflow.com/users/4690",
"pm_score": 0,
"selected": false,
"text": "map1\nmap2\nremovedElements\naddedElements\n\nlist1.each |item|\n{\n map1.add(item)\n}\nlist2.each |item|\n{\n map2.add(item)\n}\nlist1.each |item|\n{\n removedElements.add(item) unless map2.contains?(item)\n}\nlist2.each |item|\n{\n addedElements.add(item) unless map1.contains?(item)\n}\n list1.each |item|\n{\n map1.add(item)\n}\nlist2.each |item|\n{\n map2.add(item)\n addedElements.add(item) unless map1.contains?(item)\n}\nlist1.each |item|\n{\n removedElements.add(item) unless map2.contains?(item)\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] |
127,156
|
<p>How do I check if an index exists on a table field in MySQL?</p>
<p>I've needed to Google this multiple times, so I'm sharing my Q/A.</p>
|
[
{
"answer_id": 127157,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 8,
"selected": true,
"text": "SHOW INDEX SHOW INDEX FROM [tablename]\n"
},
{
"answer_id": 127164,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 2,
"selected": false,
"text": "desc mytable\n show table mytable\n"
},
{
"answer_id": 9051521,
"author": "Stéphan Champagne",
"author_id": 1176140,
"author_profile": "https://Stackoverflow.com/users/1176140",
"pm_score": 5,
"selected": false,
"text": "SELECT * FROM information_schema.statistics \n WHERE table_schema = [DATABASE NAME] \n AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]\n"
},
{
"answer_id": 10470870,
"author": "pulock",
"author_id": 1378073,
"author_profile": "https://Stackoverflow.com/users/1378073",
"pm_score": 3,
"selected": false,
"text": "SHOW KEYS FROM tablename WHERE Key_name='unique key name'\n"
},
{
"answer_id": 29115111,
"author": "Somil",
"author_id": 4062929,
"author_profile": "https://Stackoverflow.com/users/4062929",
"pm_score": 3,
"selected": false,
"text": "show index from table_name where Column_name='column_name';\n"
},
{
"answer_id": 40512030,
"author": "kjdion84",
"author_id": 5645843,
"author_profile": "https://Stackoverflow.com/users/5645843",
"pm_score": -1,
"selected": false,
"text": "leads province $this->name = 'province';\n\n$stm = $this->db->prepare('show index from `leads`');\n$stm->execute();\n$res = $stm->fetchAll();\n$index_exists = false;\n\nforeach ($res as $r) {\n if ($r['Column_name'] == $this->name) {\n $index_exists = true;\n }\n}\n print_r $res"
},
{
"answer_id": 44821106,
"author": "Dian Yudha Negara",
"author_id": 8230575,
"author_profile": "https://Stackoverflow.com/users/8230575",
"pm_score": 0,
"selected": false,
"text": "select a.table_schema, a.table_name, a.column_name, index_name\nfrom information_schema.columns a\njoin information_schema.tables b on a.table_schema = b.table_schema and\n a.table_name = b.table_name and \n b.table_type = 'BASE TABLE'\nleft join (\n select concat(x.name, '/', y.name) full_path_schema, y.name index_name\n FROM information_schema.INNODB_SYS_TABLES as x\n JOIN information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID\n WHERE x.name = 'your_schema'\n and y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema\nwhere a.table_schema = 'your_schema'\nand a.column_name = 'your_column'\norder by a.table_schema, a.table_name;\n"
},
{
"answer_id": 48036809,
"author": "GK10",
"author_id": 5733987,
"author_profile": "https://Stackoverflow.com/users/5733987",
"pm_score": 3,
"selected": false,
"text": "SHOW INDEX FROM *your_table*\n row[\"Table\"] row[\"Key_name\"]"
},
{
"answer_id": 54515141,
"author": "Hubbe73",
"author_id": 5649667,
"author_profile": "https://Stackoverflow.com/users/5649667",
"pm_score": 0,
"selected": false,
"text": "AND SEQ_IN_INDEX = 1 DELIMITER $$\nCREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(\n `IN_SCHEMA` VARCHAR(255),\n `IN_TABLE` VARCHAR(255),\n `IN_COLUMN` VARCHAR(255)\n)\nRETURNS tinyint(4)\nLANGUAGE SQL\nDETERMINISTIC\nCONTAINS SQL\nSQL SECURITY DEFINER\nCOMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'\nBEGIN\n\n-- Check if index exists at first place in sequence for a given column in a given table in a given schema. \n-- Returns -1 if schema does not exist. \n-- Returns -2 if table does not exist. \n-- Returns -3 if column does not exist. \n-- If the index exists in first place it returns 1, otherwise 0.\n-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');\n\n-- check if schema exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.SCHEMATA\nWHERE \n SCHEMA_NAME = IN_SCHEMA\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -1;\nEND IF;\n\n\n-- check if table exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.TABLES\nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -2;\nEND IF;\n\n\n-- check if column exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.COLUMNS\nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE\nAND COLUMN_NAME = IN_COLUMN\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -3;\nEND IF;\n\n-- check if index exists at first place in sequence\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n information_schema.statistics \nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN\nAND SEQ_IN_INDEX = 1;\n\n\nIF @COUNT_EXISTS > 0 THEN\n RETURN 1;\nELSE\n RETURN 0;\nEND IF;\n\n\nEND$$\nDELIMITER ;\n"
},
{
"answer_id": 61768732,
"author": "De Paradox",
"author_id": 10337783,
"author_profile": "https://Stackoverflow.com/users/10337783",
"pm_score": 0,
"selected": false,
"text": "SELECT TRUE\nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE \nWHERE TABLE_SCHEMA = \"{DB_NAME}\" \nAND TABLE_NAME = \"{DB_TABLE}\"\nAND COLUMN_NAME = \"{DB_INDEXED_FIELD}\";\n"
},
{
"answer_id": 66501780,
"author": "napierjohn",
"author_id": 6104690,
"author_profile": "https://Stackoverflow.com/users/6104690",
"pm_score": 1,
"selected": false,
"text": "$mysqli = mysqli_connect(\"localhost\", \"my_user\", \"my_password\", \"world\");\n\n$sql = \"SHOW INDEX FROM 'mydatabase.mytable' WHERE Key_name = 'PRIMARY';\" ;\n$result = mysqli_query($mysqli, $sql);\n\nwhile ($row = $result->fetch_assoc()) {\n echo $rowVerbatimsSet[\"Column_name\"];\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446/"
] |
127,188
|
<p>Can you explain STA and MTA in your own words?</p>
<p>Also, what are apartment threads and do they pertain only to COM? If so, why?</p>
|
[
{
"answer_id": 127340,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 8,
"selected": false,
"text": "ThreadingModel ThreadingModel Apartment Free Free Both [STAThread] Apartment"
},
{
"answer_id": 68271080,
"author": "Pekka Ylönen",
"author_id": 16391556,
"author_profile": "https://Stackoverflow.com/users/16391556",
"pm_score": 0,
"selected": false,
"text": " IStorage_vtbl** reference; // you got it by some means of factory\n \n \n public unsafe int OpenStorage(char* pwcsName, IStorage pstgPriority, uint grfMode, char** snbExclude, uint reserved, IStorage* ppstg)\n {\n IStorage_vtbl** @this = (IStorage_vtbl**)reference;\n IStorage_vtbl* vtbl = *@this;\n if (vtbl == null)\n throw new InvalidComObjectException();\n Delegate genericDelegate = Marshal.GetDelegateForFunctionPointer(vtbl->method_6, typeof(delegate_6));\n delegate_6 method = (delegate_6)genericDelegate;\n return method(@this, pwcsName, pstgPriority, grfMode, snbExclude, reserved, ppstg);\n }\n \n"
},
{
"answer_id": 71317474,
"author": "lfree",
"author_id": 2407681,
"author_profile": "https://Stackoverflow.com/users/2407681",
"pm_score": 2,
"selected": false,
"text": "CoInitialize CoInitializeEx"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19490/"
] |
127,190
|
<p>I'm learning Haskell in the hope that it will help me get closer to functional programming. Previously, I've mostly used languages with C-like syntax, like C, Java, and D.</p>
<p>I have a little question about the coding style of an <code>if</code>/<code>else</code> control block used by the <a href="http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output" rel="nofollow noreferrer">tutorial on Wikibooks</a>. The code looks like the following:</p>
<pre><code>doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num
then do putStrLn "Too low!"
doGuessing num
else if (read guess) > num
then do putStrLn "Too high!"
doGuessing num
else do putStrLn "You Win!"
</code></pre>
<p>It makes me confused, because this coding style totally violates the recommended style in C-like languages, where we should indent <code>if</code>, <code>else if</code>, and <code>else</code> at the same column.</p>
<p>I know it just does not work in Haskell, because it would be a parse error if I indented <code>else</code> at the same column as <code>if</code>.</p>
<p>But what about the following style? I think it is much more clear than the above one. But since the above is used by Wikibooks and Yet Another Haskell Tutorial, which is marked "best tutorial available online" at the official Haskell website, I'm not sure whether this coding style is a convention in Haskell programs.</p>
<pre><code>doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num then
do
putStrLn "Too low!"
doGuessing num
else if (read guess) > num then do
putStrLn "Too high!"
doGuessing num
else do
putStrLn "You Win!"
</code></pre>
<p>So, I'm curious about which coding style is used more often—or is there another coding style for this piece of code?</p>
|
[
{
"answer_id": 130220,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": 3,
"selected": false,
"text": "doGuessing num = do\n putStrLn \"Enter your guess:\"\n guess <- getLine\n case (read guess) of\n g | g < num -> do \n putStrLn \"Too low!\"\n doGuessing num\n g | g > num -> do \n putStrLn \"Too high!\"\n doGuessing num\n otherwise -> do \n putStrLn \"You Win!\"\n"
},
{
"answer_id": 147239,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 3,
"selected": false,
"text": "doGuessing num = do\n putStrLn \"Enter your guess:\"\n guess <- getLine\n case (read guess) `compare` num of\n LT -> do putStrLn \"Too low!\"\n doGuessing num\n GT -> do putStrLn \"Too high!\"\n doGuessing num\n EQ -> putStrLn \"You Win!\"\n"
},
{
"answer_id": 2096144,
"author": "Greg Bacon",
"author_id": 123109,
"author_profile": "https://Stackoverflow.com/users/123109",
"pm_score": 6,
"selected": true,
"text": "main = untilM (isCorrect 42) (read `liftM` getLine)\n getLine read untilM :: Monad m => (a -> m Bool) -> m a -> m ()\nuntilM p a = do\n x <- a\n done <- p x\n if done\n then return ()\n else untilM p a\n main isCorrect :: Int -> Int -> IO Bool\nisCorrect num guess =\n case compare num guess of\n EQ -> putStrLn \"You Win!\" >> return True\n LT -> putStrLn \"Too high!\" >> return False\n GT -> putStrLn \"Too low!\" >> return False\n read `liftM` getLine\n getLine IO String read String liftM read Int readLine String liftM read IO"
},
{
"answer_id": 2097719,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "if ... then ... else do then else if DoAndIfThenElse DoAndIfThenElse"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242644/"
] |
127,205
|
<p>I have a constructor like as follows:</p>
<pre><code>public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
</code></pre>
<p>I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?</p>
|
[
{
"answer_id": 127219,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "this this"
},
{
"answer_id": 127245,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "setTopWorldAgent this this"
},
{
"answer_id": 127247,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 1,
"selected": false,
"text": "public class Test {\n public Test() {\n this.hi(this);\n }\n public void hi(Test t) {\n System.out.println(t);\n }\n\n public static void main(String[] args) throws Exception {\n Test t = new Test();\n }\n}\n"
},
{
"answer_id": 127262,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "\nAgent agent = new Agent(\"John\", 9);\nagent.setTopWorldAgent(agent, \"Top_World_Agent\", true);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
127,233
|
<p>This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.</p>
|
[
{
"answer_id": 127254,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "foreach IEnumerable GetEnumerator MoveNext Current class EnumerableWrapper {\n private readonly TheObjectType obj;\n\n public EnumerableWrapper(TheObjectType obj) {\n this.obj = obj;\n }\n\n public IEnumerator<YourType> GetEnumerator() {\n return obj.TheMethodReturningTheIEnumerator();\n }\n}\n\n// Called like this:\n\nforeach (var xyz in new EnumerableWrapper(yourObj))\n …;\n IEnumerator foreach (var yz in yourObj.MethodA())\n …;\n"
},
{
"answer_id": 127260,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 0,
"selected": false,
"text": "\nclass EnumerableAdapter\n{\n ExternalSillyClass _target;\n\n public EnumerableAdapter(ExternalSillyClass target)\n {\n _target = target;\n }\n\n public IEnumerable GetEnumerator(){ return _target.SomeMethodThatGivesAnEnumerator(); }\n\n}\n"
},
{
"answer_id": 127291,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "foreach (object y in X.A())\n{\n //...\n}\n\n// or\n\nforeach (object y in X.B())\n{\n //...\n}\n"
},
{
"answer_id": 127294,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 2,
"selected": false,
"text": "class Counter\n{\n public IEnumerable<int> Count(int max)\n {\n int i = 0;\n while (i <= max)\n {\n yield return i;\n i++;\n }\n yield break;\n }\n}\n Counter cnt = new Counter();\n\nforeach (var i in cnt.Count(6))\n{\n Console.WriteLine(i);\n}\n"
},
{
"answer_id": 127297,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 3,
"selected": false,
"text": "foreach (type identifier in expression) statement\n"
},
{
"answer_id": 127306,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 3,
"selected": false,
"text": "\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace ConsoleApplication3\n{\n class FakeIterator\n {\n int _count;\n\n public FakeIterator(int count)\n {\n _count = count;\n }\n public string Current { get { return \"Hello World!\"; } }\n public bool MoveNext()\n {\n if(_count-- > 0)\n return true;\n return false;\n }\n }\n\n class FakeCollection\n {\n public FakeIterator GetEnumerator() { return new FakeIterator(3); }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n foreach (string value in new FakeCollection())\n Console.WriteLine(value);\n }\n }\n}\n"
},
{
"answer_id": 127314,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "class ForeachWrapper\n{\n private IEnumerator _enumerator;\n\n public ForeachWrapper(Func<IEnumerator> enumerator)\n {\n _enumerator = enumerator;\n }\n\n public IEnumerator GetEnumerator()\n {\n return _enumerator();\n }\n}\n foreach (var element in new ForeachWrapper(x => myClass.MyEnumerator()))\n{\n ...\n}\n"
},
{
"answer_id": 136051,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 0,
"selected": false,
"text": "public class Foo\n{\n private int[] _someInts = { 1, 2, 3, 4, 5, 6 };\n public IEnumerator GetEnumerator()\n {\n foreach (var item in _someInts)\n {\n yield return item;\n }\n }\n}\n public IEnumerator GetEnumerator()\n {\n return _someInts.GetEnumerator();\n }\n foreach (int item in new Foo())\n {\n Console.Write(\"{0,2}\",item);\n }\n"
},
{
"answer_id": 20308550,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 0,
"selected": false,
"text": "GetEnumerator MoveNext Current class Test\n{\n public SomethingEnumerator GetEnumerator()\n {\n\n }\n}\n\nclass SomethingEnumerator\n{\n public Something Current //could return anything\n {\n get { }\n }\n\n public bool MoveNext()\n {\n\n }\n}\n\n//now you can call\nforeach (Something thing in new Test()) //type safe\n{\n\n}\n var enumerator = new Test().GetEnumerator();\ntry {\n Something element; //pre C# 5\n while (enumerator.MoveNext()) {\n Something element; //post C# 5\n element = (Something)enumerator.Current; //the cast!\n statement;\n }\n}\nfinally {\n IDisposable disposable = enumerator as System.IDisposable;\n if (disposable != null) disposable.Dispose();\n}\n public GetEnumerator foreach class Test : IEnumerable<int>\n{\n public SomethingEnumerator GetEnumerator()\n {\n //this one is called\n }\n\n IEnumerator<int> IEnumerable<int>.GetEnumerator()\n {\n\n }\n}\n IEnumerator<T> IEnumerator"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
127,241
|
<p>We are developing a .NET 2.0 winform application. The application needs to access <a href="http://ws.lokad.com/" rel="nofollow noreferrer">Web Services</a>. Yet, we are encountering issues with users behind proxies.</p>
<p>Popular windows backup applications (think <a href="http://mozy.com/" rel="nofollow noreferrer">Mozy</a>) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me.</p>
<p>What are best ways to deal with proxy with .NET client apps?</p>
<p>More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the <em>default proxy behavior</em> of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy.</p>
<p>What should we do to enforce that the user is not prompted for his username and password when launching IE?</p>
|
[
{
"answer_id": 127338,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 4,
"selected": true,
"text": "<configuration>\n <system.net>\n <defaultProxy>\n <proxy autoDetect=\"true\" />\n </defaultProxy>\n </system.net>\n</configuration>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
] |
127,258
|
<p>Greetings!</p>
<p>I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:</p>
<pre><code><Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc" attrib2="222" attrib3="false" />
<Item attrib1="ddd" attrib2="333" attrib3="true" />
</GroupB>
<GroupC>
<Item attrib1="eee" attrib2="444" attrib3="true" />
<Item attrib1="fff" attrib2="555" attrib3="true" />
</GroupC>
</Root>
</code></pre>
<p>I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:</p>
<pre><code>var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
select new
{
attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,
attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
};
</code></pre>
<p>The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?</p>
|
[
{
"answer_id": 127301,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "var results = from group in l_theDoc.Root.Elements(groupName)\n select new\n {\n items = from i in group.Elements(\"Item\")\n select new \n {\n attrib1_val = i.Attribute(\"attrib1\").Value,\n attrib2_val = i.Attribute(\"attrib2\").Value\n }\n };\n"
},
{
"answer_id": 127317,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "XElement e = XElement.Parse(testStr);\n\nstring groupName = \"GroupB\";\nvar items = from g in e.Elements(groupName)\n from i in g.Elements(\"Item\")\n select new {\n attr1 = (string)i.Attribute(\"attrib1\"),\n attr2 = (string)i.Attribute(\"attrib2\")\n };\n\nforeach (var item in items)\n{\n Console.WriteLine(item.attr1 + \":\" + item.attr2);\n}\n"
},
{
"answer_id": 127357,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 0,
"selected": false,
"text": "var groupName = \"GroupB\";\nvar results = from theitem in doc.Descendants(\"Item\")\n where theitem.Parent.Name == groupName\n select new \n { \n attrib1_val = theitem.Attribute(\"attrib1\").Value,\n attrib2_val = theitem.Attribute(\"attrib2\").Value, \n };\n"
},
{
"answer_id": 127445,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "var items = \n e.Elements(\"GroupB\")\n .SelectMany(g => g.Elements(\"Item\"))\n .Select(i => new {\n attr1 = i.Attribute(\"attrib1\").Value,\n attr2 = i.Attribute(\"attrib2\").Value,\n attr3 = i.Attribute(\"attrib3\").Value\n } )\n .ToList()\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
127,283
|
<p>I'm having an annoying problem registering a javascript event from inside a user control within a formview in an Async panel. I go to my formview, and press a button to switch into insert mode. This doesn't do a full page postback. Within insert mode, my user control's page_load event should then register a javascript event using ScriptManager.RegisterStartupScript:</p>
<pre><code>ScriptManager.RegisterStartupScript(base.Page, this.GetType(), ("dialogJavascript" + this.ID), "alert(\"Registered\");", true);
</code></pre>
<p>However when I look at my HTML source, the event isn't there. Hence the alert box is never shown. This is the setup of my actual aspx file:</p>
<pre><code><igmisc:WebAsyncRefreshPanel ID="WebAsyncRefreshPanel1" runat="server">
<asp:FormView ID="FormView1" runat="server" DataSourceID="odsCurrentIncident">
<EditItemTemplate>
<uc1:SearchSEDUsers ID="SearchSEDUsers1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
Hello
<asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Button" />
</ItemTemplate>
</asp:FormView>
</igmisc:WebAsyncRefreshPanel>
</code></pre>
<p>Does anyone have any idea what I might be missing here?</p>
|
[
{
"answer_id": 1482753,
"author": "Christian",
"author_id": 179649,
"author_profile": "https://Stackoverflow.com/users/179649",
"pm_score": 0,
"selected": false,
"text": "ScriptManager.RegisterClientScriptBlock(MyBase.Page, Me.[GetType](),\n (\"dialogJavascript\" + this.ID), \"alert(\\\"Registered\\\");\", True)\n"
},
{
"answer_id": 13238328,
"author": "Amrik",
"author_id": 1783751,
"author_profile": "https://Stackoverflow.com/users/1783751",
"pm_score": 1,
"selected": false,
"text": "resizeChartMid() ScriptManager.RegisterStartupScript(this, typeof(string), \"getchart48\", \"resizeChartMid();\", true);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17885/"
] |
127,290
|
<p>Is there a side effect in doing this:</p>
<p>C code:</p>
<pre><code>struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
</code></pre>
<p>C++ code:</p>
<pre><code>class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
</code></pre>
<p>There's an <code>extern "C"</code> around the C++ code and each code is inside its own compilation unit.</p>
<p>Is this portable across compilers?</p>
|
[
{
"answer_id": 127312,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "foo* x = new bar();\ndelete x;\n new"
},
{
"answer_id": 127358,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 1,
"selected": false,
"text": "class Bar\n{\nprivate:\n Foo mFoo;\n};\n"
},
{
"answer_id": 127458,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 0,
"selected": false,
"text": "class bar {\npublic: \n int my_bar() { \n return ret_foo( foo_ ); \n }\n\n // \n // This allows a 'bar' to be used where a 'foo' is expected\n inline operator foo& () {\n return foo_;\n }\n\nprivate: \n foo foo_;\n};\n"
},
{
"answer_id": 127468,
"author": "Roman Odaisky",
"author_id": 21055,
"author_profile": "https://Stackoverflow.com/users/21055",
"pm_score": 2,
"selected": false,
"text": "extern \"C\""
},
{
"answer_id": 127531,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 2,
"selected": false,
"text": "struct POINT { int x, y; }\nclass CPoint : POINT\n{\npublic:\n CPoint( int x_, int y_ ) { x = x_; y = y_; }\n\n const CPoint& operator+=( const POINT& op2 )\n { x += op2.x; y += op2.y; return *this; }\n\n // etc.\n};\n"
},
{
"answer_id": 127965,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 2,
"selected": false,
"text": "foo *pFoo = new bar;\ndelete pFoo;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21648/"
] |
127,316
|
<p>I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server."</p>
<p>Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error. Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more. Please help.</p>
<pre><code>Response.Clear();
base.Response.Buffer = true;
base.Response.ContentType = "application/vnd.ms-excel";
base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls");
base.Response.Charset = "";
this.EnableViewState = false;
StringWriter writer = new StringWriter();
HtmlTextWriter writer2 = new HtmlTextWriter(writer);
this.lblExport.RenderControl(writer2);
base.Response.Write(writer.ToString());
</code></pre>
|
[
{
"answer_id": 127334,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 2,
"selected": true,
"text": "public override void VerifyRenderingInServerForm(Control control)\n {\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
127,318
|
<p>I want to programmatically edit file content using windows command line (<a href="http://en.wikipedia.org/wiki/Windows_command_line" rel="noreferrer">cmd.exe</a>). In *nix there is <a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a> for this tasks. Is there any useful native equivalent in windows?</p>
|
[
{
"answer_id": 127567,
"author": "b w",
"author_id": 4126,
"author_profile": "https://Stackoverflow.com/users/4126",
"pm_score": 7,
"selected": false,
"text": "sed sed grep -z cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ < inpfile.txt > outfile.txt\n sed Dim pat, patparts, rxp, inp\npat = WScript.Arguments(0)\npatparts = Split(pat,\"/\")\nSet rxp = new RegExp\nrxp.Global = True\nrxp.Multiline = False\nrxp.Pattern = patparts(1)\nDo While Not WScript.StdIn.AtEndOfStream\n inp = WScript.StdIn.ReadLine()\n WScript.Echo rxp.Replace(inp, patparts(2))\nLoop\n"
},
{
"answer_id": 5728961,
"author": "Rober",
"author_id": 339460,
"author_profile": "https://Stackoverflow.com/users/339460",
"pm_score": 4,
"selected": false,
"text": "Const ForReading = 1\nConst ForWriting = 2\n\nstrFileName = Wscript.Arguments(0)\nstrOldText = Wscript.Arguments(1)\nstrNewText = Wscript.Arguments(2)\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(strFileName, ForReading)\n\nstrText = objFile.ReadAll\nobjFile.Close\nstrNewText = Replace(strText, strOldText, strNewText)\n\nSet objFile = objFSO.OpenTextFile(strFileName, ForWriting)\nobjFile.Write strNewText\nobjFile.Close\n cscript replace.vbs \"C:\\One.txt\" \"Robert\" \"Rob\"\n"
},
{
"answer_id": 6028937,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 8,
"selected": true,
"text": "grep get-content somefile.txt | where { $_ -match \"expression\"}\n select-string somefile.txt -pattern \"expression\"\n sed get-content somefile.txt | %{$_ -replace \"expression\",\"replace\"}\n"
},
{
"answer_id": 19789163,
"author": "krogon",
"author_id": 2956243,
"author_profile": "https://Stackoverflow.com/users/2956243",
"pm_score": 4,
"selected": false,
"text": "> (Get-content file.txt) | Foreach-Object {$_ -replace \"^SourceRegexp$\", \"DestinationString\"} | Set-Content file.txt\n sed -i 's/^SourceRegexp$/DestinationString/g' file.txt\n"
},
{
"answer_id": 19789668,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 3,
"selected": false,
"text": "repl.bat doesn't require any additional download Jscript swift doesn't suffer from the usual poison characters repl findrepl.bat GREP Jscript findrepl"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] |
127,328
|
<p>I have a class that defines the names of various constants, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP <strong>without</strong> using Scriptlet code such as:</p>
<pre><code><%@ page import="com.example.Constants" %>
<%= Constants.ATTR_CURRENT_USER %>
</code></pre>
<p>There appears to be a tag in the Apache <a href="http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants" rel="noreferrer">unstandard</a> taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?</p>
<p>Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 127442,
"author": "ncgz",
"author_id": 12905,
"author_profile": "https://Stackoverflow.com/users/12905",
"pm_score": 2,
"selected": false,
"text": "servletContext.setAttribute(\"Constants\", com.example.Constants);\n <c:out value=\"${Constants.ATTR_CURRENT_USER}\"/>\n"
},
{
"answer_id": 128234,
"author": "paulgreg",
"author_id": 3122,
"author_profile": "https://Stackoverflow.com/users/3122",
"pm_score": 0,
"selected": false,
"text": " <dependency>\n <groupId>jakarta</groupId>\n <artifactId>jakarta-taglibs-unstandard</artifactId>\n <version>20060829</version>\n </dependency>\n"
},
{
"answer_id": 11512425,
"author": "Roger Keays",
"author_id": 1104885,
"author_profile": "https://Stackoverflow.com/users/1104885",
"pm_score": 1,
"selected": false,
"text": "public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n ${bean.manager_role}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
127,336
|
<p>Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named <em>"Outlook Rules Organizer"</em> with a message class <code>IPM.RuleOrganizer</code>. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard.</p>
<p>Has anyone deciphered the layout of this binary blob?</p>
|
[
{
"answer_id": 127442,
"author": "ncgz",
"author_id": 12905,
"author_profile": "https://Stackoverflow.com/users/12905",
"pm_score": 2,
"selected": false,
"text": "servletContext.setAttribute(\"Constants\", com.example.Constants);\n <c:out value=\"${Constants.ATTR_CURRENT_USER}\"/>\n"
},
{
"answer_id": 128234,
"author": "paulgreg",
"author_id": 3122,
"author_profile": "https://Stackoverflow.com/users/3122",
"pm_score": 0,
"selected": false,
"text": " <dependency>\n <groupId>jakarta</groupId>\n <artifactId>jakarta-taglibs-unstandard</artifactId>\n <version>20060829</version>\n </dependency>\n"
},
{
"answer_id": 11512425,
"author": "Roger Keays",
"author_id": 1104885,
"author_profile": "https://Stackoverflow.com/users/1104885",
"pm_score": 1,
"selected": false,
"text": "public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n ${bean.manager_role}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21685/"
] |
127,363
|
<p>I need to create S/MIME messages using C# (as specified in RFC 2633, "S/MIME Version 3 message specification", and RFC 3335).
The only S/MIME library I can find is a commercial library (<a href="http://www.example-code.com/csharp/smime.asp" rel="noreferrer">http://www.example-code.com/csharp/smime.asp</a>), which is no good for us.</p>
<p>Are there any existing libraries to accomplish creating S/MIME messages, and in particular, .p7s files?</p>
<p>I have all the encrypted and signed elements that need to go into this file, but I'd like to create the .p7s file without handrolling my own library with the aid of the RFC document...</p>
<hr>
<p>EDIT:
I've found another <a href="http://www.eldos.com/sbb/desc-mime.php" rel="noreferrer">commercial S/MIME library</a>, which is still no good for our requirements.
It's looking more and more like I'm going to have to hand roll a S/MIME library, which is sad.
Is everyone in .net who needs S/MIME using commercial, closed source libraries to do it?</p>
|
[
{
"answer_id": 18392068,
"author": "Bert Johnson",
"author_id": 2709133,
"author_profile": "https://Stackoverflow.com/users/2709133",
"pm_score": 2,
"selected": false,
"text": "// Instantiate a new SMTP connection to Gmail using TLS/SSL protection.\nSmtpClient smtpClient = new SmtpClient(\"smtp.gmail.com\", 587);\nsmtpClient.Credentials = new NetworkCredential(\"username@gmail.com\", \"Pass@word1\");\nsmtpClient.EnableSsl = true;\n\n// Create a new MailMessage class with lorem ipsum.\nMailMessage message = new MailMessage(\"username@gmail.com\", \"user@example.com\", \"Example subject\", \"Lorem ipsum body.\");\n\n// Specify that the message should be signed, have its envelope encrypted, and then be signed again (triple-wrapped).\nmessage.SmimeSigned = true;\nmessage.SmimeEncryptedEnvelope = true;\nmessage.SmimeTripleWrapped = true;\n\n// Specify that the message should be timestamped.\nmessage.SmimeSigningOptionFlags = SmimeSigningOptionFlags.SignTime;\n\n// Load the signing certificate from the Local Machine store. \nmessage.SmimeSigningCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, \"username@gmail.com\");\n\n// Send the message.\nawait smtpClient.SendAsync(message);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21002/"
] |
127,386
|
<p>In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.</p>
<p>From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong).</p>
<p>Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.</p>
<p>Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?</p>
|
[
{
"answer_id": 48255562,
"author": "Glenn Slayden",
"author_id": 147511,
"author_profile": "https://Stackoverflow.com/users/147511",
"pm_score": 3,
"selected": false,
"text": "0xCC 0xCD 0xCC INT 0xCD 0xCC INT 3 INT 3 INT 0xCD 0xCD 0x03 INT 3 0xCC 0xCDCDCDCD CD CD CD CC CD CC INT 3 INT 204 CC CD CC CD"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7234/"
] |
127,389
|
<p>Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:</p>
<pre><code><test>
<route>citytest/:city</route>
<defaults>
<controller>result</controller>
<action>test</action>
</defaults>
<reqs>
<city>.+</city>
</reqs>
</test>
</code></pre>
<p>and three Urls:</p>
<ul>
<li>mysite.local/citytest/Berlin</li>
<li>mysite.local/citytest/Hamburg</li>
<li>mysite.local/citytest/M%FCnchen </li>
</ul>
<p>the last Url does not match and thus the correct controller is not called. Anybody got a clue why?</p>
<p>Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ )</p>
<p>Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great.</p>
<p>Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170):</p>
<pre><code>$regex = $this->_regexDelimiter . '^' .
$part['regex'] . '$' .
$this->_regexDelimiter . 'iu';
</code></pre>
<p>If I change that to </p>
<pre><code> $this->_regexDelimiter . 'i';
</code></pre>
<p>it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading.</p>
|
[
{
"answer_id": 127818,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 1,
"selected": false,
"text": "ü mysite.local/citytest/M%C3%BCnchen"
},
{
"answer_id": 144192,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": true,
"text": "function createUrlFriendlyName($name) // $name must be an UTF-8 encoded string\n{\n $name=mb_convert_encoding(trim($name), 'HTML-ENTITIES', 'UTF-8');\n $name=preg_replace(\n array('/ß/', '/&(..)lig;/', '/&([aouAOU])uml;/', '/&(.)[^;]*;/', '/\\W/'),\n array('ss', '$1', '$1e', '$1', '-'),\n $name);\n $name=preg_replace('/-{2,}/', '-', $name);\n return trim($name, '-');\n}\n"
},
{
"answer_id": 6452338,
"author": "Imran Munawar Khan",
"author_id": 811977,
"author_profile": "https://Stackoverflow.com/users/811977",
"pm_score": 2,
"selected": false,
"text": "/^[\\p{L}-. ]*$/u\n ^ [ ... ]* \\p{L} – . $ /u $str= ‘Füße’;\nif (!preg_match(“/^[\\p{L}-. ]*$/u”, $str))\n{\n echo ‘error’;\n}\nelse\n{\n echo “success”;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18606/"
] |
127,391
|
<p>I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.</p>
<p>If a person has a define such as:</p>
<pre><code>#define count 1
</code></pre>
<p>Can that person find the variable name <code>count</code> using the 1 that is inside it?</p>
<p>I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.</p>
|
[
{
"answer_id": 127402,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 0,
"selected": false,
"text": "#define count 1\n if (x > count) ...\n if (x > 1) ...\n"
},
{
"answer_id": 127407,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "#define"
},
{
"answer_id": 127429,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 0,
"selected": false,
"text": "int count = 1;\nint count2 = 1;\n"
},
{
"answer_id": 127430,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 3,
"selected": false,
"text": "#define COUNT (1)\n...\nint myVar = COUNT;\n...\n ...\nint myVar = (1);\n...\n"
},
{
"answer_id": 127437,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 2,
"selected": false,
"text": "#define count 1 count"
},
{
"answer_id": 127449,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 0,
"selected": false,
"text": "int i = count;\n #define count 1\n"
},
{
"answer_id": 127512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#define displayInt(val) printf(\"%s: %d\\n\",#val,val)\n#define displayFloat(val) printf(\"%s: %d\\n\",#val,val)\n#define displayString(val) printf(\"%s: %s\\n\",#val,val)\n\nint main(){\n int foo=123;\n float bar=456.789;\n char thud[]=\"this is a string\";\n\n displayInt(foo);\n displayFloat(bar);\n displayString(thud);\n\n return 0;\n}\n foo: 123\nbar: 456.789\nthud: this is a string\n"
},
{
"answer_id": 127517,
"author": "Trent",
"author_id": 9083,
"author_profile": "https://Stackoverflow.com/users/9083",
"pm_score": 0,
"selected": false,
"text": "#define ZERO 0\n#define ONE 1\n#define TWO 2\n enum {\n ZERO,\n ONE,\n TWO\n};\n x = TWO;\n"
},
{
"answer_id": 127547,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 1,
"selected": false,
"text": "count #define SHOW(sym) (printf(#sym \" = %d\\n\", sym))\n#define count 1\n\nSHOW(count); // prints \"count = 1\"\n #"
},
{
"answer_id": 127597,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "#define count 1 count void copyString(char* dst, const char* src, size_t count) {\n ...\n}\n count 1 void copyString(char* dst, const char* src, size_t 1) {\n ...\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354/"
] |
127,395
|
<p>Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.</p>
<p>Over simplified example:</p>
<pre><code> public class Name
{
public string FirstName {get; set;}
public string Surname { get; set; }
public override string ToString()
{
return string.Concat(FirstName, " ", Surname);
}
}
</code></pre>
<p>I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.</p>
|
[
{
"answer_id": 127910,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "public struct Whatever\n{\n public string A;\n public int B;\n}\n [WebMethod]\npublic Whatever GiveMeWhatever()\n{\n Whatever what = new Whatever();\n what.A = \"A\";\n what.B = 42;\n return what;\n}\n Webreference.Whatever what = new Webreference.Whatever();\nwhat.A = \"that works?\";\nwhat.B = -1; // FILENOTFOUND\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9539/"
] |
127,411
|
<p>Is there a project that maintains annotations for patterns?</p>
<p><p>For example, when I write a builder, I want to mark it with <code>@Builder</code>.</p>
<p><p>Annotating in this way immediately provides a clear idea of what the code implements. Also, the Javadoc of the <code>@Builder</code> annotation can reference explanations of the builder pattern. Furthermore, navigating from the Javadoc of a builder implementation to <code>@Builder</code> Javadoc is made easy by annotating <code>@Builder</code> with <code>@Documented</code>.</p>
<p><p>I've being slowing accumulating a small set of such annotations for patterns and idioms that I have in my code, but I'd like to leverage a more complete existing project if it exists. If there is no such project, maybe I can share what I have by spinning it off to a separate pattern/idiom annotation project.</p>
<p><p>Update: I've created the <a href="http://code.google.com/p/patternnotes" rel="noreferrer">Pattern Notes project</a> in response to this discussion. Contributions welcome! Here is <a href="http://code.google.com/p/patternnotes/source/browse/trunk/trunk/src/com/iparelan/annotations/patterns/Builder.java" rel="noreferrer"><code>@Builder</code></a></p>
|
[
{
"answer_id": 1543918,
"author": "elhoim",
"author_id": 171469,
"author_profile": "https://Stackoverflow.com/users/171469",
"pm_score": 2,
"selected": false,
"text": "Serializable"
},
{
"answer_id": 1843217,
"author": "Martin Harris",
"author_id": 224306,
"author_profile": "https://Stackoverflow.com/users/224306",
"pm_score": 2,
"selected": false,
"text": "@Builder(\"buildMethodName\")\nClass Thing {\n String thingName;\n String thingDescr;\n}\n Thing thing =\n new Thing.Builder().setThingName(\"X\").setThingDescr(\"x\").buildMethodName();\n"
},
{
"answer_id": 3350427,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@AdapterPattern\npublic class EnumerationIteratorAdapter<T> implements Enumeration<T> {\n ...\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13940/"
] |
127,412
|
<p>Is there a indexing plugin for GDS that allows for source code search? I see some for specific types (Java, C++, ...) and one for "any text". These are nice, but I would like one that allows for many/configurable extensions (HTML, CSS, JS, VB, C#, Java, Python, ...). A huge bonus would be to allow for syntax highlighting (<a href="http://pygments.org/" rel="noreferrer">http://pygments.org/</a>) in the cache.</p>
|
[
{
"answer_id": 2416289,
"author": "HaveAGuess",
"author_id": 57344,
"author_profile": "https://Stackoverflow.com/users/57344",
"pm_score": 0,
"selected": false,
"text": "<YOUR SEARCH> filetype:java under:\"C:\\hft\\trunk\"\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4231/"
] |
127,413
|
<p>I have user control named DateTimeUC which has two textboxes on its markup:</p>
<pre><code><asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox>
<asp:TextBox ID="timeTextBox" runat="server"></asp:TextBox>
</code></pre>
<p>I am dynamically creating this control in another user control:</p>
<pre><code>Controls.Add(GenerateDateTime(parameter));
private DateTimeUC GenerateDateTime(SomeParameter parameter)
{
DateTimeUC uc = new DateTimeUC();
uc.ID = parameter.Name;
return uc;
}
</code></pre>
<p>But when I render the page, DateTimeUC renders nothing. I checked it like this:</p>
<pre><code>protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
StringBuilder builder = new StringBuilder();
StringWriter swriter = new StringWriter(builder);
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
base.Render(hwriter);
string s = builder.ToString();
}
</code></pre>
<p>s is empty and Controls.Count is 0. What am I doing wrong?</p>
|
[
{
"answer_id": 127438,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 4,
"selected": true,
"text": "LoadControl( \"your_user_control_app_relative_path.ascx\" )"
},
{
"answer_id": 127499,
"author": "Briggie Smalls",
"author_id": 9559,
"author_profile": "https://Stackoverflow.com/users/9559",
"pm_score": 0,
"selected": false,
"text": "Controls.Add( GenerateDateTime(parameter) );\n Page.Form.Controls.Add( GenerateDateTime(parameter) );\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
127,426
|
<p>I have defined an interface in C++, i.e. a class containing only pure virtual functions.</p>
<p>I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:</p>
<pre><code>class ITest{
public:
virtual void doSomething() = 0;
protected:
~ITest(){}
};
void someFunction(ITest * test){
test->doSomething(); // ok
// deleting object is not allowed
// delete test;
}
</code></pre>
<p>The GNU compiler gives me a warning saying:</p>
<blockquote>
<p>class 'ITest' has virtual functions but non-virtual destructor</p>
</blockquote>
<p>Once the destructor is protected, what is the difference in having it virtual or non-virtual?</p>
<p>Do you think this warning can be safely ignored or silenced?</p>
|
[
{
"answer_id": 127486,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "ITest delete"
},
{
"answer_id": 127557,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "-Wno-non-virtual-dtor -Wall -Weffc++"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
] |
127,459
|
<p>I need to be able to change the users' password through a web page (in a controlled environment).
So, for that, I'm using this code:</p>
<pre><code><?php
$output = shell_exec("sudo -u dummy passwd testUser testUserPassword");
$output2 = shell_exec("dummyPassword");
echo $output;
echo $output2;
echo "done";
?>
</code></pre>
<p>My problem is that this script is not changing the password for the user "testUser".
What am I doing wrong?</p>
<p>Thanks</p>
|
[
{
"answer_id": 127495,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 2,
"selected": false,
"text": "shell_exec dummyPassword"
},
{
"answer_id": 127574,
"author": "Jeremy DeGroot",
"author_id": 20820,
"author_profile": "https://Stackoverflow.com/users/20820",
"pm_score": 2,
"selected": false,
"text": "popen() fopen() file() <?php\n$pipe = popen(\"sudo -u dummy passwd testUser testUserPassword\", 'r');\nfwrite($pipe, \"dummyPasswd\\r\\n\");\npclose($pipe);\necho \"done\";\n?>\n proc_open()"
},
{
"answer_id": 127596,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/expect -f\nset username [lindex $argv 0]\nset password [lindex $argv 1]\n\nspawn passwd $username\nexpect \"(current) UNIX password: \" \nsend \"$password\\r\"\nexpect \"Enter new UNIX password: \"\nsend \"$password\\r\"\nexpect \"Retype new UNIX password: \"\nsend \"$password\\r\"\nexpect eof\n <?php\nshell_exec(\"sudo -u root /path/to/passwd_change.sh testUser testUserPass\");\n?>\n"
},
{
"answer_id": 127639,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 2,
"selected": false,
"text": "$tmpfname = tempnam('/tmp/', 'chpasswd');\n$handle = fopen($tmpfname, \"w\");\nfwrite($handle, \"$username:\".crypt($password).\"\\n\");\nfclose($handle);\nshell_exec(\"sudo sh -c \\\"chpasswd -e < $tmpfname\\\"\");\n"
},
{
"answer_id": 132379,
"author": "voldern",
"author_id": 20326,
"author_profile": "https://Stackoverflow.com/users/20326",
"pm_score": 0,
"selected": false,
"text": "usermod usermod --password username encryptedpassword Where salt1234"
},
{
"answer_id": 383653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nUSER=\"root\"\nNEWPASS=\"bullsheit123\"\n\necho $USER:$NEWPASS | chpasswd\necho $?\n"
},
{
"answer_id": 6927039,
"author": "Cem Kalyoncu",
"author_id": 173347,
"author_profile": "https://Stackoverflow.com/users/173347",
"pm_score": 0,
"selected": false,
"text": " file_put_contents(\"passd\", \"$pass\\n$pass\\n\");\n echo \"$uname: $pass\\n\";\n `passwd $uname --stdin < passd`;\n `rm -rf passd`;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019426/"
] |
127,461
|
<p>A coworker of mine has this problem, apparently after installing Re#, which seems totally irrelevant. But perhaps it isn't.</p>
<p>Could not load file or assembly "SqlManagerUi, Version=9.0.242.0..." or one of its dependencies. The module was expected to contain an assembly manifest. (mscorlib).</p>
<p>Why is this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 56600620,
"author": "Fabricio Leite",
"author_id": 6780871,
"author_profile": "https://Stackoverflow.com/users/6780871",
"pm_score": 3,
"selected": false,
"text": "C:\\Program Files (x86)\\Microsoft SQL Server Management Studio 18\\Common7\\IDE\\Ssms.exe.config <NgenBind_OptimizeNonGac enabled=\"1\" /> <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <!-- ...snip... -->\n <runtime>\n <!-- ...snip... -->\n <!-- Remove this line (~line 38) -->\n <NgenBind_OptimizeNonGac enabled=\"1\" />\n <!-- ...snip... -->\n </runtime>\n <!-- ...snip... -->\n</configuration>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21692/"
] |
127,477
|
<p>In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the <code>ExceptionValidationRule</code> or <code>DataErrorValidationRule</code>.</p>
<p>Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.</p>
<p>In WPF, how do you find out if any of your Data Bound controls have validation errors set?</p>
|
[
{
"answer_id": 128346,
"author": "aogan",
"author_id": 4795,
"author_profile": "https://Stackoverflow.com/users/4795",
"pm_score": 6,
"selected": false,
"text": "public static class Validator\n{\n\n public static bool IsValid(DependencyObject parent)\n {\n // Validate all the bindings on the parent\n bool valid = true;\n LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();\n while (localValues.MoveNext())\n {\n LocalValueEntry entry = localValues.Current;\n if (BindingOperations.IsDataBound(parent, entry.Property))\n {\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n foreach (ValidationRule rule in binding.ValidationRules)\n {\n ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);\n if (!result.IsValid)\n {\n BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);\n System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));\n valid = false;\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n if (!IsValid(child)) { valid = false; }\n }\n\n return valid;\n }\n\n}\n private void saveButton_Click(object sender, RoutedEventArgs e)\n{\n\n if (Validator.IsValid(this)) // is valid\n {\n\n ....\n }\n}\n"
},
{
"answer_id": 565560,
"author": "H-Man2",
"author_id": 43814,
"author_profile": "https://Stackoverflow.com/users/43814",
"pm_score": 5,
"selected": false,
"text": "public static bool IsValid(DependencyObject parent)\n{\n if (Validation.GetHasError(parent))\n return false;\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n if (!IsValid(child)) { return false; }\n }\n\n return true;\n}\n"
},
{
"answer_id": 1085704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "expression.UpdateSource(): if (BindingOperations.IsDataBound(parent, entry.Property))\n{\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n if (binding.ValidationRules.Count > 0)\n {\n BindingExpression expression \n = BindingOperations.GetBindingExpression(parent, entry.Property);\n expression.UpdateSource();\n\n if (expression.HasError) valid = false;\n }\n}\n"
},
{
"answer_id": 1613016,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": " public static bool IsValid(DependencyObject parent)\n {\n // Validate all the bindings on the parent\n bool valid = true;\n LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();\n while (localValues.MoveNext())\n {\n LocalValueEntry entry = localValues.Current;\n if (BindingOperations.IsDataBound(parent, entry.Property))\n {\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n if (binding.ValidationRules.Count > 0)\n {\n BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);\n expression.UpdateSource();\n\n if (expression.HasError)\n {\n valid = false;\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent);\n foreach (object obj in children)\n {\n if (obj is DependencyObject)\n {\n DependencyObject child = (DependencyObject)obj;\n if (!IsValid(child)) { valid = false; }\n }\n }\n return valid;\n }\n"
},
{
"answer_id": 4650392,
"author": "Dean",
"author_id": 570277,
"author_profile": "https://Stackoverflow.com/users/570277",
"pm_score": 8,
"selected": true,
"text": "private void CanExecute(object sender, CanExecuteRoutedEventArgs e)\n{\n e.CanExecute = IsValid(sender as DependencyObject);\n}\n\nprivate bool IsValid(DependencyObject obj)\n{\n // The dependency object is valid if it has no errors and all\n // of its children (that are dependency objects) are error-free.\n return !Validation.GetHasError(obj) &&\n LogicalTreeHelper.GetChildren(obj)\n .OfType<DependencyObject>()\n .All(IsValid);\n}\n"
},
{
"answer_id": 13168143,
"author": "Matthias Loerke",
"author_id": 1552445,
"author_profile": "https://Stackoverflow.com/users/1552445",
"pm_score": 3,
"selected": false,
"text": "public static bool IsValid(this DependencyObject instance)\n{\n // Validate recursivly\n return !Validation.GetHasError(instance) && LogicalTreeHelper.GetChildren(instance).OfType<DependencyObject>().All(child => child.IsValid());\n}\n"
},
{
"answer_id": 35313741,
"author": "Johan Larsson",
"author_id": 1069200,
"author_profile": "https://Stackoverflow.com/users/1069200",
"pm_score": 2,
"selected": false,
"text": "<Border BorderBrush=\"{Binding Path=(validationScope:Scope.HasErrors),\n Converter={local:BoolToBrushConverter},\n ElementName=Form}\"\n BorderThickness=\"1\">\n <StackPanel x:Name=\"Form\" validationScope:Scope.ForInputTypes=\"{x:Static validationScope:InputTypeCollection.Default}\">\n <TextBox Text=\"{Binding SomeProperty}\" />\n <TextBox Text=\"{Binding SomeOtherProperty}\" />\n </StackPanel>\n</Border>\n <ItemsControl ItemsSource=\"{Binding Path=(validationScope:Scope.Errors),\n ElementName=Form}\">\n <ItemsControl.ItemTemplate>\n <DataTemplate DataType=\"{x:Type ValidationError}\">\n <TextBlock Foreground=\"Red\"\n Text=\"{Binding ErrorContent}\" />\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n</ItemsControl>\n"
},
{
"answer_id": 73574604,
"author": "Jim",
"author_id": 486660,
"author_profile": "https://Stackoverflow.com/users/486660",
"pm_score": 0,
"selected": false,
"text": "public static List<string> Errors { get; set; } = new();\n\npublic static bool IsValid(this DependencyObject parent)\n{\n Errors.Clear();\n\n return IsValidInternal(parent);\n}\n\nprivate static bool IsValidInternal(DependencyObject parent)\n{\n // Validate all the bindings on this instance\n bool valid = true;\n\n if (Validation.GetHasError(parent) ||\n GetRowsHasError(parent))\n {\n valid = false;\n\n /*\n * Find the error message and log it in the Errors list.\n */\n foreach (var error in Validation.GetErrors(parent))\n {\n if (error.ErrorContent is string errorMessage)\n {\n Errors.Add(errorMessage);\n }\n else\n {\n if (parent is Control control)\n {\n Errors.Add($\"<unknow error> on field `{control.Name}`\");\n }\n else\n {\n Errors.Add(\"<unknow error>\");\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n if (IsValidInternal(child) == false)\n {\n valid = false;\n }\n }\n\n return valid;\n}\n\nprivate static bool GetRowsHasError(DependencyObject parent)\n{\n DataGridRow dataGridRow;\n\n if (parent is not DataGrid dataGrid)\n {\n /*\n * This is not a DataGrid, so return and say we do not have an error.\n * Errors for this object will be checked by the normal check instead.\n */\n return false;\n }\n\n foreach (var item in dataGrid.Items)\n {\n /*\n * Not sure why, but under some conditions I was returned a null dataGridRow\n * so I had to test for it.\n */\n dataGridRow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);\n if (dataGridRow != null &&\n Validation.GetHasError(dataGridRow))\n {\n return true;\n }\n }\n return false;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407/"
] |
127,492
|
<p>I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">
<display-name>MyEAR</display-name>
<module>
<web>
<web-uri>war1.war</web-uri>
<context-root>/</context-root>
</web>
</module>
<module>
<web>
<web-uri>war2.war</web-uri>
<context-root>/war2location</context-root>
</web>
</module>
</application>
</code></pre>
<p>This results in war2.war being available on <strong><a href="http://localhost:8080/war2location" rel="nofollow noreferrer">http://localhost:8080/war2location</a></strong>, which is correct, but war1.war is on <strong><a href="http://localhost:8080//" rel="nofollow noreferrer">http://localhost:8080//</a></strong> -- note the two slashes.</p>
<p>What am I doing wrong?</p>
<p>Note that the WARs' sun-web.xml files get ignored when contained in an EAR.</p>
|
[
{
"answer_id": 127548,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "http://localhost:8080// http://localhost:8080/ <context-root>.</context-root>"
},
{
"answer_id": 127566,
"author": "Panagiotis Korros",
"author_id": 19331,
"author_profile": "https://Stackoverflow.com/users/19331",
"pm_score": 2,
"selected": false,
"text": "<context-root>ROOT</context-root>\n"
},
{
"answer_id": 127819,
"author": "Marius Marais",
"author_id": 13455,
"author_profile": "https://Stackoverflow.com/users/13455",
"pm_score": 2,
"selected": false,
"text": "RewriteEngine On\nRedirectMatch ^/(w[^/].*) /w/$1\nRedirectMatch ^/([^w].*) /w/$1\n"
},
{
"answer_id": 3994929,
"author": "SteveGreenslade",
"author_id": 462602,
"author_profile": "https://Stackoverflow.com/users/462602",
"pm_score": 1,
"selected": false,
"text": "default-web-module domain.xml"
},
{
"answer_id": 15877576,
"author": "Peter Butkovic",
"author_id": 1581069,
"author_profile": "https://Stackoverflow.com/users/1581069",
"pm_score": 1,
"selected": false,
"text": "asadmin get server.http-service.virtual-server.server.default-web-module\n <your_ear>.ear/META-INF/application.xml\n <context-root/>\n <context-root>/</context-root>\n if (wmContextPath.length() == 0)\n displayContextPath = \"/\";\n else\n displayContextPath = wmContextPath;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13455/"
] |
127,498
|
<p>What guidelines can you give for rich HTML formatting in emails while maintaining good visual stability across many clients and web based email interfaces?</p>
<p>An unrelated answer on a question on Stack Overflow suggested:</p>
<p><a href="http://www.campaignmonitor.com/blog/archives/2008/05/2008_email_design_guidelines.html" rel="noreferrer">http://www.campaignmonitor.com/blog/archives/2008/05/2008_email_design_guidelines.html</a></p>
<p>Which contains the following guidelines:</p>
<ol>
<li><strong>Place stylesheet in <code><body></code> instead of <code><head></code></strong><br>
Some email clients will strip CSS out of the head, but leave it if the style block is (invalidly) in the body. </li>
<li><strong>Use inline styles where ever possible</strong><br>
Gmail will strip any stylesheet, whether in the <code><head></code> or in the <code><body></code>, but honor inline styles assigned using the <code>style=""</code> attribute</li>
<li><strong>Return to tables</strong><br>
Email standards have actually taken a giant step backwards in recent years thanks to Outlook 2007 using the Microsoft Word rendering engine. Unlearn most of what you learned about positioning without stylesheets.</li>
<li><strong>Don't rely on images</strong><br>
Most clients and most web based email clients will not display images unless the user specifically requests them to be displayed.</li>
</ol>
<p>I also have a few "unconfirmed" truths that I don't remember where I read them.</p>
<ol>
<li><strong>Don't use more than two levels of nesting in tables</strong><br>
Is this true. What is likely to happen if I do? Is there any particular client/clients that choke on this?</li>
<li><strong>Be careful of nesting background images in cells/tables</strong><br>
As I understand you may encounter situations where the background image is applied in the descending table/cell completely anew, and not just "shining through". Again, true or not? Which clients?</li>
</ol>
<p>I would like to flesh out this list with more guidelines and experiences from the trenches.</p>
<p><strong>Can you offer any further suggestions?</strong></p>
<p><strong>Update:</strong> I'm specifially asking for guidelines for the <strong>design part</strong> in HTML and consistency there of. Questions about general guidelines for <a href="https://stackoverflow.com/questions/371/how-do-you-make-sure-email-you-send-programmatically-is-not-automatically-marke">avoiding spam filters</a>, and <a href="https://stackoverflow.com/questions/120107/guidelines-for-email-newsletter-service">common courtesy</a> are already on SO.</p>
|
[
{
"answer_id": 127576,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 6,
"selected": false,
"text": "style float <a href=\"http://domain.tld\">www.someotherdomain.tld</a>"
},
{
"answer_id": 127706,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "MIME-Version:\nContent-Type:\n"
},
{
"answer_id": 4278447,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 1,
"selected": false,
"text": "<img src=\"http://myserver.com/myImage.jpg\" alt=\"Lolkat\"/>\n <img src=cid:myImage/>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2105/"
] |
127,514
|
<p>I am writing a program which has two panes (via <code>CSplitter</code>), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single <code>CEdit</code> control? </p>
<p>I'm fairly sure it is to do with the <code>CEdit::OnSize()</code> function... But I'm not really getting anywhere...</p>
<p>Thanks! :)</p>
|
[
{
"answer_id": 127520,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 4,
"selected": true,
"text": "void CMyPane::OnSize(UINT nType, int cx, int cy)\n{\n m_wndEdit.SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);\n}\n"
},
{
"answer_id": 127617,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 4,
"selected": false,
"text": "void MyFrame::OnSize(UINT nType, int w, int h)\n{\n // w and h parameters are new width and height of your frame\n // suppose you have member variable CEdit myEdit which you need to resize/move\n myEdit.MoveWindow(w/5, h/5, w/2, h/2);\n}\n"
},
{
"answer_id": 130069,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 1,
"selected": false,
"text": "SetResize(IDC_EDIT1, 0, 0, 0.5, 1);\nSetResize(IDC_EDIT2, 0.5, 0, 1, 1);\n"
},
{
"answer_id": 54087338,
"author": "nUOs",
"author_id": 4957665,
"author_profile": "https://Stackoverflow.com/users/4957665",
"pm_score": 0,
"selected": false,
"text": "ON_WM_SIZE() ON_WM_SIZING() ON_WM_GETMINMAXINFO() ON_WM_SIZE ::OnSize() ON_WM_SIZING ::OnSizing() ON_WM_GETMINMAXINFO ::OnGetMinMaxInfo() cwnd ON_WM_GETMINMAXINFO"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
127,530
|
<p>I'm adding a new field to a list and view. To add the field to the view, I'm using this code:</p>
<pre><code>view.ViewFields.Add("My New Field");
</code></pre>
<p>However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.</p>
|
[
{
"answer_id": 127859,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 3,
"selected": true,
"text": "string[] fieldNames = new string[] { \"Title\", \"My New Field\", \"Modified\", \"Created\" };\nSPViewFieldCollection viewFields = view.ViewFields;\nviewFields.DeleteAll();\nforeach (string fieldName in fieldNames)\n{\n viewFields.Add(fieldName);\n}\nview.Update();\n"
},
{
"answer_id": 128934,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " string reorderMethod = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\"?> \n <Method ID=\"\"0,REORDERFIELDS\"\"> \n <SetList Scope=\"\"Request\"\">{0}</SetList> \n <SetVar Name=\"\"Cmd\"\">REORDERFIELDS</SetVar> \n <SetVar Name=\"\"ReorderedFields\"\">{1}</SetVar> \n <SetVar Name=\"\"owshiddenversion\"\">{2}</SetVar> \n </Method>\";\n"
},
{
"answer_id": 33506845,
"author": "MarsRobot",
"author_id": 2167309,
"author_profile": "https://Stackoverflow.com/users/2167309",
"pm_score": 1,
"selected": false,
"text": " int newFieldOrderIndex = 1;\n SPViewFieldCollection viewFields = view.ViewFields;\n viewFields.MoveFieldTo(fieldName, newFieldOrderIndex);\n view.Update();\n"
},
{
"answer_id": 47074491,
"author": "SBP",
"author_id": 3748892,
"author_profile": "https://Stackoverflow.com/users/3748892",
"pm_score": 0,
"selected": false,
"text": "ViewFieldCollection srcViewFields = srcView.ViewFields;\nViewFieldCollection destViewFields = destView.ViewFields;\n\nvar srcArray = srcViewFields.ToArray<string>();\nvar destArray = destViewFields.ToArray<string>();\n\nforeach (var item in destArray)\n{\n destViewFields.MoveFieldTo(item, Array.IndexOf(srcArray, item));\n destView.Update();\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
127,534
|
<p>We have a couple of developers asking for <code>allow_url_fopen</code> to be enabled on our server. What's the norm these days and if <code>libcurl</code> is enabled is there really any good reason to allow?</p>
<p>Environment is: Windows 2003, PHP 5.2.6, FastCGI</p>
|
[
{
"answer_id": 127562,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 5,
"selected": true,
"text": "allow_url_include allow_url_fopen allow_url_include allow_url_fopen"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] |
127,556
|
<p>I have a listbox where the items contain checkboxes:</p>
<pre><code><ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected.</p>
<p>The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off.</p>
<p>Some more info:</p>
<pre><code>private void Checkbox_Click(object sender, RoutedEventArgs e)
{
CheckBox chkBox = e.OriginalSource as CheckBox;
}
</code></pre>
<p>In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null.</p>
<p>Kent's answer put me down the right path, here's what I ended up with:</p>
<pre><code><ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" />
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item.</p>
|
[
{
"answer_id": 127589,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": true,
"text": "CheckBox <StackPanel Orientation=\"Horizontal\">\n <CheckBox IsChecked=\"{Binding IsChecked}\"/>\n <TextBlock Text=\"{Binding DisplayText}\"/>\n</StackPanel>\n ListBoxItem CheckBox ListBoxItem UIElement.KeyUp DataTemplate <CheckBox IsChecked=\"{Binding IsChecked}\" UIElement.KeyUp=\"...\"/>\n"
},
{
"answer_id": 133823,
"author": "Vassili Altynikov",
"author_id": 22205,
"author_profile": "https://Stackoverflow.com/users/22205",
"pm_score": 2,
"selected": false,
"text": "<ListBox>\n <ListBox.ItemTemplate>\n <DataTemplate>\n <CheckBox Content=\"{Binding DisplayText}\" IsChecked=\"{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}\"/>\n </DataTemplate>\n </ListBox.ItemTemplate>\n</ListBox>\n"
},
{
"answer_id": 7817243,
"author": "Patrick Klug",
"author_id": 10779,
"author_profile": "https://Stackoverflow.com/users/10779",
"pm_score": 2,
"selected": false,
"text": "ItemsControl <ItemsControl Style=\"{StaticResource CheckBoxListStyle}\" Name=\"EditListBox\">\n <ItemsControl .ItemTemplate>\n <DataTemplate>\n <CheckBox Click=\"Checkbox_Click\" IsChecked=\"{Binding Path=IsChecked, Mode=TwoWay}\" Content=\"{Binding Path=DisplayText}\" />\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n</ItemsControl>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2284/"
] |
127,564
|
<p>I have come to realize that Windbg is a very powerful debugger for the Windows platform & I learn something new about it once in a while. Can fellow Windbg users share some of their mad skills?</p>
<p>ps: I am not looking for a nifty command, those can be found in the documentation. How about sharing tips on doing something that one couldn't otherwise imagine could be done with windbg? e.g. Some way to generate statistics about memory allocations when a process is run under windbg.</p>
|
[
{
"answer_id": 127875,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 5,
"selected": false,
"text": ".cmdtree <file> <file>"
},
{
"answer_id": 159483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "dv /i /t\n?? this\nkM (kinda undocumented) generates links to frames\n.frame x\n!analyze -v\n!lmi\n~\n dv /i /t dv /i /t ?? this ?? this kM k M .frame x .frame x dv /i /t d !analyze -v !analyze analyze ! -v !lmi !lmi lmi ~ ~"
},
{
"answer_id": 171935,
"author": "Tal",
"author_id": 11287,
"author_profile": "https://Stackoverflow.com/users/11287",
"pm_score": 1,
"selected": false,
"text": ".heap -stat .heap -flt ..."
},
{
"answer_id": 537670,
"author": "jturcotte",
"author_id": 56315,
"author_profile": "https://Stackoverflow.com/users/56315",
"pm_score": 5,
"selected": false,
"text": "!heap -h 0 \"C:\\Program Files\\Debugging Tools for Windows\\cdb.exe\" -c \"!heap -h 0;q\" -z [DumpPath] > DumpHeapEntries.log\n grep \"busy ([[:alnum:]]\\+)\" DumpHeapEntries.log \\\n| gawk '{ str = $8; gsub(/\\(|\\)/, \"\", str); print \"0x\" str \" 0x\" $4 }' \\\n| sort \\\n| uniq -c \\\n| gawk '{ printf \"%10.2f %10d %10d ( %s = %d )\\n\", $1*strtonum($3)/1024, $1, strtonum($3), $2, strtonum($2) }' \\\n| sort > DumpHeapEntriesStats.log\n 8489.52 707 12296 ( 0x3000 = 12288 )\n 11894.28 5924 2056 ( 0x800 = 2048 )\n 13222.66 846250 16 ( 0x2 = 2 )\n 14120.41 602471 24 ( 0x2 = 2 )\n 31539.30 2018515 16 ( 0x1 = 1 )\n 38902.01 1659819 24 ( 0x1 = 1 )\n 40856.38 817 51208 ( 0xc800 = 51200 )\n1196684.53 25529270 48 ( 0x24 = 36 )\n dps 0:075> dps 3be7f7e8\n3be7f7e8 00020006\n3be7f7ec 090c01e7\n3be7f7f0 0b40fe94 SomeDll!SomeType::`vftable'\n3be7f7f4 00000000\n3be7f7f8 00000000\n"
},
{
"answer_id": 1221659,
"author": "Nicolas Lefebvre",
"author_id": 73660,
"author_profile": "https://Stackoverflow.com/users/73660",
"pm_score": 3,
"selected": false,
"text": "$$ dump some information from $t0\n\n$$ allow the user to examine our reference\naS /x myref @@(&((<C++ type of the reference>*)@$t0)->reference )\n.block { .printf /D \"<link cmd=\\\"$$>a< <full path to this script> ${myref}\\\">dump Ref</link> \" }\n"
},
{
"answer_id": 1814027,
"author": "wangzq",
"author_id": 10564,
"author_profile": "https://Stackoverflow.com/users/10564",
"pm_score": 2,
"selected": false,
"text": "; WM_VSCROLL = 0x115 (277)\nScrollUp(control=\"\")\n{\n SendMessage, 277, 0, 0, %control%, A\n}\n\nScrollDown(control=\"\")\n{\n SendMessage, 277, 1, 0, %control%, A\n}\n\nScrollPageUp(control=\"\")\n{\n SendMessage, 277, 2, 0, %control%, A\n}\n\nScrollPageDown(control=\"\")\n{\n SendMessage, 277, 3, 0, %control%, A\n}\n\nScrollToTop(control=\"\")\n{\n SendMessage, 277, 6, 0, %control%, A\n}\n\nScrollToBottom(control=\"\")\n{ \n SendMessage, 277, 7, 0, %control%, A\n}\n\n#IfWinActive, ahk_class WinDbgFrameClass\n ; For WinDbg, when the child window is attached to the main window\n !UP::ScrollUp(\"RichEdit50W1\")\n ^k::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n ^j::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n#IfWinActive, ahk_class WinBaseClass\n ; Also for WinDbg, when the child window is a separate window\n !UP::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n"
},
{
"answer_id": 2731215,
"author": "JasonE",
"author_id": 266189,
"author_profile": "https://Stackoverflow.com/users/266189",
"pm_score": 3,
"selected": false,
"text": ".prefer_dml 1 lm .reload /f /o file.dll /o .enable_unicode 1 .ignore_missing_pages 1 aS !p !process;\naS !t !thread;\naS .f .frame;\naS .p .process /p /r\naS .t .thread /p /r\naS dv dv /V /i /t //make dv do your favorite options by default\naS f !process 0 0 //f for find, e.g. f explorer.exe\n"
},
{
"answer_id": 3701342,
"author": "Naveen",
"author_id": 19407,
"author_profile": "https://Stackoverflow.com/users/19407",
"pm_score": 2,
"selected": false,
"text": "!for_each_module .if(($sicmp( \"@#ModuleName\" , \"mscorwks\") = 0) ) \n{.loadby sos mscorwks} .elsif ($sicmp( \"@#ModuleName\" , \"clr\") = 0) \n{.loadby sos clr}\n"
},
{
"answer_id": 4869928,
"author": "Naveen",
"author_id": 19407,
"author_profile": "https://Stackoverflow.com/users/19407",
"pm_score": 1,
"selected": false,
"text": "j $ptrsize = 8 'aS !ds .printf \"%mu \\n\", c+';'aS !ds .printf \"%mu \\n\", 10+'\n 0:000> !ds 00000000023620b8\n\nMaxConcurrentInstances\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15071/"
] |
127,587
|
<p>I'm trying to use <a href="http://trac.videolan.org/jvlc/" rel="nofollow noreferrer">JVLC</a> but I can't seem to get it work. I've downloaded the jar, I installed <a href="http://www.videolan.org/vlc/" rel="nofollow noreferrer">VLC</a> and passed the -D argument to the JVM telling it where VLC is installed. I also tried:</p>
<pre><code>NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC");
</code></pre>
<p>with no luck. I always get:</p>
<blockquote>
<p>Exception in thread "main"
java.lang.UnsatisfiedLinkError: Unable
to load library 'libvlc': The
specified module could not be found.</p>
</blockquote>
<p>Has anyone made it work?</p>
|
[
{
"answer_id": 127875,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 5,
"selected": false,
"text": ".cmdtree <file> <file>"
},
{
"answer_id": 159483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "dv /i /t\n?? this\nkM (kinda undocumented) generates links to frames\n.frame x\n!analyze -v\n!lmi\n~\n dv /i /t dv /i /t ?? this ?? this kM k M .frame x .frame x dv /i /t d !analyze -v !analyze analyze ! -v !lmi !lmi lmi ~ ~"
},
{
"answer_id": 171935,
"author": "Tal",
"author_id": 11287,
"author_profile": "https://Stackoverflow.com/users/11287",
"pm_score": 1,
"selected": false,
"text": ".heap -stat .heap -flt ..."
},
{
"answer_id": 537670,
"author": "jturcotte",
"author_id": 56315,
"author_profile": "https://Stackoverflow.com/users/56315",
"pm_score": 5,
"selected": false,
"text": "!heap -h 0 \"C:\\Program Files\\Debugging Tools for Windows\\cdb.exe\" -c \"!heap -h 0;q\" -z [DumpPath] > DumpHeapEntries.log\n grep \"busy ([[:alnum:]]\\+)\" DumpHeapEntries.log \\\n| gawk '{ str = $8; gsub(/\\(|\\)/, \"\", str); print \"0x\" str \" 0x\" $4 }' \\\n| sort \\\n| uniq -c \\\n| gawk '{ printf \"%10.2f %10d %10d ( %s = %d )\\n\", $1*strtonum($3)/1024, $1, strtonum($3), $2, strtonum($2) }' \\\n| sort > DumpHeapEntriesStats.log\n 8489.52 707 12296 ( 0x3000 = 12288 )\n 11894.28 5924 2056 ( 0x800 = 2048 )\n 13222.66 846250 16 ( 0x2 = 2 )\n 14120.41 602471 24 ( 0x2 = 2 )\n 31539.30 2018515 16 ( 0x1 = 1 )\n 38902.01 1659819 24 ( 0x1 = 1 )\n 40856.38 817 51208 ( 0xc800 = 51200 )\n1196684.53 25529270 48 ( 0x24 = 36 )\n dps 0:075> dps 3be7f7e8\n3be7f7e8 00020006\n3be7f7ec 090c01e7\n3be7f7f0 0b40fe94 SomeDll!SomeType::`vftable'\n3be7f7f4 00000000\n3be7f7f8 00000000\n"
},
{
"answer_id": 1221659,
"author": "Nicolas Lefebvre",
"author_id": 73660,
"author_profile": "https://Stackoverflow.com/users/73660",
"pm_score": 3,
"selected": false,
"text": "$$ dump some information from $t0\n\n$$ allow the user to examine our reference\naS /x myref @@(&((<C++ type of the reference>*)@$t0)->reference )\n.block { .printf /D \"<link cmd=\\\"$$>a< <full path to this script> ${myref}\\\">dump Ref</link> \" }\n"
},
{
"answer_id": 1814027,
"author": "wangzq",
"author_id": 10564,
"author_profile": "https://Stackoverflow.com/users/10564",
"pm_score": 2,
"selected": false,
"text": "; WM_VSCROLL = 0x115 (277)\nScrollUp(control=\"\")\n{\n SendMessage, 277, 0, 0, %control%, A\n}\n\nScrollDown(control=\"\")\n{\n SendMessage, 277, 1, 0, %control%, A\n}\n\nScrollPageUp(control=\"\")\n{\n SendMessage, 277, 2, 0, %control%, A\n}\n\nScrollPageDown(control=\"\")\n{\n SendMessage, 277, 3, 0, %control%, A\n}\n\nScrollToTop(control=\"\")\n{\n SendMessage, 277, 6, 0, %control%, A\n}\n\nScrollToBottom(control=\"\")\n{ \n SendMessage, 277, 7, 0, %control%, A\n}\n\n#IfWinActive, ahk_class WinDbgFrameClass\n ; For WinDbg, when the child window is attached to the main window\n !UP::ScrollUp(\"RichEdit50W1\")\n ^k::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n ^j::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n#IfWinActive, ahk_class WinBaseClass\n ; Also for WinDbg, when the child window is a separate window\n !UP::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n"
},
{
"answer_id": 2731215,
"author": "JasonE",
"author_id": 266189,
"author_profile": "https://Stackoverflow.com/users/266189",
"pm_score": 3,
"selected": false,
"text": ".prefer_dml 1 lm .reload /f /o file.dll /o .enable_unicode 1 .ignore_missing_pages 1 aS !p !process;\naS !t !thread;\naS .f .frame;\naS .p .process /p /r\naS .t .thread /p /r\naS dv dv /V /i /t //make dv do your favorite options by default\naS f !process 0 0 //f for find, e.g. f explorer.exe\n"
},
{
"answer_id": 3701342,
"author": "Naveen",
"author_id": 19407,
"author_profile": "https://Stackoverflow.com/users/19407",
"pm_score": 2,
"selected": false,
"text": "!for_each_module .if(($sicmp( \"@#ModuleName\" , \"mscorwks\") = 0) ) \n{.loadby sos mscorwks} .elsif ($sicmp( \"@#ModuleName\" , \"clr\") = 0) \n{.loadby sos clr}\n"
},
{
"answer_id": 4869928,
"author": "Naveen",
"author_id": 19407,
"author_profile": "https://Stackoverflow.com/users/19407",
"pm_score": 1,
"selected": false,
"text": "j $ptrsize = 8 'aS !ds .printf \"%mu \\n\", c+';'aS !ds .printf \"%mu \\n\", 10+'\n 0:000> !ds 00000000023620b8\n\nMaxConcurrentInstances\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459/"
] |
127,591
|
<p>How do I make <kbd>Caps Lock</kbd> work like <kbd>Esc</kbd> in Mac OS X?</p>
|
[
{
"answer_id": 249923,
"author": "eelco",
"author_id": 8293,
"author_profile": "https://Stackoverflow.com/users/8293",
"pm_score": 5,
"selected": false,
"text": "map <Help> <Esc>\nmap! <Help> <Esc>\nmap <Insert> <Esc>\nmap! <Insert> <Esc>\n"
},
{
"answer_id": 8437594,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 9,
"selected": false,
"text": "PCKeyboardHack No Action pqrs.org"
},
{
"answer_id": 23599812,
"author": "user2581875",
"author_id": 2581875,
"author_profile": "https://Stackoverflow.com/users/2581875",
"pm_score": 3,
"selected": false,
"text": "~/Library/Preferences/ByHost/.GlobalPreferences*.plist <key>HIDKeyboardModifierMappingDst</key>\n<integer>6</integer>\n<key>HIDKeyboardModifierMappingSrc</key>\n<integer>0</integer>\n"
},
{
"answer_id": 40015938,
"author": "mb21",
"author_id": 214446,
"author_profile": "https://Stackoverflow.com/users/214446",
"pm_score": 2,
"selected": false,
"text": "~/.karabiner.d/configuration/karabiner.json {\n \"profiles\" : [\n {\n \"name\" : \"Default profile\",\n \"selected\" : true,\n \"simple_modifications\" : {\n \"caps_lock\" : \"escape\"\n }\n }\n ]\n}\n"
},
{
"answer_id": 46460200,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 6,
"selected": false,
"text": "hidutil hidutil property --set '{\"UserKeyMapping\":[{\"HIDKeyboardModifierMappingSrc\":0x700000039,\"HIDKeyboardModifierMappingDst\":0x700000029}]}'\n hidutil property --set '{\"UserKeyMapping\":[{\"HIDKeyboardModifierMappingSrc\":0x700000039,\"HIDKeyboardModifierMappingDst\":0x70000002A}, {\"HIDKeyboardModifierMappingSrc\":0x70000002A,\"HIDKeyboardModifierMappingDst\":0x70000004C}]}'\n hidutil property --get \"UserKeyMapping\"\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!-- Place in ~/Library/LaunchAgents/ -->\n<!-- launchctl load com.ldaws.CapslockBackspace.plist -->\n<plist version=\"1.0\">\n <dict>\n <key>Label</key>\n <string>com.ldaws.CapslockEsc</string>\n <key>ProgramArguments</key>\n <array>\n <string>/usr/bin/hidutil</string>\n <string>property</string>\n <string>--set</string>\n <string>{\"UserKeyMapping\":[{\"HIDKeyboardModifierMappingSrc\":0x700000039,\"HIDKeyboardModifierMappingDst\":0x70000002A},{\"HIDKeyboardModifierMappingSrc\":0x70000002A,\"HIDKeyboardModifierMappingDst\":0x70000004C}]}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n </dict>\n</plist>\n ~/Library/LaunchAgents/com.ldaws.CapslockBackspace.plist launchctl load com.ldaws.CapslockBackspace.plist\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7706/"
] |
127,598
|
<p>So, I have Flex project that loads a Module using the ModuleManager - not the module loader. The problem that I'm having is that to load an external asset (like a video or image) the path to load that asset has to be relative to the Module swf...not relative to the swf that loaded the module.</p>
<p>The question is - How can I load an asset into a loaded module using a path relative to the parent swf, not the module swf?</p>
<hr>
<p>Arg! So in digging through the SWFLoader Class I found this chunk of code in private function loadContent:</p>
<pre><code> // make relative paths relative to the SWF loading it, not the top-level SWF
if (!(url.indexOf(":") > -1 || url.indexOf("/") == 0 || url.indexOf("\\") == 0))
{
var rootURL:String;
if (SystemManagerGlobals.bootstrapLoaderInfoURL != null && SystemManagerGlobals.bootstrapLoaderInfoURL != "")
rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL;
else if (root)
rootURL = LoaderUtil.normalizeURL(root.loaderInfo);
else if (systemManager)
rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo);
if (rootURL)
{
var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/"));
if (lastIndex != -1)
url = rootURL.substr(0, lastIndex + 1) + url;
}
}
}
</code></pre>
<p>So apparently, Adobe has gone through the extra effort to make images load in the actual swf and not the top level swf (with no flag to choose otherwise...), so I guess I should submit a feature request to have some sort of "load relative to swf" flag, edit the SWFLoader directly, or maybe I should have everything relative to the individual swf and not the top level...any suggestions?</p>
|
[
{
"answer_id": 132670,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 3,
"selected": true,
"text": "mx.core.Application"
},
{
"answer_id": 2252676,
"author": "Fréderic Cox",
"author_id": 271921,
"author_profile": "https://Stackoverflow.com/users/271921",
"pm_score": 1,
"selected": false,
"text": "var urlParts:Array = this.url.split(\"/\");\nurlParts.pop();\nbaseURL = urlParts.join(\"/\");\nAlert.show(baseURL);\n {baseURL + \"/location/file.ext\"} /location/file.ext"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
127,606
|
<p>I'm trying to generate customized xml files from a template xml file in python. </p>
<p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p>
<pre><code>conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
|
[
{
"answer_id": 127678,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": false,
"text": "import xml.etree.ElementTree as ET\ndoc = ET.parse(\"template.xml\")\nlvl1 = doc.findall(\"level1-name\")[0]\nlvl1.remove(lvl1.find(\"leaf1\")\nlvl1.remove(lvl1.find(\"leaf2\")\n# or use del lvl1[idx]\ndoc.write(\"config-new.xml\")\n"
},
{
"answer_id": 127720,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "print xml.etree.ElementTree.tostring( conf_new )\n"
},
{
"answer_id": 128023,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 4,
"selected": true,
"text": "<root>\n <level1>leaf1</level1>\n <level2>leaf2</level2>\n</root>\n from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString\n\nsoup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file\nsoup.contents[0].name\n# u'root'\n soup.root.contents[0].name\n# u'level1'\n import re\ntags_starting_with_level = soup.findAll(re.compile('^level'))\nfor tag in tags_starting_with_level: print tag.name\n# level1\n# level2\n # build and insert a new level with a new leaf\nlevel3 = Tag(soup, 'level3')\nlevel3.insert(0, NavigableString('leaf3')\nsoup.root.insert(2, level3)\n\nprint soup.prettify()\n# <root>\n# <level1>\n# leaf1\n# </level1>\n# <level2>\n# leaf2\n# </level2>\n# <level3>\n# leaf3\n# </level3>\n# </root>\n"
},
{
"answer_id": 2303733,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "\n \nimport xml.etree.ElementTree as etree\n\ntree = etree.parse('test.xml')\nroot = tree.getroot()\n\ndef xml_to_dict(el):\n d={}\n if el.text:\n d[el.tag] = el.text\n else:\n d[el.tag] = {}\n children = el.getchildren()\n if children:\n d[el.tag] = map(xml_to_dict, children)\n return d\n <note>\n <to>Tove</to>\n <from>Jani</from>\n <heading>Reminder</heading>\n <body>Don't forget me this weekend!</body>\n</note>\n \n{'note': [{'to': 'Tove'},\n {'from': 'Jani'},\n {'heading': 'Reminder'},\n {'body': \"Don't forget me this weekend!\"}]}\n"
},
{
"answer_id": 2545294,
"author": "Loooo",
"author_id": 305090,
"author_profile": "https://Stackoverflow.com/users/305090",
"pm_score": 0,
"selected": false,
"text": "root = ET.parse(xh)\ndata = root.getroot()\nxdic = {}\nif data > None:\n for part in data.getchildren():\n xdic[part.tag] = part.text\n"
},
{
"answer_id": 6088101,
"author": "Mark",
"author_id": 437948,
"author_profile": "https://Stackoverflow.com/users/437948",
"pm_score": 2,
"selected": false,
"text": "def xml_to_dictionary(element):\n l = len(namespace)\n dictionary={}\n tag = element.tag[l:]\n if element.text:\n if (element.text == ' '):\n dictionary[tag] = {}\n else:\n dictionary[tag] = element.text\n children = element.getchildren()\n if children:\n subdictionary = {}\n for child in children:\n for k,v in xml_to_dictionary(child).items():\n if k in subdictionary:\n if ( isinstance(subdictionary[k], list)):\n subdictionary[k].append(v)\n else:\n subdictionary[k] = [subdictionary[k], v]\n else:\n subdictionary[k] = v\n if (dictionary[tag] == {}):\n dictionary[tag] = subdictionary\n else:\n dictionary[tag] = [dictionary[tag], subdictionary]\n if element.attrib:\n attribs = {}\n for k,v in element.attrib.items():\n attribs[k] = v\n if (dictionary[tag] == {}):\n dictionary[tag] = attribs\n else:\n dictionary[tag] = [dictionary[tag], attribs]\n return dictionary\n spacepattern = re.compile(r'\\s+')\nmydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))\n {'note': {'to': 'Tove',\n 'from': 'Jani',\n 'heading': 'Reminder',\n 'body': \"Don't forget me this weekend!\"}}\n <elementName attributeName='attributeContent'>elementContent</elementName>\n"
},
{
"answer_id": 10599880,
"author": "Robbo",
"author_id": 1395962,
"author_profile": "https://Stackoverflow.com/users/1395962",
"pm_score": 1,
"selected": false,
"text": "d.update(('@' + k, v) for k, v in el.attrib.iteritems())\n import xml.etree.ElementTree as etree\nfrom urllib import urlopen\n\nxml_file = \"http://your_xml_url\"\ntree = etree.parse(urlopen(xml_file))\nroot = tree.getroot()\n\ndef xml_to_dict(el):\n d={}\n if el.text:\n d[el.tag] = el.text\n else:\n d[el.tag] = {}\n children = el.getchildren()\n if children:\n d[el.tag] = map(xml_to_dict, children)\n\n d.update(('@' + k, v) for k, v in el.attrib.iteritems())\n\n return d\n xml_to_dict(root)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1489/"
] |
127,610
|
<p>I have an SSIS package, which depending on a boolean variable, should either go to a Script Task or an Email task.(Note: the paths are coming <em>from</em> a Script Task)</p>
<p>I recall in the old dts designer there was a way to do this via code. What is the proper way to accomplish this in SSIS?</p>
|
[
{
"answer_id": 129159,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 2,
"selected": false,
"text": "@[User::SendEmail] == True\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343291/"
] |
127,625
|
<p>I'm currently working on a class that calculates the difference between two objects. I'm trying to decide what the best design for this class would be. I see two options:</p>
<p>1) Single-use class instance. Takes the objects to diff in the constructor and calculates the diff for that.</p>
<pre><code>public class MyObjDiffer {
public MyObjDiffer(MyObj o1, MyObj o2) {
// Calculate diff here and store results in member variables
}
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
// ...
}
</code></pre>
<p>2) Re-usable class instance. Constructor takes no arguments. Has a "calculateDiff()" method that takes the objects to diff, and returns the results.</p>
<pre><code>public class MyObjDiffer {
public MyObjDiffer() { }
public DiffResults getResults(MyObj o1, MyObj o2) {
// calculate and return the results. Nothing is stored in this class's members.
}
}
public class DiffResults {
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
}
</code></pre>
<p>The diffing will be fairly complex (details don't matter for the question), so there will need to be a number of helper functions. If I take solution 1 then I can store the data in member variables and don't have to pass everything around. It's slightly more compact, as everything is handled within a single class.</p>
<p>However, conceptually, it seems weird that a "Differ" would be specific to a certain set of results. Option 2 splits the results from the logic that actually calculates them.</p>
<p>EDIT: Option 2 also provides the ability to make the "MyObjDiffer" class static. Thanks kitsune, I forgot to mention that.</p>
<p>I'm having trouble seeing any significant pro or con to either option. I figure this kind of thing (a class that just handles some one-shot calculation) has to come up fairly often, and maybe I'm missing something. So, I figured I'd pose the question to the cloud. Are there significant pros or cons to one or the other option here? Is one inherently better? Does it matter?</p>
<p>I am doing this in Java, so there might be some restrictions on the possibilities, but the overall question of design is probably language-agnostic.</p>
|
[
{
"answer_id": 127670,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "public class Diff\n{\n public Diff(String path1, String path2)\n {\n // get diff\n\n if (same)\n throw new EmptyDiffException();\n }\n\n public String getDiffString()\n {\n\n }\n\n public int numHunks()\n {\n\n }\n\n public bool apply(String path1)\n {\n // try to apply diff as patch to file at path1. Return\n // whether the patch applied successfully or not.\n }\n\n public bool merge(Diff diff)\n {\n // similar to apply(), but do merge yourself with another diff\n }\n}\n"
},
{
"answer_id": 127695,
"author": "daveb",
"author_id": 11858,
"author_profile": "https://Stackoverflow.com/users/11858",
"pm_score": 0,
"selected": false,
"text": "Diffs diffs = Diffs.calculateDifferences(foo, bar);\n"
},
{
"answer_id": 127744,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "MyObjDiffer"
},
{
"answer_id": 127772,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 1,
"selected": false,
"text": "MyComparer cmp = new MyComparer(obj1, obj2);\nboolean match = cmp.isMatch();\ncmp.setSubjects(obj3,obj4);\nList uniques1 = cmp.getOnlyIn(MyComparer.FIRST);\ncmd.setSubject(MyComparer.SECOND,obj5);\nList uniques = cmp.getOnlyIn(MyComparer.SECOND);\n // set up cmp with options and the master object\nMyComparer cmp = new MyComparer();\ncmp.setIgnoreCase(true);\ncmp.setIgnoreTrailingWhitespace(false);\ncmp.setSubject(MyComparer.FIRST,canonicalSubject);\n\n// find items that are in the testSubjects objects,\n// but not in the master.\nList extraItems = new ArrayList();\nfor (Iterator it=testSubjects.iterator(); it.hasNext(); ) {\n cmp.setSubject(MyComparer.SECOND,it.next());\n extraItems.append(cmp.getOnlyIn(MyComparer.SECOND);\n}\n"
},
{
"answer_id": 127809,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "d= new MyObjDiffer( x, y ) d= theDiffer.getResults( x, y ) DifferFactory df= new DifferFactory();\nMyObjDiffer mod= df.getDiffer();\nmod.getResults( x, y );\n getDiffer"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] |
127,626
|
<p>I'm trying to install <a href="http://www.maatkit.org/" rel="nofollow noreferrer">Maatkit</a> following <a href="http://maatkit.sourceforge.net/doc/maatkit.html#installation" rel="nofollow noreferrer">the maatkit instructions</a>. I can't get past having to install DBD::mysql. "Warning: prerequisite DBD::mysql 1 not found."
When I try to install DBD::mysql from cpan, I get very helpful "make had returned bad status, install seems impossible".</p>
<p>Perl is "v5.8.8 built for darwin-thread-multi-2level", the one that came with OS X. I also tried <a href="http://search.cpan.org/dist/DBD-mysql/lib/DBD/mysql.pm#INSTALLATION" rel="nofollow noreferrer">building</a> from source with same result.</p>
|
[
{
"answer_id": 127923,
"author": "Corion",
"author_id": 21731,
"author_profile": "https://Stackoverflow.com/users/21731",
"pm_score": 3,
"selected": false,
"text": "make site:perlmonks.org"
},
{
"answer_id": 344043,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$ perl Makefile.PL\nChecking if your kit is complete...\nLooks good\nWarning: prerequisite DBD::mysql 1 not found.\nWriting Makefile for maatkit\n\n$ mysql --version\nmysql Ver 14.12 Distrib 5.0.51b, for apple-darwin9.0.0b5 (i686) using readline 5.0\n"
},
{
"answer_id": 346528,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql\nsudo ln -s /usr/local/mysql/include /usr/local/mysql/include/mysql\nsudo perl -MCPAN -e 'install Bundle::DBD::mysql'\n perl Makefile.PL\nsudo make install\n"
},
{
"answer_id": 346533,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 0,
"selected": false,
"text": "ayaz@ayazs-macbook$ fink list | grep -i 'dbd-mysql'\n dbd-mysql-pm586 3.0008-10 Perl5 Database Interface to MySQL\n dbd-mysql-pm588 3.0008-10 Perl5 Database Interface to MySQL\n $ sudo fink --use-binary-dist install mysql15-dev\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
127,638
|
<p>Is there a way to prevent someone from faking a mime type on a file upload and then running a php/exe/etc...</p>
<p>I have to make the file upload directory writeable and executable so that the files can be stored, but this allows anyone to run a script after. One thing I can do is add random data to the file name so they can't guess the file name after (since they still can't read from the directory to get a listing).</p>
<p>I'm using file upload with php for the first time and I'm trying to cover all of the security issues.</p>
|
[
{
"answer_id": 127658,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": true,
"text": "remove_all_my_files.php http://xample.com/uploads/remove_all_my_files.php"
},
{
"answer_id": 127694,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "$_FILES <?php\n// example :-)\n$finfo = finfo_open(FILEINFO_MIME);\necho finfo_file($finfo, '/path/to/your/upload/file);\nfinfo_close($finfo);\n?>\n"
},
{
"answer_id": 127835,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "function ReadAndOutputFileChunked ($filename) { \n $chunksize = 1*(1024*1024); // how many bytes per chunk \n $buffer = ''; \n $handle = @fopen($filename, 'rb'); \n if ($handle === false) { \n return false; \n } \n while (!feof($handle)) { \n $buffer = @fread($handle, $chunksize); \n print $buffer; \n } \n return @fclose($handle); \n}\n\nheader(\"Content-type: application/octet-stream\");\nReadAndOutputFileChunked('/private/path/to/upload/files/' . $nameOfFile);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12529/"
] |
127,645
|
<p>When an error occurs in a function, I'd like to know the sequence of events that lead up to it, especially when that function is called from a dozen different places. Is there any way to retrieve the call stack in VB6, or do I have to do it the hard way (e.g., log entries in every function and error handler, etc.)?</p>
|
[
{
"answer_id": 206726,
"author": "JeffK",
"author_id": 5420,
"author_profile": "https://Stackoverflow.com/users/5420",
"pm_score": 4,
"selected": false,
"text": "Private Function DoSomething(ByVal Arg as String)\n\n On Error GoTo Handler\n\n Dim ThisVar as String\n Dim ThatVar as Long\n\n ' Code here to implement DoSomething...\n\n Exit Function\n\nHandler:\n Err.Raise Err.Number, , \"MiscFunctions.DoSomething: \" & Err.Description\n\nEnd Function\n Err.Raise PCLOADLETTER_ERRNUM, , \"PC Load Letter error on Printer \"\"\" & PrinterName & \"\"\"\"\n"
},
{
"answer_id": 20190458,
"author": "Max1234-ITA",
"author_id": 3031020,
"author_profile": "https://Stackoverflow.com/users/3031020",
"pm_score": 0,
"selected": false,
"text": "Sub MyRoutine\n (...) ' Your code here\n call DoSomething (Var1, Var2, Var3, \"MyRoutine\")\n ' ^\n ' Present routine's name -----------+\n\n (...) ' Your code here\n\nEnd Sub\n\n\nPublic DoSomething (DoVar1, DoVar2, DoVar3, Optional Caller as string = \"[unknown]\")\n Debug.Print \" DoSomething Routine Called. Caller = \" & Caller\n\n ... ' (your code here)\n\nEnd Sub\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
127,654
|
<p>I'm working on an existing report and I would like to test it with the database. The problem is that the catalog set during the initial report creation no longer exists. I just need to change the catalog parameter to a new database. The report is using a stored proc for its data. It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over.</p>
<p>I'm working in the designer in Studio and just need to tweak the catalog property to get a preview. I have code working to handle things properly from the program.</p>
|
[
{
"answer_id": 127674,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 0,
"selected": false,
"text": "report.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);\n private void FixDatabase(ReportDocument report)\n {\n ConnectionInfo crystalConnectionInfo = someConnectionInfo;\n\n foreach (Table table in report.Database.Tables)\n {\n TableLogOnInfo logOnInfo = table.LogOnInfo;\n\n if (logOnInfo != null)\n {\n logOnInfo.ConnectionInfo = crystalConnectionInfo;\n\n table.LogOnInfo.TableName = table.Name;\n table.LogOnInfo.ConnectionInfo.UserID = someConnectionInfo.UserID;\n table.LogOnInfo.ConnectionInfo.Password = someConnectionInfo.Password;\n table.LogOnInfo.ConnectionInfo.DatabaseName = someConnectionInfo.DatabaseName;\n table.LogOnInfo.ConnectionInfo.ServerName = someConnectionInfo.ServerName;\n table.ApplyLogOnInfo(table.LogOnInfo);\n\n table.Location = someConnectionInfo.DatabaseName + \".dbo.\" + table.Name;\n }\n }\n\n //call this method recursively for each subreport\n foreach (ReportObject reportObject in report.ReportDefinition.ReportObjects)\n {\n if (reportObject.Kind == ReportObjectKind.SubreportObject)\n {\n this.FixDatabase(report.OpenSubreport(((SubreportObject)reportObject).SubreportName));\n }\n }\n }\n"
},
{
"answer_id": 135406,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 2,
"selected": false,
"text": "#'SET REPORT CONNECTION INFO\n For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1\n rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\n Next\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] |
127,669
|
<p>I have a computer A with two directory trees. The first directory contains the original mod dates that span back several years. The second directory is a copy of the first with a few additional files. There is a second computer be which contains a directory tree which is the same as the second directory on computer A (new mod times and additional files). How update the files in the two newer directories on both machines so that the mod times on the files are the same as the original? Note that these directory trees are in the order of 10s of gigabytes so the solution would have to include some method of sending only the date information to the second computer.</p>
|
[
{
"answer_id": 128307,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 1,
"selected": false,
"text": "touch #!/usr/bin/perl\n\nmy $STARTDIR=\"$HOME/test\";\n\nchdir $STARTDIR;\nmy @files = `find . -type f`;\nchomp @files;\n\nforeach my $file (@files) {\n my $mtime = localtime((stat($file))[9]);\n print qq(touch -m -d \"$mtime\" \"$file\"\\n);\n}\n"
},
{
"answer_id": 128316,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 1,
"selected": false,
"text": "find touch -r"
},
{
"answer_id": 128402,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "touch -t `stat -t '%Y%m%d%H%M.%S' -f '%Sa' TEST1` TEST2\n find . -type f -print -exec stat -t '%Y%m%d%H%M.%S' -f '%Sm' \"{}\" \\; > /tmp/original_dates.txt\n # cat /tmp/original_dates.txt \n./test1\n200809241840.55\n./test2\n200809241849.56\n cat original_dates.txt | (while read FILE && read DATE; do touch -t $DATE \"$FILE\"; done)\n '%Sm' - last modification date\n'%Sc' - creation date\n'%Sa' - last access date\n"
},
{
"answer_id": 16647648,
"author": "marton78",
"author_id": 728847,
"author_profile": "https://Stackoverflow.com/users/728847",
"pm_score": 2,
"selected": false,
"text": "rsync rsync -Prt --size-only original_dir copy_dir\n -P -r -t --size-only"
},
{
"answer_id": 20378408,
"author": "Jaan",
"author_id": 188986,
"author_profile": "https://Stackoverflow.com/users/188986",
"pm_score": 0,
"selected": false,
"text": "find stat maxTime import os\nfrom datetime import datetime\nfrom pytz import utc\n\nfor dirpath, dirnames, filenames in os.walk('./'):\n for name in filenames+dirnames:\n path = os.path.join(dirpath, name)\n # Avoid symlinks because os.path.getmtime and os.utime get and\n # set the time of the pointed file, and in the new directory,\n # the link may have been redirected.\n if not os.path.islink(path):\n mtime = datetime.fromtimestamp(os.path.getmtime(path), utc)\n print(mtime.isoformat()+\" \"+path)\n import datetime, fileinput, os, sys, time\nimport dateutil.parser\nfrom pytz import utc\n\n# Based on\n# http://stackoverflow.com/questions/6999726/python-getting-millis-since-epoch-from-datetime\ndef unix_time(dt):\n epoch = datetime.datetime.fromtimestamp(0, utc)\n delta = dt - epoch\n return delta.total_seconds()\n\nif len(sys.argv) != 2:\n print('Syntax: '+sys.argv[0]+' <maxTime>')\n print(' where <maxTime> an ISO time, e. g. \"2013-12-02T23:00+02:00\".')\n exit(1)\n\n# A file with modification time newer than maxTime is not reset to\n# its original modification time.\nmaxTime = unix_time(dateutil.parser.parse(sys.argv[1]))\n\nfor line in fileinput.input([]):\n (datetimeString, path) = line.rstrip('\\r\\n').split(' ', 1)\n mtime = dateutil.parser.parse(datetimeString)\n if os.path.exists(path) and not os.path.islink(path):\n if os.path.getmtime(path) <= maxTime:\n os.utime(path, (time.time(), unix_time(mtime)))\n python listMTimes.py >/tmp/original_dates.txt\n python setMTimes.py 2013-12-02T23:00+02:00 </tmp/original_dates.txt\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
127,679
|
<p>How do I view the grants (access rights) for a given user in MySQL?</p>
|
[
{
"answer_id": 127683,
"author": "alanc10n",
"author_id": 14059,
"author_profile": "https://Stackoverflow.com/users/14059",
"pm_score": 6,
"selected": true,
"text": "mysql> show grants for 'user'@'host'\n"
},
{
"answer_id": 129533,
"author": "igelkott",
"author_id": 2052165,
"author_profile": "https://Stackoverflow.com/users/2052165",
"pm_score": 5,
"selected": false,
"text": "select * from information_schema.user_privileges where grantee like \"'user'%\";\n"
},
{
"answer_id": 13328263,
"author": "Anita",
"author_id": 1410223,
"author_profile": "https://Stackoverflow.com/users/1410223",
"pm_score": 3,
"selected": false,
"text": "SELECT GRANTEE, PRIVILEGE_TYPE FROM information_schema.user_privileges;\nSELECT User,Host,Db FROM mysql.db;\n"
},
{
"answer_id": 63408415,
"author": "damn sure So",
"author_id": 10770640,
"author_profile": "https://Stackoverflow.com/users/10770640",
"pm_score": 1,
"selected": false,
"text": "SHOW GRANTS [FOR user]\n SHOW GRANTS;\nSHOW GRANTS FOR CURRENT_USER;\nSHOW GRANTS FOR CURRENT_USER();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14059/"
] |
127,684
|
<p>I have a REST Java server implemented with Jersey running on Jetty. It seems that certain browsers (IE7) internally caches all requests made to the server. </p>
<p>What I would like to do is to send a certain HTTP header in the response from the REST server indicating the browser that it shouldn't cache that response, and so will query the server again the next time it needs access to that resource.</p>
<p>Any ideas on how to configure Jersey/Jetty for this?
Or the only way to configure it is client-side?</p>
|
[
{
"answer_id": 127723,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "response.setHeader(\"Pragma\", \"no-cache\");\nresponse.setHeader(\"Cache-Control\", \"no-cache\");\nresponse.setHeader(\"Expires\", \"0\");\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12791/"
] |
127,704
|
<p>I want to write a function that takes an array of letters as an argument and a number of those letters to select. </p>
<p>Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:</p>
<pre><code>8! / ((8 - 3)! * 3!) = 56
</code></pre>
<p>Arrays (or words) in return consisting of 3 letters each.</p>
|
[
{
"answer_id": 127856,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 10,
"selected": true,
"text": "27 = C(6,4) + C(5,3) + C(2,2) + C(1,1) choose (* this will find the [x] combination of a [set] list when taking [k] elements *)\nlet combination_maccaffery set k x =\n (* maximize function -- maximize a that is aCb *)\n (* return largest c where c < i and choose(c,i) <= z *)\n let rec maximize a b x =\n if (choose a b ) <= x then a else maximize (a-1) b x\n in\n let rec iterate n x i = match i with\n | 0 -> []\n | i ->\n let max = maximize n i x in\n max :: iterate n (x - (choose max i)) (i-1)\n in\n if x < 0 then failwith \"errors\" else\n let idxs = iterate (List.length set) x k in\n List.map (List.nth set) (List.sort (-) idxs)\n k let iter_combs n k f =\n let rec iter v s j =\n if j = k then f v\n else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in\n iter [] 0 0\n let fold_combs n k f x =\n let rec loop i s c x =\n if i < n then\n loop (i+1) s c @@\n let c = i::c and s = s + 1 and i = i + 1 in\n if s < k then loop i s c x else f c x\n else x in\n loop 0 0 [] x\n"
},
{
"answer_id": 127898,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 6,
"selected": false,
"text": "void print_combinations(const char *string)\n{\n int i, j, k;\n int len = strlen(string);\n\n for (i = 0; i < len - 2; i++)\n {\n for (j = i + 1; j < len - 1; j++)\n {\n for (k = j + 1; k < len; k++)\n printf(\"%c%c%c\\n\", string[i], string[j], string[k]);\n }\n }\n}\n"
},
{
"answer_id": 127930,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 4,
"selected": false,
"text": "static IEnumerable<string> Combinations(List<string> characters, int length)\n{\n for (int i = 0; i < characters.Count; i++)\n {\n // only want 1 character, just return this one\n if (length == 1)\n yield return characters[i];\n\n // want more than one character, return this one plus all combinations one shorter\n // only use characters after the current one for the rest of the combinations\n else\n foreach (string next in Combinations(characters.GetRange(i + 1, characters.Count - (i + 1)), length - 1))\n yield return characters[i] + next;\n }\n}\n"
},
{
"answer_id": 128369,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 3,
"selected": false,
"text": "SELECT A.Letter, B.Letter, C.Letter\nFROM Alphabet AS A, Alphabet AS B, Alphabet AS C\nWHERE A.Letter<>B.Letter AND A.Letter<>C.Letter AND B.Letter<>C.Letter\nAND A.Letter<B.Letter AND B.Letter<C.Letter\n"
},
{
"answer_id": 128592,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 6,
"selected": false,
"text": "i i k-1 i i i"
},
{
"answer_id": 131810,
"author": "Maciej Hehl",
"author_id": 19939,
"author_profile": "https://Stackoverflow.com/users/19939",
"pm_score": 2,
"selected": false,
"text": "#include <vector>\n#include <stdexcept>\n\ntemplate <typename Fci> // Fci - forward const iterator\nstd::vector<std::vector<Fci> >\nenumerate_combinations(Fci begin, Fci end, unsigned int combination_size)\n{\n if(begin == end && combination_size > 0u)\n throw std::invalid_argument(\"empty set and positive combination size!\");\n std::vector<std::vector<Fci> > result; // empty set of combinations\n if(combination_size == 0u) return result; // there is exactly one combination of\n // size 0 - emty set\n std::vector<Fci> current_combination;\n current_combination.reserve(combination_size + 1u); // I reserve one aditional slot\n // in my vector to store\n // the end sentinel there.\n // The code is cleaner thanks to that\n for(unsigned int i = 0u; i < combination_size && begin != end; ++i, ++begin)\n {\n current_combination.push_back(begin); // Construction of the first combination\n }\n // Since I assume the itarators support only incrementing, I have to iterate over\n // the set to get its size, which is expensive. Here I had to itrate anyway to \n // produce the first cobination, so I use the loop to also check the size.\n if(current_combination.size() < combination_size)\n throw std::invalid_argument(\"combination size > set size!\");\n result.push_back(current_combination); // Store the first combination in the results set\n current_combination.push_back(end); // Here I add mentioned earlier sentinel to\n // simplyfy rest of the code. If I did it \n // earlier, previous statement would get ugly.\n while(true)\n {\n unsigned int i = combination_size;\n Fci tmp; // Thanks to the sentinel I can find first\n do // iterator to change, simply by scaning\n { // from right to left and looking for the\n tmp = current_combination[--i]; // first \"bubble\". The fact, that it's \n ++tmp; // a forward iterator makes it ugly but I\n } // can't help it.\n while(i > 0u && tmp == current_combination[i + 1u]);\n\n // Here is probably my most obfuscated expression.\n // Loop above looks for a \"bubble\". If there is no \"bubble\", that means, that\n // current_combination is the last combination, Expression in the if statement\n // below evaluates to true and the function exits returning result.\n // If the \"bubble\" is found however, the ststement below has a sideeffect of \n // incrementing the first iterator to the left of the \"bubble\".\n if(++current_combination[i] == current_combination[i + 1u])\n return result;\n // Rest of the code sets posiotons of the rest of the iterstors\n // (if there are any), that are to the right of the incremented one,\n // to form next combination\n\n while(++i < combination_size)\n {\n current_combination[i] = current_combination[i - 1u];\n ++current_combination[i];\n }\n // Below is the ugly side of using the sentinel. Well it had to haave some \n // disadvantage. Try without it.\n result.push_back(std::vector<Fci>(current_combination.begin(),\n current_combination.end() - 1));\n }\n}\n"
},
{
"answer_id": 131859,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 3,
"selected": false,
"text": "def missing(miss,src):\n \"Returns the list of items in src not present in miss\"\n return [i for i in src if i not in miss]\n\n\ndef permutation_gen(n,l):\n \"Generates all the permutations of n items of the l list\"\n for i in l:\n if n<=1: yield [i]\n r = [i]\n for j in permutation_gen(n-1,missing([i],l)): yield r+j\n n<len(l) \n for comb in permutation_gen(3,list(\"ABCDEFGH\")):\n print comb \n"
},
{
"answer_id": 339196,
"author": "esiegel",
"author_id": 28486,
"author_profile": "https://Stackoverflow.com/users/28486",
"pm_score": 0,
"selected": false,
"text": "def combinations(list, k):\n \"\"\"Choose combinations of list, choosing k elements(no repeats)\"\"\"\n if len(list) < k:\n return []\n else:\n seq = [i for i in range(k)]\n while seq:\n print [list[index] for index in seq]\n seq = get_next_combination(len(list), k, seq)\n\ndef get_next_combination(num_elements, k, seq):\n index_to_move = find_index_to_move(num_elements, seq)\n if index_to_move == None:\n return None\n else:\n seq[index_to_move] += 1\n\n #for every element past this sequence, move it down\n for i, elem in enumerate(seq[(index_to_move+1):]):\n seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1\n\n return seq\n\ndef find_index_to_move(num_elements, seq):\n \"\"\"Tells which index should be moved\"\"\"\n for rev_index, elem in enumerate(reversed(seq)):\n if elem < (num_elements - rev_index - 1):\n return len(seq) - rev_index - 1\n return None \n"
},
{
"answer_id": 1064091,
"author": "Jesse",
"author_id": 122073,
"author_profile": "https://Stackoverflow.com/users/122073",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM dbo.fn_GetMChooseNCombos('ABCD', 2, '')\n Word\n----\nAB\nAC\nAD\nBC\nBD\nCD\n\n(6 row(s) affected)\n"
},
{
"answer_id": 1617797,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "#include <algorithm>\n\ntemplate <typename Iterator>\nbool next_combination(const Iterator first, Iterator k, const Iterator last)\n{\n /* Credits: Mark Nelson http://marknelson.us */\n if ((first == last) || (first == k) || (last == k))\n return false;\n Iterator i1 = first;\n Iterator i2 = last;\n ++i1;\n if (last == i1)\n return false;\n i1 = last;\n --i1;\n i1 = k;\n --i2;\n while (first != i1)\n {\n if (*--i1 < *i2)\n {\n Iterator j = k;\n while (!(*i1 < *j)) ++j;\n std::iter_swap(i1,j);\n ++i1;\n ++j;\n i2 = k;\n std::rotate(i1,j,last);\n while (last != j)\n {\n ++j;\n ++i2;\n }\n std::rotate(k,i2,last);\n return true;\n }\n }\n std::rotate(first,k,last);\n return false;\n}\n #include <string>\n#include <iostream>\n\nint main()\n{\n std::string s = \"12345\";\n std::size_t comb_size = 3;\n do\n {\n std::cout << std::string(s.begin(), s.begin() + comb_size) << std::endl;\n } while (next_combination(s.begin(), s.begin() + comb_size, s.end()));\n\n return 0;\n}\n 123\n124\n125\n134\n135\n145\n234\n235\n245\n345\n"
},
{
"answer_id": 1898744,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)\n{\n return k == 0 ? new[] { new T[0] } :\n elements.SelectMany((e, i) =>\n elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));\n}\n var result = Combinations(new[] { 1, 2, 3, 4, 5 }, 3);\n 123\n124\n125\n134\n135\n145\n234\n235\n245\n345\n"
},
{
"answer_id": 2438441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "// author: Sourabh Bhat (heySourabh@gmail.com)\n\npublic class Testing\n{\n public static void main(String[] args)\n {\n\n// Test case num = 5, outOf = 8.\n\n int num = 5;\n int outOf = 8;\n int[][] combinations = getCombinations(num, outOf);\n for (int i = 0; i < combinations.length; i++)\n {\n for (int j = 0; j < combinations[i].length; j++)\n {\n System.out.print(combinations[i][j] + \" \");\n }\n System.out.println();\n }\n }\n\n private static int[][] getCombinations(int num, int outOf)\n {\n int possibilities = get_nCr(outOf, num);\n int[][] combinations = new int[possibilities][num];\n int arrayPointer = 0;\n\n int[] counter = new int[num];\n\n for (int i = 0; i < num; i++)\n {\n counter[i] = i;\n }\n breakLoop: while (true)\n {\n // Initializing part\n for (int i = 1; i < num; i++)\n {\n if (counter[i] >= outOf - (num - 1 - i))\n counter[i] = counter[i - 1] + 1;\n }\n\n // Testing part\n for (int i = 0; i < num; i++)\n {\n if (counter[i] < outOf)\n {\n continue;\n } else\n {\n break breakLoop;\n }\n }\n\n // Innermost part\n combinations[arrayPointer] = counter.clone();\n arrayPointer++;\n\n // Incrementing part\n counter[num - 1]++;\n for (int i = num - 1; i >= 1; i--)\n {\n if (counter[i] >= outOf - (num - 1 - i))\n counter[i - 1]++;\n }\n }\n\n return combinations;\n }\n\n private static int get_nCr(int n, int r)\n {\n if(r > n)\n {\n throw new ArithmeticException(\"r is greater then n\");\n }\n long numerator = 1;\n long denominator = 1;\n for (int i = n; i >= r + 1; i--)\n {\n numerator *= i;\n }\n for (int i = 2; i <= n - r; i++)\n {\n denominator *= i;\n }\n\n return (int) (numerator / denominator);\n }\n}\n"
},
{
"answer_id": 2583739,
"author": "Nagendra Gulur",
"author_id": 309877,
"author_profile": "https://Stackoverflow.com/users/309877",
"pm_score": 1,
"selected": false,
"text": "m=(rand()%n)+1; // m will vary from 1 to n\n\nfor (i=0;i<n;i++) a[i]=i+1;\n\n// we want to print all possible C(n,m) combinations of selecting m objects out of n\nprintf(\"Printing C(%d,%d) possible combinations ...\\n\", n,m);\n\n// This is an adhoc algo that keeps m pointers to the next valid combination\nfor (i=0;i<m;i++) p[i]=i; // the p[.] contain indices to the a vector whose elements constitute next combination\n\ndone=false;\nwhile (!done)\n{\n // print combination\n for (i=0;i<m;i++) printf(\"%2d \", a[p[i]]);\n printf(\"\\n\");\n\n // update combination\n // method: start with p[m-1]. try to increment it. if it is already at the end, then try moving p[m-2] ahead.\n // if this is possible, then reset p[m-1] to 1 more than (the new) p[m-2].\n // if p[m-2] can not also be moved, then try p[m-3]. move that ahead. then reset p[m-2] and p[m-1].\n // repeat all the way down to p[0]. if p[0] can not also be moved, then we have generated all combinations.\n j=m-1;\n i=1;\n move_found=false;\n while ((j>=0) && !move_found)\n {\n if (p[j]<(n-i)) \n {\n move_found=true;\n p[j]++; // point p[j] to next index\n for (k=j+1;k<m;k++)\n {\n p[k]=p[j]+(k-j);\n }\n }\n else\n {\n j--;\n i++;\n }\n }\n if (!move_found) done=true;\n}\n"
},
{
"answer_id": 2602811,
"author": "Zack Marrapese",
"author_id": 43222,
"author_profile": "https://Stackoverflow.com/users/43222",
"pm_score": 3,
"selected": false,
"text": "object P26 {\n def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] = \n ls match {\n case Nil => Nil\n case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)\n }\n\n def combinations[A](n: Int, ls: List[A]): List[List[A]] =\n if (n == 0) List(Nil)\n else flatMapSublists(ls) { sl =>\n combinations(n - 1, sl.tail) map {sl.head :: _}\n }\n}\n"
},
{
"answer_id": 2837693,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 6,
"selected": false,
"text": "def choose_iter(elements, length):\n for i in xrange(len(elements)):\n if length == 1:\n yield (elements[i],)\n else:\n for next in choose_iter(elements[i+1:], length-1):\n yield (elements[i],) + next\ndef choose(l, k):\n return list(choose_iter(l, k))\n >>> len(list(choose_iter(\"abcdefgh\",3)))\n56\n"
},
{
"answer_id": 4534968,
"author": "Juan Antonio Cano",
"author_id": 104185,
"author_profile": "https://Stackoverflow.com/users/104185",
"pm_score": 3,
"selected": false,
"text": " static bool nextCombination(int[] num, int n, int k)\n {\n bool finished, changed;\n\n changed = finished = false;\n\n if (k > 0)\n {\n for (int i = k - 1; !finished && !changed; i--)\n {\n if (num[i] < (n - 1) - (k - 1) + i)\n {\n num[i]++;\n if (i < k - 1)\n {\n for (int j = i + 1; j < k; j++)\n {\n num[j] = num[j - 1] + 1;\n }\n }\n changed = true;\n }\n finished = (i == 0);\n }\n }\n\n return changed;\n }\n\n static IEnumerable Combinations<T>(IEnumerable<T> elements, int k)\n {\n T[] elem = elements.ToArray();\n int size = elem.Length;\n\n if (k <= size)\n {\n int[] numbers = new int[k];\n for (int i = 0; i < k; i++)\n {\n numbers[i] = i;\n }\n\n do\n {\n yield return numbers.Select(n => elem[n]);\n }\n while (nextCombination(numbers, size, k));\n }\n }\n static void Main(string[] args)\n {\n int k = 3;\n var t = new[] { \"dog\", \"cat\", \"mouse\", \"zebra\"};\n\n foreach (IEnumerable<string> i in Combinations(t, k))\n {\n Console.WriteLine(string.Join(\",\", i));\n }\n }\n"
},
{
"answer_id": 6724912,
"author": "kes",
"author_id": 335138,
"author_profile": "https://Stackoverflow.com/users/335138",
"pm_score": 1,
"selected": false,
"text": "(defmacro txaat (some-list taken-at-a-time)\n (let* ((vars (reverse (truncate-list '(a b c d e f g h i j) taken-at-a-time))))\n `(\n ,@(loop for i below taken-at-a-time \n for j in vars \n with nested = nil \n finally (return nested) \n do\n (setf \n nested \n `(loop for ,j from\n ,(if (< i (1- (length vars)))\n `(1+ ,(nth (1+ i) vars))\n 0)\n below (- (length ,some-list) ,i)\n ,@(if (equal i 0) \n `(collect \n (list\n ,@(loop for k from (1- taken-at-a-time) downto 0\n append `((nth ,(nth k vars) ,some-list)))))\n `(append ,nested))))))))\n CL-USER> (macroexpand-1 '(txaat '(a b c d) 1))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D))))\nT\nCL-USER> (macroexpand-1 '(txaat '(a b c d) 2))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 2)\n APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D)) (NTH B '(A B C D)))))\nT\nCL-USER> (macroexpand-1 '(txaat '(a b c d) 3))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 3)\n APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 2)\n APPEND (LOOP FOR C FROM (1+ B) TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D))\n (NTH B '(A B C D))\n (NTH C '(A B C D))))))\nT\n\nCL-USER> \n CL-USER> (txaat '(a b c d) 1)\n((A) (B) (C) (D))\nCL-USER> (txaat '(a b c d) 2)\n((A B) (A C) (A D) (B C) (B D) (C D))\nCL-USER> (txaat '(a b c d) 3)\n((A B C) (A B D) (A C D) (B C D))\nCL-USER> (txaat '(a b c d) 4)\n((A B C D))\nCL-USER> (txaat '(a b c d) 5)\nNIL\nCL-USER> (txaat '(a b c d) 0)\nNIL\nCL-USER> \n"
},
{
"answer_id": 8171776,
"author": "Adam",
"author_id": 1052360,
"author_profile": "https://Stackoverflow.com/users/1052360",
"pm_score": 5,
"selected": false,
"text": "function string_recurse(active, rest) {\n if (rest.length == 0) {\n console.log(active);\n } else {\n string_recurse(active + rest.charAt(0), rest.substring(1, rest.length));\n string_recurse(active, rest.substring(1, rest.length));\n }\n}\nstring_recurse(\"\", \"abc\");\n abc\nab\nac\na\nbc\nb\nc\n"
},
{
"answer_id": 8495629,
"author": "Adrian",
"author_id": 1007845,
"author_profile": "https://Stackoverflow.com/users/1007845",
"pm_score": 2,
"selected": false,
"text": "public void run(String data, int howMany){\n choose(data, howMany, new StringBuffer(), 0);\n}\n\n\n//n choose k\nprivate void choose(String data, int k, StringBuffer result, int startIndex){\n if (result.length()==k){\n System.out.println(result.toString());\n return;\n }\n\n for (int i=startIndex; i<data.length(); i++){\n result.append(data.charAt(i));\n choose(data,k,result, i+1);\n result.setLength(result.length()-1);\n }\n}\n"
},
{
"answer_id": 8625691,
"author": "mpounsett",
"author_id": 951589,
"author_profile": "https://Stackoverflow.com/users/951589",
"pm_score": 0,
"selected": false,
"text": "import copy\n\ndef find_combinations( length, set, combinations = None, candidate = None ):\n # recursive function to calculate all unique combinations of unique values\n # from [set], given combinations of [length]. The result is populated\n # into the 'combinations' list.\n #\n if combinations == None:\n combinations = []\n if candidate == None:\n candidate = []\n\n for item in set:\n if item in candidate:\n # this item already appears in the current combination somewhere.\n # skip it\n continue\n\n attempt = copy.deepcopy(candidate)\n attempt.append(item)\n # sorting the subset is what gives us completely unique combinations,\n # so that [1, 2, 3] and [1, 3, 2] will be treated as equals\n attempt.sort()\n\n if len(attempt) < length:\n # the current attempt at finding a new combination is still too\n # short, so add another item to the end of the set\n # yay recursion!\n find_combinations( length, set, combinations, attempt )\n else:\n # the current combination attempt is the right length. If it\n # already appears in the list of found combinations then we'll\n # skip it.\n if attempt in combinations:\n continue\n else:\n # otherwise, we append it to the list of found combinations\n # and move on.\n combinations.append(attempt)\n continue\n return len(combinations)\n size = 3\nset = [1, 2, 3, 4, 5]\nresult = []\n\nnum = find_combinations( size, set, result ) \nprint \"size %d results in %d sets\" % (size, num)\nprint \"result: %s\" % (result,)\n size 3 results in 10 sets\nresult: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]\n set = [\n [ 'vanilla', 'cupcake' ],\n [ 'chocolate', 'pudding' ],\n [ 'vanilla', 'pudding' ],\n [ 'chocolate', 'cookie' ],\n [ 'mint', 'cookie' ]\n]\n"
},
{
"answer_id": 8626006,
"author": "shang",
"author_id": 572606,
"author_profile": "https://Stackoverflow.com/users/572606",
"pm_score": 4,
"selected": false,
"text": "import Data.List\n\ncombinations 0 lst = [[]]\ncombinations n lst = do\n (x:xs) <- tails lst\n rest <- combinations (n-1) xs\n return $ x : rest\n x xs x rest n - 1 xs combinations x : rest x rest x rest > combinations 3 \"abcde\"\n[\"abc\",\"abd\",\"abe\",\"acd\",\"ace\",\"ade\",\"bcd\",\"bce\",\"bde\",\"cde\"]\n > let c = combinations 8 \"abcdefghijklmnopqrstuvwxyz\"\n> take 10 c\n[\"abcdefgh\",\"abcdefgi\",\"abcdefgj\",\"abcdefgk\",\"abcdefgl\",\"abcdefgm\",\"abcdefgn\",\n \"abcdefgo\",\"abcdefgp\",\"abcdefgq\"]\n"
},
{
"answer_id": 8946800,
"author": "Manohar Bhat",
"author_id": 1161324,
"author_profile": "https://Stackoverflow.com/users/1161324",
"pm_score": 1,
"selected": false,
"text": "nCk.Elements 1 n #include<stdio.h>\n#include<stdlib.h>\n\nint nCk(int n,int loopno,int ini,int *a,int k)\n{\n static int count=0;\n int i;\n loopno--;\n if(loopno<0)\n {\n a[k-1]=ini;\n for(i=0;i<k;i++)\n {\n printf(\"%d,\",a[i]);\n }\n printf(\"\\n\");\n count++;\n return 0;\n }\n for(i=ini;i<=n-loopno-1;i++)\n {\n a[k-1-loopno]=i+1;\n nCk(n,loopno,i+1,a,k);\n }\n if(ini==0)\n return count;\n else\n return 0;\n}\n\nvoid main()\n{\n int n,k,*a,count;\n printf(\"Enter the value of n and k\\n\");\n scanf(\"%d %d\",&n,&k);\n a=(int*)malloc(k*sizeof(int));\n count=nCk(n,k,0,a,k);\n printf(\"No of combinations=%d\\n\",count);\n}\n"
},
{
"answer_id": 8986232,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 1,
"selected": false,
"text": "Sub CreateAllCombinationsOfPicksFromPool(ByVal PicksArray() As UInteger, ByVal PicksIndex As UInteger, ByVal PoolArray() As UInteger, ByVal PoolIndex As UInteger)\n If PicksIndex < PicksArray.Length Then\n For i As Integer = PoolIndex To PoolArray.Length - PicksArray.Length + PicksIndex\n PicksArray(PicksIndex) = PoolArray(i)\n CreateAllCombinationsOfPicksFromPool(PicksArray, PicksIndex + 1, PoolArray, i + 1)\n Next\n Else\n ' completed combination. build your collections using PicksArray.\n End If\nEnd Sub\n\n Dim PoolArray() As UInteger = Array.ConvertAll(\"8,10,20,33,41,44,47\".Split(\",\"), Function(u) UInteger.Parse(u))\n Dim nPicks as UInteger = 5\n Dim Picks(nPicks - 1) As UInteger\n CreateAllCombinationsOfPicksFromPool(Picks, 0, PoolArray, 0)\n"
},
{
"answer_id": 9726413,
"author": "Marcus Junius Brutus",
"author_id": 274677,
"author_profile": "https://Stackoverflow.com/users/274677",
"pm_score": 1,
"selected": false,
"text": "lmul a lmul [ l1 ; l2 ; l3] = [a::l1 ; a::l2 ; a::l3]\n lmul List.map (fun x -> h::x)\n let rec choose l n = match l, (List.length l) with \n | _, lsize when n==lsize -> [l] \n | h::t, _ -> (List.map (fun x-> h::x) (choose t (n-1))) @ (choose t n) \n | [], _ -> [] \n"
},
{
"answer_id": 10439025,
"author": "Tsiros.P",
"author_id": 1373560,
"author_profile": "https://Stackoverflow.com/users/1373560",
"pm_score": 0,
"selected": false,
"text": "set = [\"q0\", \"q1\", \"q2\", \"q3\"]\ncollector = []\n\n\nfunction comb(num) {\n results = []\n one_comb = []\n for (i = set.length - 1; i >= 0; --i) {\n tmp = Math.pow(2, i)\n quotient = parseInt(num / tmp)\n results.push(quotient)\n num = num % tmp\n }\n k = 0\n for (i = 0; i < results.length; ++i)\n if (results[i]) {\n ++k\n one_comb.push(set[i])\n }\n if (collector[k] == undefined)\n collector[k] = []\n collector[k].push(one_comb)\n}\n\n\nsum = 0\nfor (i = 0; i < set.length; ++i)\n sum += Math.pow(2, i)\n for (ii = sum; ii > 0; --ii)\n comb(ii)\n cnt = 0\nfor (i = 1; i < collector.length; ++i) {\n n = 0\n for (j = 0; j < collector[i].length; ++j)\n document.write(++cnt, \" - \" + (++n) + \" - \", collector[i][j], \"<br>\")\n document.write(\"<hr>\")\n} \n"
},
{
"answer_id": 10690924,
"author": "oddi",
"author_id": 409706,
"author_profile": "https://Stackoverflow.com/users/409706",
"pm_score": 3,
"selected": false,
"text": "Array.prototype.combs = function(num) {\n\n var str = this,\n length = str.length,\n of = Math.pow(2, length) - 1,\n out, combinations = [];\n\n while(of) {\n\n out = [];\n\n for(var i = 0, y; i < length; i++) {\n\n y = (1 << i);\n\n if(y & of && (y !== of))\n out.push(str[i]);\n\n }\n\n if (out.length >= num) {\n combinations.push(out);\n }\n\n of--;\n }\n\n return combinations;\n}\n"
},
{
"answer_id": 11495614,
"author": "Akseli Palén",
"author_id": 638546,
"author_profile": "https://Stackoverflow.com/users/638546",
"pm_score": 3,
"selected": false,
"text": "k_combinations([1,2,3], 2)\n-> [[1,2], [1,3], [2,3]]\n\ncombinations([1,2,3])\n-> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]\n"
},
{
"answer_id": 11603358,
"author": "Mehmud Abliz",
"author_id": 1544404,
"author_profile": "https://Stackoverflow.com/users/1544404",
"pm_score": 1,
"selected": false,
"text": "void combine(char a[], int N, int M, int m, int start, char result[]) {\n if (0 == m) {\n for (int i = M - 1; i >= 0; i--)\n std::cout << result[i];\n std::cout << std::endl;\n return;\n }\n for (int i = start; i < (N - m + 1); i++) {\n result[m - 1] = a[i];\n combine(a, N, M, m-1, i+1, result);\n }\n}\n\nvoid combine(char a[], int N, int M) {\n char *result = new char[M];\n combine(a, N, M, M, 0, result);\n delete[] result;\n}\n"
},
{
"answer_id": 12447007,
"author": "sss123next",
"author_id": 816494,
"author_profile": "https://Stackoverflow.com/users/816494",
"pm_score": -1,
"selected": false,
"text": "#include <unistd.h>\n#include <stdio.h>\n#include <iconv.h>\n#include <string.h>\n#include <errno.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n int opt = -1, min_len = 0, max_len = 0;\n char ofile[256], fchar[2], tchar[2];\n ofile[0] = 0;\n fchar[0] = 0;\n tchar[0] = 0;\n while((opt = getopt(argc, argv, \"o:f:t:l:L:\")) != -1)\n {\n switch(opt)\n {\n case 'o':\n strncpy(ofile, optarg, 255);\n break;\n case 'f':\n strncpy(fchar, optarg, 1);\n break;\n case 't':\n strncpy(tchar, optarg, 1);\n break;\n case 'l':\n min_len = atoi(optarg);\n break;\n case 'L':\n max_len = atoi(optarg);\n break;\n default:\n printf(\"usage: %s -oftlL\\n\\t-o output file\\n\\t-f from char\\n\\t-t to char\\n\\t-l min seq len\\n\\t-L max seq len\", argv[0]);\n }\n }\nif(max_len < 1)\n{\n printf(\"error, length must be more than 0\\n\");\n return 1;\n}\nif(min_len > max_len)\n{\n printf(\"error, max length must be greater or equal min_length\\n\");\n return 1;\n}\nif((int)fchar[0] > (int)tchar[0])\n{\n printf(\"error, invalid range specified\\n\");\n return 1;\n}\nFILE *out = fopen(ofile, \"w\");\nif(!out)\n{\n printf(\"failed to open input file with error: %s\\n\", strerror(errno));\n return 1;\n}\nint cur_len = min_len;\nwhile(cur_len <= max_len)\n{\n char buf[cur_len];\n for(int i = 0; i < cur_len; i++)\n buf[i] = fchar[0];\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n while(buf[0] != (tchar[0]+1))\n {\n while(buf[cur_len-1] < tchar[0])\n {\n (int)buf[cur_len-1]++;\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n }\n if(cur_len < 2)\n break;\n if(buf[0] == tchar[0])\n {\n bool stop = true;\n for(int i = 1; i < cur_len; i++)\n {\n if(buf[i] != tchar[0])\n {\n stop = false;\n break;\n }\n }\n if(stop)\n break;\n }\n int u = cur_len-2;\n for(; u>=0 && buf[u] >= tchar[0]; u--)\n ;\n (int)buf[u]++;\n for(int i = u+1; i < cur_len; i++)\n buf[i] = fchar[0];\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n }\n cur_len++;\n}\nfclose(out);\nreturn 0;\n}\n"
},
{
"answer_id": 13490411,
"author": "Harry Fisher",
"author_id": 1841487,
"author_profile": "https://Stackoverflow.com/users/1841487",
"pm_score": 4,
"selected": false,
"text": " idx1 = 1\n idx2 = 2\n idx3 = 3\n idx4 = 4\n 1 --- pos.1\n2 --- pos 2\n3 --- pos 3\n4 --- pos 4\n5\n6\n7\netc.\n 1234\n1235\n1236\n1237\n1245\n1246\n1247\n1256\n1257\n1267\netc.\n 01 DATA_ARAY.\n 05 FILLER PIC X(8) VALUE \"VALUE_01\".\n 05 FILLER PIC X(8) VALUE \"VALUE_02\".\n etc.\n01 ARAY_DATA OCCURS 34.\n 05 ARAY_ITEM PIC X(8).\n\n01 OUTPUT_ARAY OCCURS 50000 PIC X(32).\n\n01 MAX_NUM PIC 99 COMP VALUE 34.\n\n01 INDEXXES COMP.\n 05 IDX1 PIC 99.\n 05 IDX2 PIC 99.\n 05 IDX3 PIC 99.\n 05 IDX4 PIC 99.\n 05 OUT_IDX PIC 9(9).\n\n01 WHERE_TO_STOP_SEARCH PIC 99 COMP.\n * Stop the search when IDX1 is on the third last array element:\n\nCOMPUTE WHERE_TO_STOP_SEARCH = MAX_VALUE - 3 \n\nMOVE 1 TO IDX1\n\nPERFORM UNTIL IDX1 > WHERE_TO_STOP_SEARCH\n COMPUTE IDX2 = IDX1 + 1\n PERFORM UNTIL IDX2 > MAX_NUM\n COMPUTE IDX3 = IDX2 + 1\n PERFORM UNTIL IDX3 > MAX_NUM\n COMPUTE IDX4 = IDX3 + 1\n PERFORM UNTIL IDX4 > MAX_NUM\n ADD 1 TO OUT_IDX\n STRING ARAY_ITEM(IDX1)\n ARAY_ITEM(IDX2)\n ARAY_ITEM(IDX3)\n ARAY_ITEM(IDX4)\n INTO OUTPUT_ARAY(OUT_IDX)\n ADD 1 TO IDX4\n END-PERFORM\n ADD 1 TO IDX3\n END-PERFORM\n ADD 1 TO IDX2\n END_PERFORM\n ADD 1 TO IDX1\nEND-PERFORM.\n"
},
{
"answer_id": 14292168,
"author": "Sree Ram",
"author_id": 1268779,
"author_profile": "https://Stackoverflow.com/users/1268779",
"pm_score": 0,
"selected": false,
"text": "#include<iostream>\n#include<string>\nusing namespace std;\n\nvoid combination(string a,string dest){\nint l = dest.length();\nif(a.empty() && l == 3 ){\n cout<<dest<<endl;}\nelse{\n if(!a.empty() && dest.length() < 3 ){\n combination(a.substr(1,a.length()),dest+a[0]);}\n if(!a.empty() && dest.length() <= 3 ){\n combination(a.substr(1,a.length()),dest);}\n }\n\n }\n\n int main(){\n string demo(\"abcd\");\n combination(demo,\"\");\n return 0;\n }\n"
},
{
"answer_id": 14821001,
"author": "Marcus Junius Brutus",
"author_id": 274677,
"author_profile": "https://Stackoverflow.com/users/274677",
"pm_score": 1,
"selected": false,
"text": "(defn select\n ([items]\n (select items 0 (inc (count items))))\n ([items n1 n2]\n (reduce concat\n (map #(select % items)\n (range n1 (inc n2)))))\n ([n items]\n (let [\n lmul (fn [a list-of-lists-of-bs]\n (map #(cons a %) list-of-lists-of-bs))\n ]\n (if (= n (count items))\n (list items)\n (if (empty? items)\n items\n (concat\n (select n (rest items))\n (lmul (first items) (select (dec n) (rest items))))))))) \n user=> (count (select 3 \"abcdefgh\"))\n 56\n user=> (select '(1 2 3 4) 2 3)\n((3 4) (2 4) (2 3) (1 4) (1 3) (1 2) (2 3 4) (1 3 4) (1 2 4) (1 2 3))\n user=> (select '(1 2 3))\n(() (3) (2) (1) (2 3) (1 3) (1 2) (1 2 3))\n"
},
{
"answer_id": 16253878,
"author": "ManAndPC",
"author_id": 2327165,
"author_profile": "https://Stackoverflow.com/users/2327165",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nvoid main(int argc, char *argv[]) {\n const int n = 6; /* The size of the set; for {1, 2, 3, 4} it's 4 */\n const int p = 4; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */\n int comb[40] = {0}; /* comb[i] is the index of the i-th element in the combination */\n\n int i = 0;\n for (int j = 0; j <= n; j++) comb[j] = 0;\n while (i >= 0) {\n if (comb[i] < n + i - p + 1) {\n comb[i]++;\n if (i == p - 1) { for (int j = 0; j < p; j++) printf(\"%d \", comb[j]); printf(\"\\n\"); }\n else { comb[++i] = comb[i - 1]; }\n } else i--; }\n}\n #include <time.h>\n#include <stdio.h>\n\nvoid main(int argc, char *argv[]) {\n const int n = 32; /* The size of the set; for {1, 2, 3, 4} it's 4 */\n const int p = 16; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */\n int comb[40] = {0}; /* comb[i] is the index of the i-th element in the combination */\n\n int c = 0; int i = 0;\n for (int j = 0; j <= n; j++) comb[j] = 0;\n while (i >= 0) {\n if (comb[i] < n + i - p + 1) {\n comb[i]++;\n /* if (i == p - 1) { for (int j = 0; j < p; j++) printf(\"%d \", comb[j]); printf(\"\\n\"); } */\n if (i == p - 1) c++;\n else { comb[++i] = comb[i - 1]; }\n } else i--; }\n printf(\"%d!%d == %d combination(s) in %15.3f second(s)\\n \", p, n, c, clock()/1000.0);\n}\n Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nc:\\Program Files\\lcc\\projects>combination\n16!32 == 601080390 combination(s) in 5.781 second(s)\n\nc:\\Program Files\\lcc\\projects>\n"
},
{
"answer_id": 16256122,
"author": "user935714",
"author_id": 935714,
"author_profile": "https://Stackoverflow.com/users/935714",
"pm_score": 7,
"selected": false,
"text": "import java.util.Arrays;\n\npublic class Combination {\n public static void main(String[] args){\n String[] arr = {\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"};\n combinations2(arr, 3, 0, new String[3]);\n }\n\n static void combinations2(String[] arr, int len, int startPosition, String[] result){\n if (len == 0){\n System.out.println(Arrays.toString(result));\n return;\n } \n for (int i = startPosition; i <= arr.length-len; i++){\n result[result.length - len] = arr[i];\n combinations2(arr, len-1, i+1, result);\n }\n } \n}\n [A, B, C]\n[A, B, D]\n[A, B, E]\n[A, B, F]\n[A, C, D]\n[A, C, E]\n[A, C, F]\n[A, D, E]\n[A, D, F]\n[A, E, F]\n[B, C, D]\n[B, C, E]\n[B, C, F]\n[B, D, E]\n[B, D, F]\n[B, E, F]\n[C, D, E]\n[C, D, F]\n[C, E, F]\n[D, E, F]\n"
},
{
"answer_id": 16504886,
"author": "Jolly1234",
"author_id": 1490677,
"author_profile": "https://Stackoverflow.com/users/1490677",
"pm_score": 0,
"selected": false,
"text": "stack = [] \ndef choose(n,x):\n r(0,0,n+1,x)\n\ndef r(p, c, n,x):\n if x-c == 0:\n print stack\n return\n\n for i in range(p, n-(x-1)+c):\n stack.append(i)\n r(i+1,c+1,n,x)\n stack.pop()\n choose(4,3) \n\n[0, 1, 2]\n[0, 1, 3]\n[0, 1, 4]\n[0, 2, 3]\n[0, 2, 4]\n[0, 3, 4]\n[1, 2, 3]\n[1, 2, 4]\n[1, 3, 4]\n[2, 3, 4]\n"
},
{
"answer_id": 17328465,
"author": "Loourr",
"author_id": 1470897,
"author_profile": "https://Stackoverflow.com/users/1470897",
"pm_score": 0,
"selected": false,
"text": "combinations: (list, n) ->\n permuations = Math.pow(2, list.length) - 1\n out = []\n combinations = []\n\n while permuations\n out = []\n\n for i in [0..list.length]\n y = ( 1 << i )\n if( y & permuations and (y isnt permuations))\n out.push(list[i])\n\n if out.length <= n and out.length > 0\n combinations.push(out)\n\n permuations--\n\n return combinations \n"
},
{
"answer_id": 17474408,
"author": "Vladimir Kostyukov",
"author_id": 554460,
"author_profile": "https://Stackoverflow.com/users/554460",
"pm_score": 1,
"selected": false,
"text": "def combinations[A](s: List[A], k: Int): List[List[A]] = \n if (k > s.length) Nil\n else if (k == 1) s.map(List(_))\n else combinations(s.tail, k - 1).map(s.head :: _) ::: combinations(s.tail, k)\n"
},
{
"answer_id": 17639321,
"author": "monster",
"author_id": 2580880,
"author_profile": "https://Stackoverflow.com/users/2580880",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nunsigned int next_combination(unsigned int *ar, size_t n, unsigned int k)\n{\n unsigned int finished = 0;\n unsigned int changed = 0;\n unsigned int i;\n\n if (k > 0) {\n for (i = k - 1; !finished && !changed; i--) {\n if (ar[i] < (n - 1) - (k - 1) + i) {\n /* Increment this element */\n ar[i]++;\n if (i < k - 1) {\n /* Turn the elements after it into a linear sequence */\n unsigned int j;\n for (j = i + 1; j < k; j++) {\n ar[j] = ar[j - 1] + 1;\n }\n }\n changed = 1;\n }\n finished = i == 0;\n }\n if (!changed) {\n /* Reset to first combination */\n for (i = 0; i < k; i++) {\n ar[i] = i;\n }\n }\n }\n return changed;\n}\n\ntypedef void(*printfn)(const void *, FILE *);\n\nvoid print_set(const unsigned int *ar, size_t len, const void **elements,\n const char *brackets, printfn print, FILE *fptr)\n{\n unsigned int i;\n fputc(brackets[0], fptr);\n for (i = 0; i < len; i++) {\n print(elements[ar[i]], fptr);\n if (i < len - 1) {\n fputs(\", \", fptr);\n }\n }\n fputc(brackets[1], fptr);\n}\n\nint main(void)\n{\n unsigned int numbers[] = { 0, 1, 2 };\n char *elements[] = { \"a\", \"b\", \"c\", \"d\", \"e\" };\n const unsigned int k = sizeof(numbers) / sizeof(unsigned int);\n const unsigned int n = sizeof(elements) / sizeof(const char*);\n\n do {\n print_set(numbers, k, (void*)elements, \"[]\", (printfn)fputs, stdout);\n putchar('\\n');\n } while (next_combination(numbers, n, k));\n getchar();\n return 0;\n}\n"
},
{
"answer_id": 17996834,
"author": "Rick Giuly",
"author_id": 2593312,
"author_profile": "https://Stackoverflow.com/users/2593312",
"pm_score": 5,
"selected": false,
"text": "def comb(sofar, rest, n):\n if n == 0:\n print sofar\n else:\n for i in range(len(rest)):\n comb(sofar + rest[i], rest[i+1:], n-1)\n\n>>> comb(\"\", \"abcde\", 3)\nabc\nabd\nabe\nacd\nace\nade\nbcd\nbce\nbde\ncde\n"
},
{
"answer_id": 20916633,
"author": "llj098",
"author_id": 189961,
"author_profile": "https://Stackoverflow.com/users/189961",
"pm_score": 3,
"selected": false,
"text": "(defn comb [k l]\n (if (= 1 k) (map vector l)\n (apply concat\n (map-indexed\n #(map (fn [x] (conj x %2))\n (comb (dec k) (drop (inc %1) l)))\n l))))\n"
},
{
"answer_id": 22148556,
"author": "rusty",
"author_id": 3141472,
"author_profile": "https://Stackoverflow.com/users/3141472",
"pm_score": 2,
"selected": false,
"text": "let combi n lst =\n let rec comb l c =\n if( List.length c = n) then [c] else\n match l with\n [] -> []\n | (h::t) -> (combi t (h::c))@(combi t c)\n in\n combi lst []\n;;\n"
},
{
"answer_id": 23910252,
"author": "Vladimir M",
"author_id": 3588312,
"author_profile": "https://Stackoverflow.com/users/3588312",
"pm_score": 0,
"selected": false,
"text": "def combis(str:String, k:Int):Array[String] = {\n str.combinations(k).toArray \n}\n println(combis(\"abcd\",2).toList)\n List(ab, ac, ad, bc, bd, cd)\n"
},
{
"answer_id": 24467251,
"author": "Roberto B",
"author_id": 2641447,
"author_profile": "https://Stackoverflow.com/users/2641447",
"pm_score": 0,
"selected": false,
"text": "public static IEnumerable<IEnumerable<T>> Combinations<T>(IEnumerable<T> elements, int k)\n{\n return Combinations(elements.Count(), k).Select(p => p.Select(q => elements.ElementAt(q))); \n} \n\npublic static List<int[]> Combinations(int setLenght, int subSetLenght) //5, 3\n{\n var result = new List<int[]>();\n\n var lastIndex = subSetLenght - 1;\n var dif = setLenght - subSetLenght;\n var prevSubSet = new int[subSetLenght];\n var lastSubSet = new int[subSetLenght];\n for (int i = 0; i < subSetLenght; i++)\n {\n prevSubSet[i] = i;\n lastSubSet[i] = i + dif;\n }\n\n while(true)\n {\n //add subSet ad result set\n var n = new int[subSetLenght];\n for (int i = 0; i < subSetLenght; i++)\n n[i] = prevSubSet[i];\n\n result.Add(n);\n\n if (prevSubSet[0] >= lastSubSet[0])\n break;\n\n //start at index 1 because index 0 is checked and breaking in the current loop\n int j = 1;\n for (; j < subSetLenght; j++)\n {\n if (prevSubSet[j] >= lastSubSet[j])\n {\n prevSubSet[j - 1]++;\n\n for (int p = j; p < subSetLenght; p++)\n prevSubSet[p] = prevSubSet[p - 1] + 1;\n\n break;\n }\n }\n\n if (j > lastIndex)\n prevSubSet[lastIndex]++;\n }\n\n return result;\n}\n"
},
{
"answer_id": 26060071,
"author": "user2648503",
"author_id": 2648503,
"author_profile": "https://Stackoverflow.com/users/2648503",
"pm_score": 2,
"selected": false,
"text": "Array.prototype.combine=function combine(k){ \n var toCombine=this;\n var last;\n function combi(n,comb){ \n var combs=[];\n for ( var x=0,y=comb.length;x<y;x++){\n for ( var l=0,m=toCombine.length;l<m;l++){ \n combs.push(comb[x]+toCombine[l]); \n }\n }\n if (n<k-1){\n n++;\n combi(n,combs);\n } else{last=combs;}\n }\n combi(1,toCombine);\n return last;\n}\n// Example:\n// var toCombine=['a','b','c'];\n// var results=toCombine.combine(4);\n"
},
{
"answer_id": 27311621,
"author": "android927",
"author_id": 4144062,
"author_profile": "https://Stackoverflow.com/users/4144062",
"pm_score": 0,
"selected": false,
"text": "void r_nCr(unsigned int startNum, unsigned int bitVal, unsigned int testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)\n{\n unsigned int n = (startNum - bitVal) << 1;\n n += bitVal ? 1 : 0;\n\n for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s\n cout << (n >> (i - 1) & 1);\n cout << endl;\n\n if (!(n & testNum) && n != startNum)\n r_nCr(n, bitVal, testNum);\n\n if (bitVal && bitVal < testNum)\n r_nCr(startNum, bitVal >> 1, testNum);\n}\n"
},
{
"answer_id": 28032275,
"author": "Mockingbird",
"author_id": 2247040,
"author_profile": "https://Stackoverflow.com/users/2247040",
"pm_score": 0,
"selected": false,
"text": "public static List<List<int>> GetSubsetsOfSizeK(List<int> lInputSet, int k)\n {\n List<List<int>> lSubsets = new List<List<int>>();\n GetSubsetsOfSizeK_rec(lInputSet, k, 0, new List<int>(), lSubsets);\n return lSubsets;\n }\n\npublic static void GetSubsetsOfSizeK_rec(List<int> lInputSet, int k, int i, List<int> lCurrSet, List<List<int>> lSubsets)\n {\n if (lCurrSet.Count == k)\n {\n lSubsets.Add(lCurrSet);\n return;\n }\n\n if (i >= lInputSet.Count)\n return;\n\n List<int> lWith = new List<int>(lCurrSet);\n List<int> lWithout = new List<int>(lCurrSet);\n lWith.Add(lInputSet[i++]);\n\n GetSubsetsOfSizeK_rec(lInputSet, k, i, lWith, lSubsets);\n GetSubsetsOfSizeK_rec(lInputSet, k, i, lWithout, lSubsets);\n }\n GetSubsetsOfSizeK(set of type List<int>, integer k)"
},
{
"answer_id": 28295259,
"author": "quAnton",
"author_id": 2621976,
"author_profile": "https://Stackoverflow.com/users/2621976",
"pm_score": 2,
"selected": false,
"text": "$array = array(1,2,3,4,5);\n\n$array_result = NULL;\n\n$array_general = NULL;\n\nfunction combinations($array, $len, $start_position, $result_array, $result_len, &$general_array)\n{\n if($len == 0)\n {\n $general_array[] = $result_array;\n return;\n }\n\n for ($i = $start_position; $i <= count($array) - $len; $i++)\n {\n $result_array[$result_len - $len] = $array[$i];\n combinations($array, $len-1, $i+1, $result_array, $result_len, $general_array);\n }\n} \n\ncombinations($array, 3, 0, $array_result, 3, $array_general);\n\necho \"<pre>\";\nprint_r($array_general);\necho \"</pre>\";\n var newArray = [1, 2, 3, 4, 5];\nvar arrayResult = [];\nvar arrayGeneral = [];\n\nfunction combinations(newArray, len, startPosition, resultArray, resultLen, arrayGeneral) {\n if(len === 0) {\n var tempArray = [];\n resultArray.forEach(value => tempArray.push(value));\n arrayGeneral.push(tempArray);\n return;\n }\n for (var i = startPosition; i <= newArray.length - len; i++) {\n resultArray[resultLen - len] = newArray[i];\n combinations(newArray, len-1, i+1, resultArray, resultLen, arrayGeneral);\n }\n} \n\ncombinations(newArray, 3, 0, arrayResult, 3, arrayGeneral);\n\nconsole.log(arrayGeneral);\n"
},
{
"answer_id": 28307464,
"author": "android927",
"author_id": 4144062,
"author_profile": "https://Stackoverflow.com/users/4144062",
"pm_score": 0,
"selected": false,
"text": "void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)\n{\n unsigned int n = (startNum - bitVal) << 1;\n n += bitVal ? 1 : 0;\n\n for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s\n cout << (n >> (i - 1) & 1);\n cout << endl;\n\n if (!(n & testNum) && n != startNum)\n r_nCr(n, bitVal, testNum);\n\n if (bitVal && bitVal < testNum)\n r_nCr(startNum, bitVal >> 1, testNum);\n}\n"
},
{
"answer_id": 29715947,
"author": "Nathan Schmidt",
"author_id": 4725365,
"author_profile": "https://Stackoverflow.com/users/4725365",
"pm_score": 3,
"selected": false,
"text": "def yield_combos(n,k):\n # n is set size, k is combo size\n\n i = 0\n a = [0]*k\n\n while i > -1:\n for j in range(i+1, k):\n a[j] = a[j-1]+1\n i=j\n yield a\n while a[i] == i + n - k:\n i -= 1\n a[i] += 1\n"
},
{
"answer_id": 30225393,
"author": "Wormbo",
"author_id": 1331011,
"author_profile": "https://Stackoverflow.com/users/1331011",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<T[]> Combinations<T>(this T[] values, int k)\n{\n if (k < 0 || values.Length < k)\n yield break; // invalid parameters, no combinations possible\n\n // generate the initial combination indices\n var combIndices = new int[k];\n for (var i = 0; i < k; i++)\n {\n combIndices[i] = i;\n }\n\n while (true)\n {\n // return next combination\n var combination = new T[k];\n for (var i = 0; i < k; i++)\n {\n combination[i] = values[combIndices[i]];\n }\n yield return combination;\n\n // find first index to update\n var indexToUpdate = k - 1;\n while (indexToUpdate >= 0 && combIndices[indexToUpdate] >= values.Length - k + indexToUpdate)\n {\n indexToUpdate--;\n }\n\n if (indexToUpdate < 0)\n yield break; // done\n\n // update combination indices\n for (var combIndex = combIndices[indexToUpdate] + 1; indexToUpdate < k; indexToUpdate++, combIndex++)\n {\n combIndices[indexToUpdate] = combIndex;\n }\n }\n}\n foreach (var combination in new[] {'a', 'b', 'c', 'd', 'e'}.Combinations(3))\n{\n System.Console.WriteLine(String.Join(\" \", combination));\n}\n a b c\na b d\na b e\na c d\na c e\na d e\nb c d\nb c e\nb d e\nc d e\n"
},
{
"answer_id": 30278842,
"author": "Akkuma",
"author_id": 814690,
"author_profile": "https://Stackoverflow.com/users/814690",
"pm_score": 2,
"selected": false,
"text": "function combinations(arr, size) {\n var len = arr.length;\n\n if (size > len) return [];\n if (!size) return [[]];\n if (size == len) return [arr];\n\n return arr.reduce(function (acc, val, i) {\n var res = combinations(arr.slice(i + 1), size - 1)\n .map(function (comb) { return [val].concat(comb); });\n \n return acc.concat(res);\n }, []);\n}\n\nvar combs = combinations([1,2,3,4,5,6,7,8],3);\ncombs.map(function (comb) {\n document.body.innerHTML += comb.toString() + '<br />';\n});\n\ndocument.body.innerHTML += '<br /> Total combinations = ' + combs.length;"
},
{
"answer_id": 34472590,
"author": "Jingguo Yao",
"author_id": 431698,
"author_profile": "https://Stackoverflow.com/users/431698",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid visit(int* c, int t) \n{\n // for (int j = 1; j <= t; j++)\n for (int j = t; j > 0; j--)\n printf(\"%d \", c[j]);\n printf(\"\\n\");\n}\n\nint* initialize(int n, int t) \n{\n // c[0] not used\n int *c = (int*) malloc((t + 3) * sizeof(int));\n\n for (int j = 1; j <= t; j++)\n c[j] = j - 1;\n c[t+1] = n;\n c[t+2] = 0;\n return c;\n}\n\nvoid comb(int n, int t) \n{\n int *c = initialize(n, t);\n int j;\n\n for (;;) {\n visit(c, t);\n j = 1;\n while (c[j]+1 == c[j+1]) {\n c[j] = j - 1;\n ++j;\n }\n if (j > t) \n return;\n ++c[j];\n }\n free(c);\n}\n\nint main(int argc, char *argv[])\n{\n comb(5, 3);\n return 0;\n}\n"
},
{
"answer_id": 34588366,
"author": "Miraan Tabrez",
"author_id": 4733036,
"author_profile": "https://Stackoverflow.com/users/4733036",
"pm_score": 2,
"selected": false,
"text": "(int k) (List<T> list) (List<List<T>>) public static <T> List<List<T>> getCombinations(int k, List<T> list) {\n List<List<T>> combinations = new ArrayList<List<T>>();\n if (k == 0) {\n combinations.add(new ArrayList<T>());\n return combinations;\n }\n for (int i = 0; i < list.size(); i++) {\n T element = list.get(i);\n List<T> rest = getSublist(list, i+1);\n for (List<T> previous : getCombinations(k-1, rest)) {\n previous.add(element);\n combinations.add(previous);\n }\n }\n return combinations;\n}\n\npublic static <T> List<T> getSublist(List<T> list, int i) {\n List<T> sublist = new ArrayList<T>();\n for (int j = i; j < list.size(); j++) {\n sublist.add(list.get(j));\n }\n return sublist;\n}\n"
},
{
"answer_id": 36842371,
"author": "Lor",
"author_id": 3271476,
"author_profile": "https://Stackoverflow.com/users/3271476",
"pm_score": 0,
"selected": false,
"text": "combo procedure combinata (n, k :integer; producer :oneintproc);\n\n procedure combo (ndx, nbr, len, lnd :integer);\n begin\n for nbr := nbr to len do begin\n productarray[ndx] := nbr;\n if len < lnd then\n combo(ndx+1,nbr+1,len+1,lnd)\n else\n producer(k);\n end;\n end;\n\n begin\n combo (0, 0, n-k, n-1);\n end;\n"
},
{
"answer_id": 37704231,
"author": "Robert Johnstone",
"author_id": 563247,
"author_profile": "https://Stackoverflow.com/users/563247",
"pm_score": 1,
"selected": false,
"text": "class Combinations implements Iterator\n{\n protected $c = null;\n protected $s = null;\n protected $n = 0;\n protected $k = 0;\n protected $pos = 0;\n\n function __construct($s, $k) {\n if(is_array($s)) {\n $this->s = array_values($s);\n $this->n = count($this->s);\n } else {\n $this->s = (string) $s;\n $this->n = strlen($this->s);\n }\n $this->k = $k;\n $this->rewind();\n }\n function key() {\n return $this->pos;\n }\n function current() {\n $r = array();\n for($i = 0; $i < $this->k; $i++)\n $r[] = $this->s[$this->c[$i]];\n return is_array($this->s) ? $r : implode('', $r);\n }\n function next() {\n if($this->_next())\n $this->pos++;\n else\n $this->pos = -1;\n }\n function rewind() {\n $this->c = range(0, $this->k);\n $this->pos = 0;\n }\n function valid() {\n return $this->pos >= 0;\n }\n\n protected function _next() {\n $i = $this->k - 1;\n while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i)\n $i--;\n if($i < 0)\n return false;\n $this->c[$i]++;\n while($i++ < $this->k - 1)\n $this->c[$i] = $this->c[$i - 1] + 1;\n return true;\n }\n}\n\n\nforeach(new Combinations(\"1234567\", 5) as $substring)\n echo $substring, ' ';\n"
},
{
"answer_id": 41153426,
"author": "julius",
"author_id": 242813,
"author_profile": "https://Stackoverflow.com/users/242813",
"pm_score": 0,
"selected": false,
"text": " public class CombinationsGen {\n private final int n;\n private final int k;\n private int[] buf;\n\n public CombinationsGen(int n, int k) {\n this.n = n;\n this.k = k;\n }\n\n public void combine(Consumer<int[]> consumer) {\n buf = new int[k];\n rec(0, 0, consumer);\n }\n\n private void rec(int index, int next, Consumer<int[]> consumer) {\n int max = n - index;\n\n if (index == k - 1) {\n for (int i = 0; i < max && next < n; i++) {\n buf[index] = next;\n next++;\n consumer.accept(buf);\n }\n } else {\n for (int i = 0; i < max && next + index < n; i++) {\n buf[index] = next;\n next++;\n rec(index + 1, next, consumer);\n }\n }\n }\n}\n CombinationsGen gen = new CombinationsGen(5, 2);\n\n AtomicInteger total = new AtomicInteger();\n gen.combine(arr -> {\n System.out.println(Arrays.toString(arr));\n total.incrementAndGet();\n });\n System.out.println(total);\n [0, 1]\n[0, 2]\n[0, 3]\n[0, 4]\n[1, 2]\n[1, 3]\n[1, 4]\n[2, 3]\n[2, 4]\n[3, 4]\n10\n"
},
{
"answer_id": 41344322,
"author": "krzydyn",
"author_id": 2312064,
"author_profile": "https://Stackoverflow.com/users/2312064",
"pm_score": -1,
"selected": false,
"text": "next next() public class Combinations {\n final int pos[];\n final List<Object> set;\n\n public Combinations(List<?> l, int k) {\n pos = new int[k];\n set=new ArrayList<Object>(l);\n reset();\n }\n public void reset() {\n for (int i=0; i < pos.length; ++i) pos[i]=i;\n }\n public boolean next() {\n int i = pos.length-1;\n for (int maxpos = set.size()-1; pos[i] >= maxpos; --maxpos) {\n if (i==0) return false;\n --i;\n }\n ++pos[i];\n while (++i < pos.length)\n pos[i]=pos[i-1]+1;\n return true;\n }\n\n public void getSelection(List<?> l) {\n @SuppressWarnings(\"unchecked\")\n List<Object> ll = (List<Object>)l;\n if (ll.size()!=pos.length) {\n ll.clear();\n for (int i=0; i < pos.length; ++i)\n ll.add(set.get(pos[i]));\n }\n else {\n for (int i=0; i < pos.length; ++i)\n ll.set(i, set.get(pos[i]));\n }\n }\n}\n static void main(String[] args) {\n List<Character> l = new ArrayList<Character>();\n for (int i=0; i < 32; ++i) l.add((char)('a'+i));\n Combinations comb = new Combinations(l,5);\n int n=0;\n do {\n ++n;\n comb.getSelection(l);\n //Log.debug(\"%d: %s\", n, l.toString());\n } while (comb.next());\n Log.debug(\"num = %d\", n);\n}\n"
},
{
"answer_id": 41444596,
"author": "klimenkov",
"author_id": 2580443,
"author_profile": "https://Stackoverflow.com/users/2580443",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n\nvoid backtrack(int* numbers, int n, int k, int i, int s)\n{\n if (i == k)\n {\n for (int j = 0; j < k; ++j)\n {\n std::cout << numbers[j];\n }\n std::cout << std::endl;\n\n return;\n }\n\n if (s > n)\n {\n return;\n }\n\n numbers[i] = s;\n backtrack(numbers, n, k, i + 1, s + 1);\n backtrack(numbers, n, k, i, s + 1);\n}\n\nint main(int argc, char* argv[])\n{\n int n = 5;\n int k = 3;\n\n int* numbers = new int[k];\n\n backtrack(numbers, n, k, 0, 1);\n\n delete[] numbers;\n\n return 0;\n}\n"
},
{
"answer_id": 42000025,
"author": "Oleksandr Matviienko",
"author_id": 5658393,
"author_profile": "https://Stackoverflow.com/users/5658393",
"pm_score": 1,
"selected": false,
"text": " static List<List<T>> GetCombinations<T>(List<T> originalItems, int combinationLength)\n {\n if (combinationLength < 1)\n {\n return null;\n }\n\n return CreateCombinations<T>(new List<T>(), 0, combinationLength, originalItems);\n }\n\n static List<List<T>> CreateCombinations<T>(List<T> initialCombination, int startIndex, int length, List<T> originalItems)\n {\n List<List<T>> combinations = new List<List<T>>();\n for (int i = startIndex; i < originalItems.Count - length + 1; i++)\n {\n List<T> newCombination = new List<T>(initialCombination);\n newCombination.Add(originalItems[i]);\n if (length > 1)\n {\n List<List<T>> newCombinations = CreateCombinations(newCombination, i + 1, length - 1, originalItems);\n combinations.AddRange(newCombinations);\n }\n else\n {\n combinations.Add(newCombination);\n }\n }\n\n return combinations;\n }\n List<char> initialArray = new List<char>() { 'a','b','c','d'};\n int combinationLength = 3;\n List<List<char>> combinations = GetCombinations(initialArray, combinationLength);\n"
},
{
"answer_id": 42190945,
"author": "jacoblambert",
"author_id": 3097458,
"author_profile": "https://Stackoverflow.com/users/3097458",
"pm_score": 3,
"selected": false,
"text": "void Main()\n{\n var set = new [] {\"A\", \"B\", \"C\", \"D\" }; //, \"E\", \"F\", \"G\", \"H\", \"I\", \"J\" };\n\n var kElement = 2;\n\n for(var i = 1; i < Math.Pow(2, set.Length); i++) {\n var result = Convert.ToString(i, 2).PadLeft(set.Length, '0');\n var cnt = Regex.Matches(Regex.Escape(result), \"1\").Count; \n if (cnt == kElement) {\n for(int j = 0; j < set.Length; j++)\n if ( Char.GetNumericValue(result[j]) == 1)\n Console.Write(set[j]);\n Console.WriteLine();\n }\n }\n}\n"
},
{
"answer_id": 44036562,
"author": "Oleksandr Knyga",
"author_id": 2628125,
"author_profile": "https://Stackoverflow.com/users/2628125",
"pm_score": 3,
"selected": false,
"text": "function initializePointers($cnt) {\n $pointers = [];\n\n for($i=0; $i<$cnt; $i++) {\n $pointers[] = $i;\n }\n\n return $pointers; \n}\n\nfunction incrementPointers(&$pointers, &$arrLength) {\n for($i=0; $i<count($pointers); $i++) {\n $currentPointerIndex = count($pointers) - $i - 1;\n $currentPointer = $pointers[$currentPointerIndex];\n\n if($currentPointer < $arrLength - $i - 1) {\n ++$pointers[$currentPointerIndex];\n\n for($j=1; ($currentPointerIndex+$j)<count($pointers); $j++) {\n $pointers[$currentPointerIndex+$j] = $pointers[$currentPointerIndex]+$j;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nfunction getDataByPointers(&$arr, &$pointers) {\n $data = [];\n\n for($i=0; $i<count($pointers); $i++) {\n $data[] = $arr[$pointers[$i]];\n }\n\n return $data;\n}\n\nfunction getCombinations($arr, $cnt)\n{\n $len = count($arr);\n $result = [];\n $pointers = initializePointers($cnt);\n\n do {\n $result[] = getDataByPointers($arr, $pointers);\n } while(incrementPointers($pointers, count($arr)));\n\n return $result;\n}\n\n$result = getCombinations([0, 1, 2, 3, 4, 5], 3);\nprint_r($result);\n"
},
{
"answer_id": 44786122,
"author": "Sarthak Gupta",
"author_id": 6997153,
"author_profile": "https://Stackoverflow.com/users/6997153",
"pm_score": 1,
"selected": false,
"text": "print ab (str[0] , str[1]) print ac (str[0] , str[2]) print ab (str[1] , str[2]) public class StringCombinationK { \n static void combk(String s , int k){\n int n = s.length();\n int num = 1<<n;\n int j=0;\n int count=0;\n\n for(int i=0;i<num;i++){\n if (countSet(i)==k){\n setBits(i,j,s);\n count++;\n System.out.println();\n }\n }\n\n System.out.println(count);\n }\n\n static void setBits(int i,int j,String s){ // print the corresponding string value,j represent the index of set bit\n if(i==0){\n return;\n }\n\n if(i%2==1){\n System.out.print(s.charAt(j)); \n }\n\n setBits(i/2,j+1,s);\n }\n\n static int countSet(int i){ //count number of set bits\n if( i==0){\n return 0;\n }\n\n return (i%2==0? 0:1) + countSet(i/2);\n }\n\n public static void main(String[] arhs){\n String s = \"abcdefgh\";\n int k=3;\n combk(s,k);\n }\n}\n"
},
{
"answer_id": 48917740,
"author": "Zeta",
"author_id": 6626185,
"author_profile": "https://Stackoverflow.com/users/6626185",
"pm_score": 0,
"selected": false,
"text": "char ar[] = \"0ABCDEFGH\";\nnCr ncr(8, 3);\nwhile(ncr.next()) {\n for(int i=0; i<ncr.size(); i++) cout << ar[ncr[i]];\n cout << ' ';\n}\n #pragma once\n#include <exception>\n\nclass NRexception : public std::exception\n{\npublic:\n virtual const char* what() const throw() {\n return \"Combination : N, R should be positive integer!!\";\n }\n};\n\nclass Combination\n{\npublic:\n Combination(int n, int r);\n virtual ~Combination() { delete [] ar;}\n int& operator[](unsigned i) {return ar[i];}\n bool next();\n int size() {return r;}\n static int factorial(int n);\n\nprotected:\n int* ar;\n int n, r;\n};\n\nclass nCr : public Combination\n{\npublic: \n nCr(int n, int r);\n bool next();\n int count() const;\n};\n\nclass nTr : public Combination\n{\npublic:\n nTr(int n, int r);\n bool next();\n int count() const;\n};\n\nclass nHr : public nTr\n{\npublic:\n nHr(int n, int r) : nTr(n,r) {}\n bool next();\n int count() const;\n};\n\nclass nPr : public Combination\n{\npublic:\n nPr(int n, int r);\n virtual ~nPr() {delete [] on;}\n bool next();\n void rewind();\n int count() const;\n\nprivate:\n bool* on;\n void inc_ar(int i);\n};\n #include \"combi.h\"\n#include <set>\n#include<cmath>\n\nCombination::Combination(int n, int r)\n{\n //if(n < 1 || r < 1) throw NRexception();\n ar = new int[r];\n this->n = n;\n this->r = r;\n}\n\nint Combination::factorial(int n) \n{\n return n == 1 ? n : n * factorial(n-1);\n}\n\nint nPr::count() const\n{\n return factorial(n)/factorial(n-r);\n}\n\nint nCr::count() const\n{\n return factorial(n)/factorial(n-r)/factorial(r);\n}\n\nint nTr::count() const\n{\n return pow(n, r);\n}\n\nint nHr::count() const\n{\n return factorial(n+r-1)/factorial(n-1)/factorial(r);\n}\n\nnCr::nCr(int n, int r) : Combination(n, r)\n{\n if(r == 0) return;\n for(int i=0; i<r-1; i++) ar[i] = i + 1;\n ar[r-1] = r-1;\n}\n\nnTr::nTr(int n, int r) : Combination(n, r)\n{\n for(int i=0; i<r-1; i++) ar[i] = 1;\n ar[r-1] = 0;\n}\n\nbool nCr::next()\n{\n if(r == 0) return false;\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n-r+2+i) {\n if(--i == -1) return false;\n ar[i]++;\n }\n while(i < r-1) ar[i+1] = ar[i++] + 1;\n return true;\n}\n\nbool nTr::next()\n{\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n+1) {\n ar[i] = 1;\n if(--i == -1) return false;\n ar[i]++;\n }\n return true;\n}\n\nbool nHr::next()\n{\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n+1) {\n if(--i == -1) return false;\n ar[i]++;\n }\n while(i < r-1) ar[i+1] = ar[i++];\n return true;\n}\n\nnPr::nPr(int n, int r) : Combination(n, r)\n{\n on = new bool[n+2];\n for(int i=0; i<n+2; i++) on[i] = false;\n for(int i=0; i<r; i++) {\n ar[i] = i + 1;\n on[i] = true;\n }\n ar[r-1] = 0;\n}\n\nvoid nPr::rewind()\n{\n for(int i=0; i<r; i++) {\n ar[i] = i + 1;\n on[i] = true;\n }\n ar[r-1] = 0;\n}\n\nbool nPr::next()\n{ \n inc_ar(r-1);\n\n int i = r-1;\n while(ar[i] == n+1) {\n if(--i == -1) return false;\n inc_ar(i);\n }\n while(i < r-1) {\n ar[++i] = 0;\n inc_ar(i);\n }\n return true;\n}\n\nvoid nPr::inc_ar(int i)\n{\n on[ar[i]] = false;\n while(on[++ar[i]]);\n if(ar[i] != n+1) on[ar[i]] = true;\n}\n"
},
{
"answer_id": 49019171,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 0,
"selected": false,
"text": "class CombinationsIterator\n{\nprivate:\n int input_array[]; // 1 2 3 4 5\n int index_array[]; // i j k\n int m_elements; // N\n int m_indices; // K\n\npublic:\n CombinationsIterator(int &src_data[], int k)\n {\n m_indices = k;\n m_elements = ArraySize(src_data);\n ArrayCopy(input_array, src_data);\n ArrayResize(index_array, m_indices);\n\n // create initial combination (0..k-1)\n for (int i = 0; i < m_indices; i++)\n {\n index_array[i] = i;\n }\n }\n\n // https://stackoverflow.com/questions/5076695\n // bool next_combination(int &item[], int k, int N)\n bool advance()\n {\n int N = m_elements;\n for (int i = m_indices - 1; i >= 0; --i)\n {\n if (index_array[i] < --N)\n {\n ++index_array[i];\n for (int j = i + 1; j < m_indices; ++j)\n {\n index_array[j] = index_array[j - 1] + 1;\n }\n return true;\n }\n }\n return false;\n }\n\n void getItems(int &items[])\n {\n // fill items[] from input array\n for (int i = 0; i < m_indices; i++)\n {\n items[i] = input_array[index_array[i]];\n }\n }\n}; //+------------------------------------------------------------------+\n//| |\n//+------------------------------------------------------------------+\n// driver program to test above class\n\n#define N 5\n#define K 3\n\nvoid OnStart()\n{\n int myset[N] = {1, 2, 3, 4, 5};\n int items[K];\n\n CombinationsIterator comboIt(myset, K);\n\n do\n {\n comboIt.getItems(items);\n\n printf(\"%s\", ArrayToString(items));\n\n } while (comboIt.advance());\n\n} Output:\n1 2 3 \n1 2 4 \n1 2 5 \n1 3 4 \n1 3 5 \n1 4 5 \n2 3 4 \n2 3 5 \n2 4 5 \n3 4 5"
},
{
"answer_id": 51341056,
"author": "Max Leizerovich",
"author_id": 5210321,
"author_profile": "https://Stackoverflow.com/users/5210321",
"pm_score": 0,
"selected": false,
"text": "function getAllCombinations(n, k, f1) {\n indexes = Array(k);\n for (let i =0; i< k; i++) {\n indexes[i] = i;\n }\n var total = 1;\n f1(indexes);\n while (indexes[0] !== n-k) {\n total++;\n getNext(n, indexes);\n f1(indexes);\n }\n return {total};\n}\n\nfunction getNext(n, vec) {\n const k = vec.length;\n vec[k-1]++;\n for (var i=0; i<k; i++) {\n var currentIndex = k-i-1;\n if (vec[currentIndex] === n - i) {\n var nextIndex = k-i-2;\n vec[nextIndex]++;\n vec[currentIndex] = vec[nextIndex] + 1;\n }\n }\n\n for (var i=1; i<k; i++) {\n if (vec[i] === n - (k-i - 1)) {\n vec[i] = vec[i-1] + 1;\n }\n }\n return vec;\n} \n\n\n\nlet start = new Date();\nlet result = getAllCombinations(10, 3, indexes => console.log(indexes)); \nlet runTime = new Date() - start; \n\nconsole.log({\nresult, runTime\n});"
},
{
"answer_id": 55273474,
"author": "Paulo Mendes",
"author_id": 861757,
"author_profile": "https://Stackoverflow.com/users/861757",
"pm_score": 1,
"selected": false,
"text": "body lst var (defmacro do-combinations ((var lst num) &body body)\n (loop with syms = (loop repeat num collect (gensym))\n for i on syms\n for k = `(loop for ,(car i) on (cdr ,(cadr i))\n do (let ((,var (list ,@(reverse syms)))) (progn ,@body)))\n then `(loop for ,(car i) on ,(if (cadr i) `(cdr ,(cadr i)) lst) do ,k)\n finally (return k)))\n (macroexpand-1 '(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p))))\n\n(LOOP FOR #:G3217 ON '(1 2 3 4 5 6 7) DO\n (LOOP FOR #:G3216 ON (CDR #:G3217) DO\n (LOOP FOR #:G3215 ON (CDR #:G3216) DO\n (LOOP FOR #:G3214 ON (CDR #:G3215) DO\n (LET ((P (LIST #:G3217 #:G3216 #:G3215 #:G3214)))\n (PROGN (PPRINT (MAPCAR #'CAR P))))))))\n\n(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p)))\n\n(1 2 3 4)\n(1 2 3 5)\n(1 2 3 6)\n...\n body"
},
{
"answer_id": 56141308,
"author": "luochen1990",
"author_id": 1608276,
"author_profile": "https://Stackoverflow.com/users/1608276",
"pm_score": 1,
"selected": false,
"text": "import Data.Semigroup\nimport Data.Monoid\n\ndata Comb = MkComb {count :: Int, combinations :: [[Int]]} deriving (Show, Eq, Ord)\n\ninstance Semigroup Comb where\n (MkComb c1 cs1) <> (MkComb c2 cs2) = MkComb (c1 + c2) (cs1 ++ cs2)\n\ninstance Monoid Comb where\n mempty = MkComb 0 []\n\naddElem :: Comb -> Int -> Comb\naddElem (MkComb c cs) x = MkComb c (map (x :) cs)\n\ncomb :: Int -> Int -> Comb\ncomb n k | n < 0 || k < 0 = error \"error in `comb n k`, n and k should be natural number\"\ncomb n k | k == 0 || k == n = MkComb 1 [(take k [k-1,k-2..0])]\ncomb n k | n < k = mempty\ncomb n k = comb (n-1) k <> (comb (n-1) (k-1) `addElem` (n-1))\n *Main> comb 0 1\nMkComb {count = 0, combinations = []}\n\n*Main> comb 0 0\nMkComb {count = 1, combinations = [[]]}\n\n*Main> comb 1 1\nMkComb {count = 1, combinations = [[0]]}\n\n*Main> comb 4 2\nMkComb {count = 6, combinations = [[1,0],[2,0],[2,1],[3,0],[3,1],[3,2]]}\n\n*Main> count (comb 10 5)\n252\n"
},
{
"answer_id": 56381811,
"author": "tevemadar",
"author_id": 7916438,
"author_profile": "https://Stackoverflow.com/users/7916438",
"pm_score": 2,
"selected": false,
"text": "function *nCk(n,k){\n for(var i=n-1;i>=k-1;--i)\n if(k===1)\n yield [i];\n else\n for(var temp of nCk(i,k-1)){\n temp.unshift(i);\n yield temp;\n }\n}\n\nfunction test(){\n try{\n var n=parseInt(ninp.value);\n var k=parseInt(kinp.value);\n log.innerText=\"\";\n var stop=Date.now()+1000;\n if(k>=1)\n for(var res of nCk(n,k))\n if(Date.now()<stop)\n log.innerText+=JSON.stringify(res)+\" \";\n else{\n log.innerText+=\"1 second passed, stopping here.\";\n break;\n }\n }catch(ex){}\n} n:<input id=\"ninp\" oninput=\"test()\">\n>= k:<input id=\"kinp\" oninput=\"test()\"> >= 1\n<div id=\"log\"></div> i unshift()"
},
{
"answer_id": 59112267,
"author": "David Edwards",
"author_id": 5374816,
"author_profile": "https://Stackoverflow.com/users/5374816",
"pm_score": 0,
"selected": false,
"text": "//Generate combination subsets from a base set of elements (passed as an array). This function should generate an\n//array containing nCr elements, where nCr = n!/[r! (n-r)!].\n\n//Arguments:\n\n//[1] baseSet : The base set to create the subsets from (e.g., [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"])\n//[2] cnt : The number of elements each subset is to contain (e.g., 3)\n\nfunction MakeCombinationSubsets(baseSet, cnt)\n{\n var bLen = baseSet.length;\n var indices = [];\n var subSet = [];\n var done = false;\n var result = []; //Contains all the combination subsets generated\n var done = false;\n var i = 0;\n var idx = 0;\n var tmpIdx = 0;\n var incr = 0;\n var test = 0;\n var newIndex = 0;\n var inBounds = false;\n var tmpIndices = [];\n var checkBounds = false;\n\n //First, generate an array whose elements are indices into the base set ...\n\n for (i=0; i<cnt; i++)\n\n indices.push(i);\n\n //Now create a clone of this array, to be used in the loop itself ...\n\n tmpIndices = [];\n\n tmpIndices = tmpIndices.concat(indices);\n\n //Now initialise the loop ...\n\n idx = cnt - 1; //point to the last element of the indices array\n incr = 0;\n done = false;\n while (!done)\n {\n //Create the current subset ...\n\n subSet = []; //Make sure we begin with a completely empty subset before continuing ...\n\n for (i=0; i<cnt; i++)\n\n subSet.push(baseSet[tmpIndices[i]]); //Create the current subset, using items selected from the\n //base set, using the indices array (which will change as we\n //continue scanning) ...\n\n //Add the subset thus created to the result set ...\n\n result.push(subSet);\n\n //Now update the indices used to select the elements of the subset. At the start, idx will point to the\n //rightmost index in the indices array, but the moment that index moves out of bounds with respect to the\n //base set, attention will be shifted to the next left index.\n\n test = tmpIndices[idx] + 1;\n\n if (test >= bLen)\n {\n //Here, we're about to move out of bounds with respect to the base set. We therefore need to scan back,\n //and update indices to the left of the current one. Find the leftmost index in the indices array that\n //isn't going to move out of bounds with respect to the base set ...\n\n tmpIdx = idx - 1;\n incr = 1;\n\n inBounds = false; //Assume at start that the index we're checking in the loop below is out of bounds\n checkBounds = true;\n\n while (checkBounds)\n {\n if (tmpIdx < 0)\n {\n checkBounds = false; //Exit immediately at this point\n }\n else\n {\n newIndex = tmpIndices[tmpIdx] + 1;\n test = newIndex + incr;\n\n if (test >= bLen)\n {\n //Here, incrementing the current selected index will take that index out of bounds, so\n //we move on to the next index to the left ...\n\n tmpIdx--;\n incr++;\n }\n else\n {\n //Here, the index will remain in bounds if we increment it, so we\n //exit the loop and signal that we're in bounds ...\n\n inBounds = true;\n checkBounds = false;\n\n //End if/else\n }\n\n //End if \n } \n //End while\n }\n //At this point, if we'er still in bounds, then we continue generating subsets, but if not, we abort immediately.\n\n if (!inBounds)\n done = true;\n else\n {\n //Here, we're still in bounds. We need to update the indices accordingly. NOTE: at this point, although a\n //left positioned index in the indices array may still be in bounds, incrementing it to generate indices to\n //the right may take those indices out of bounds. We therefore need to check this as we perform the index\n //updating of the indices array.\n\n tmpIndices[tmpIdx] = newIndex;\n\n inBounds = true;\n checking = true;\n i = tmpIdx + 1;\n\n while (checking)\n {\n test = tmpIndices[i - 1] + 1; //Find out if incrementing the left adjacent index takes it out of bounds\n\n if (test >= bLen)\n {\n inBounds = false; //If we move out of bounds, exit NOW ...\n checking = false;\n }\n else\n {\n tmpIndices[i] = test; //Otherwise, update the indices array ...\n\n i++; //Now move on to the next index to the right in the indices array ...\n\n checking = (i < cnt); //And continue until we've exhausted all the indices array elements ...\n //End if/else\n }\n //End while\n }\n //At this point, if the above updating of the indices array has moved any of its elements out of bounds,\n //we abort subset construction from this point ...\n if (!inBounds)\n done = true;\n //End if/else\n }\n }\n else\n {\n //Here, the rightmost index under consideration isn't moving out of bounds with respect to the base set when\n //we increment it, so we simply increment and continue the loop ...\n tmpIndices[idx] = test;\n //End if\n }\n //End while\n }\n return(result);\n//End function\n}\n\n\nfunction MakePowerSet(baseSet)\n{\n var bLen = baseSet.length;\n var result = [];\n var i = 0;\n var partialSet = [];\n\n result.push([]); //add the empty set to the power set\n\n for (i=1; i<bLen; i++)\n {\n partialSet = MakeCombinationSubsets(baseSet, i);\n result = result.concat(partialSet);\n //End i loop\n }\n //Now, finally, add the base set itself to the power set to make it complete ...\n\n partialSet = [];\n partialSet.push(baseSet);\n result = result.concat(partialSet);\n\n return(result);\n //End function\n}\n []\n[\"a\"]\n[\"b\"]\n[\"c\"]\n[\"d\"]\n[\"e\"]\n[\"f\"]\n[\"a\",\"b\"]\n[\"a\",\"c\"]\n[\"a\",\"d\"]\n[\"a\",\"e\"]\n[\"a\",\"f\"]\n[\"b\",\"c\"]\n[\"b\",\"d\"]\n[\"b\",\"e\"]\n[\"b\",\"f\"]\n[\"c\",\"d\"]\n[\"c\",\"e\"]\n[\"c\",\"f\"]\n[\"d\",\"e\"]\n[\"d\",\"f\"]\n[\"e\",\"f\"]\n[\"a\",\"b\",\"c\"]\n[\"a\",\"b\",\"d\"]\n[\"a\",\"b\",\"e\"]\n[\"a\",\"b\",\"f\"]\n[\"a\",\"c\",\"d\"]\n[\"a\",\"c\",\"e\"]\n[\"a\",\"c\",\"f\"]\n[\"a\",\"d\",\"e\"]\n[\"a\",\"d\",\"f\"]\n[\"a\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\"]\n[\"b\",\"c\",\"e\"]\n[\"b\",\"c\",\"f\"]\n[\"b\",\"d\",\"e\"]\n[\"b\",\"d\",\"f\"]\n[\"b\",\"e\",\"f\"]\n[\"c\",\"d\",\"e\"]\n[\"c\",\"d\",\"f\"]\n[\"c\",\"e\",\"f\"]\n[\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\"]\n[\"a\",\"b\",\"c\",\"e\"]\n[\"a\",\"b\",\"c\",\"f\"]\n[\"a\",\"b\",\"d\",\"e\"]\n[\"a\",\"b\",\"d\",\"f\"]\n[\"a\",\"b\",\"e\",\"f\"]\n[\"a\",\"c\",\"d\",\"e\"]\n[\"a\",\"c\",\"d\",\"f\"]\n[\"a\",\"c\",\"e\",\"f\"]\n[\"a\",\"d\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\",\"e\"]\n[\"b\",\"c\",\"d\",\"f\"]\n[\"b\",\"c\",\"e\",\"f\"]\n[\"b\",\"d\",\"e\",\"f\"]\n[\"c\",\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\",\"e\"]\n[\"a\",\"b\",\"c\",\"d\",\"f\"]\n[\"a\",\"b\",\"c\",\"e\",\"f\"]\n[\"a\",\"b\",\"d\",\"e\",\"f\"]\n[\"a\",\"c\",\"d\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n"
},
{
"answer_id": 63761492,
"author": "KevinBui",
"author_id": 836376,
"author_profile": "https://Stackoverflow.com/users/836376",
"pm_score": 2,
"selected": false,
"text": "let combine = (list, n) =>\n n == 0 ?\n [[]] :\n list.flatMap((e, i) =>\n combine(\n list.slice(i + 1),\n n - 1\n ).map(c => [e].concat(c))\n );\n\nlet res = combine([1,2,3,4], 3);\nres.forEach(e => console.log(e.join()));"
},
{
"answer_id": 65244790,
"author": "George Robinson",
"author_id": 9242492,
"author_profile": "https://Stackoverflow.com/users/9242492",
"pm_score": 0,
"selected": false,
"text": "mallloc() free() printf() new delete std::cout *alphabet \"abcdefg\" void OutputArrayChar(unsigned int* ka, size_t n, const char *alphabet) {\n for (int i = 0; i < n; i++)\n std::cout << alphabet[ka[i]] << \",\";\n std::cout << endl;\n}\n \n\nvoid GenCombinations(const unsigned int N, const unsigned int K, const char *alphabet) {\n unsigned int *ka = new unsigned int [K]; //dynamically allocate an array of UINTs\n unsigned int ki = K-1; //Point ki to the last elemet of the array\n ka[ki] = N-1; //Prime the last elemet of the array.\n \n while (true) {\n unsigned int tmp = ka[ki]; //Optimization to prevent reading ka[ki] repeatedly\n\n while (ki) //Fill to the left with consecutive descending values (blue squares)\n ka[--ki] = --tmp;\n OutputArrayChar(ka, K, alphabet);\n \n while (--ka[ki] == ki) { //Decrement and check if the resulting value equals the index (bright green squares)\n OutputArrayChar(ka, K, alphabet);\n if (++ki == K) { //Exit condition (all of the values in the array are flush to the left)\n delete[] ka;\n return;\n } \n }\n }\n}\n \n\nint main(int argc, char *argv[])\n{\n GenCombinations(7, 4, \"abcdefg\");\n return 0;\n}\n *alphabet N"
},
{
"answer_id": 65263832,
"author": "Andrushenko Alexander",
"author_id": 6093953,
"author_profile": "https://Stackoverflow.com/users/6093953",
"pm_score": 0,
"selected": false,
"text": "#include<vector>\nusing namespace std;\n\ntemplate<typename T>\nvoid ksubsets(const vector<T>& arr, unsigned left, unsigned idx,\n vector<T>& lst, vector<vector<T>>& res)\n{\n if (left < 1) {\n res.push_back(lst);\n return;\n }\n for (unsigned i = idx; i < arr.size(); i++) {\n lst.push_back(arr[i]);\n ksubsets(arr, left - 1, i + 1, lst, res);\n lst.pop_back();\n }\n}\n\nint main()\n{\n vector<int> arr = { 1, 2, 3, 4, 5 };\n unsigned left = 3;\n vector<int> lst;\n vector<vector<int>> res;\n ksubsets<int>(arr, left, 0, lst, res);\n // now res has all the combinations\n}\n"
},
{
"answer_id": 66754344,
"author": "Student222",
"author_id": 4499942,
"author_profile": "https://Stackoverflow.com/users/4499942",
"pm_score": 2,
"selected": false,
"text": "def combination_indicies(n, k, j = 0, stack = []): \n if len(stack) == k: \n yield list(stack)\n return\n \n for i in range(j, n):\n stack.append(i)\n for x in combination_indicies(n, k, i + 1, stack): \n yield x\n stack.pop() \n \nlist(combination_indicies(5, 3))\n [[0, 1, 2],\n [0, 1, 3],\n [0, 1, 4],\n [0, 2, 3],\n [0, 2, 4],\n [0, 3, 4],\n [1, 2, 3],\n [1, 2, 4],\n [1, 3, 4],\n [2, 3, 4]]\n"
},
{
"answer_id": 67084259,
"author": "nmbell",
"author_id": 5034468,
"author_profile": "https://Stackoverflow.com/users/5034468",
"pm_score": 0,
"selected": false,
"text": "function Get-NChooseK\n{\n\n [CmdletBinding()]\n\n Param\n (\n\n [String[]]\n $ArrayN\n\n , [Int]\n $ChooseK\n\n , [Switch]\n $AllK\n\n , [String]\n $Prefix = ''\n\n )\n\n PROCESS\n {\n # Validate the inputs\n $ArrayN = $ArrayN | Sort-Object -Unique\n\n If ($ChooseK -gt $ArrayN.Length)\n {\n Write-Error \"Can't choose $ChooseK items when only $($ArrayN.Length) are available.\" -ErrorAction Stop\n }\n\n # Control the output\n $firstK = If ($AllK) { 1 } Else { $ChooseK }\n\n # Get combinations\n $firstK..$ChooseK | ForEach-Object {\n\n $thisK = $_\n\n $ArrayN[0..($ArrayN.Length-($thisK--))] | ForEach-Object {\n If ($thisK -eq 0)\n {\n Write-Output ($Prefix+$_)\n }\n Else\n {\n Get-NChooseK -Array ($ArrayN[($ArrayN.IndexOf($_)+1)..($ArrayN.Length-1)]) -Choose $thisK -AllK:$false -Prefix ($Prefix+$_)\n }\n }\n\n }\n }\n\n}\n PS C:\\>$ArrayN = 'E','B','C','A','D'\nPS C:\\>$ChooseK = 3\nPS C:\\>Get-NChooseK -ArrayN $ArrayN -ChooseK $ChooseK\nABC\nABD\nABE\nACD\nACE\nADE\nBCD\nBCE\nBDE\nCDE\n"
},
{
"answer_id": 67223626,
"author": "nmbell",
"author_id": 5034468,
"author_profile": "https://Stackoverflow.com/users/5034468",
"pm_score": -1,
"selected": false,
"text": "function Get-NChooseK\n{\n <#\n .SYNOPSIS\n Returns all the possible combinations by choosing K items at a time from N possible items.\n\n .DESCRIPTION\n Returns all the possible combinations by choosing K items at a time from N possible items.\n The combinations returned do not consider the order of items as important i.e. 123 is considered to be the same combination as 231, etc.\n\n .PARAMETER ArrayN\n The array of items to choose from.\n\n .PARAMETER ChooseK\n The number of items to choose.\n\n .PARAMETER AllK\n Includes combinations for all lesser values of K above zero i.e. 1 to K.\n\n .PARAMETER Prefix\n String that will prefix each line of the output.\n\n .EXAMPLE\n PS C:\\> Get-NChooseK -ArrayN '1','2','3' -ChooseK 3\n 123\n\n .EXAMPLE\n PS C:\\> Get-NChooseK -ArrayN '1','2','3' -ChooseK 3 -AllK\n 1\n 2\n 3\n 12\n 13\n 23\n 123\n\n .EXAMPLE\n PS C:\\> Get-NChooseK -ArrayN '1','2','3' -ChooseK 2 -Prefix 'Combo: '\n Combo: 12\n Combo: 13\n Combo: 23\n\n .NOTES\n Author : nmbell\n #>\n\n # Use cmdlet binding\n [CmdletBinding()]\n\n # Declare parameters\n Param\n (\n\n [String[]]\n $ArrayN\n\n , [Int]\n $ChooseK\n\n , [Switch]\n $AllK\n\n , [String]\n $Prefix = ''\n\n )\n\n BEGIN\n {\n }\n\n PROCESS\n {\n # Validate the inputs\n $ArrayN = $ArrayN | Sort-Object -Unique\n\n If ($ChooseK -gt $ArrayN.Length)\n {\n Write-Error \"Can't choose $ChooseK items when only $($ArrayN.Length) are available.\" -ErrorAction Stop\n }\n\n # Control the output\n $firstK = If ($AllK) { 1 } Else { $ChooseK }\n\n # Get combinations\n $firstK..$ChooseK | ForEach-Object {\n\n $thisK = $_\n\n $ArrayN[0..($ArrayN.Length-($thisK--))] | ForEach-Object {\n If ($thisK -eq 0)\n {\n Write-Output ($Prefix+$_)\n }\n Else\n {\n Get-NChooseK -Array ($ArrayN[($ArrayN.IndexOf($_)+1)..($ArrayN.Length-1)]) -Choose $thisK -AllK:$false -Prefix ($Prefix+$_)\n }\n }\n\n }\n }\n\n END\n {\n }\n\n}\n\n PS C:\\>Get-NChooseK -ArrayN 'A','B','C','D','E' -ChooseK 3\nABC\nABD\nABE\nACD\nACE\nADE\nBCD\nBCE\nBDE\nCDE\n"
},
{
"answer_id": 68360430,
"author": "SDAH",
"author_id": 8558827,
"author_profile": "https://Stackoverflow.com/users/8558827",
"pm_score": 0,
"selected": false,
"text": "function Combinations( arr, r ) {\n // To avoid object referencing, cloning the array.\n arr = arr && arr.slice() || [];\n\n var len = arr.length;\n\n if( !len || r > len || !r )\n return [ [] ];\n else if( r === len ) \n return [ arr ];\n\n if( r === len ) return arr.reduce( ( x, v ) => {\n x.push( [ v ] );\n\n return x;\n }, [] );\n\n var head = arr.shift();\n\n return Combinations( arr, r - 1 ).map( x => {\n x.unshift( head );\n\n return x;\n } ).concat( Combinations( arr, r ) );\n}\n\n// Now do your stuff.\n\nconsole.log( Combinations( [ 'a', 'b', 'c', 'd', 'e' ], 3 ) );\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191/"
] |
127,713
|
<p>Why does the following method hang?</p>
<pre>
public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append(buf.flip());
}
}
</pre>
|
[
{
"answer_id": 127729,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": true,
"text": "buf.clear() read read"
},
{
"answer_id": 9628316,
"author": "Fuwjax",
"author_id": 315943,
"author_profile": "https://Stackoverflow.com/users/315943",
"pm_score": 0,
"selected": false,
"text": "Writer.append(CharBuffer buf) Writer.append(CharSequence seq) seq.toString() CharBuffer.toString() Reader.read(CharBuffer buf) public void pipe(Reader in, Writer out) throws IOException {\n char[] buf = new char[DEFAULT_BUFFER_SIZE];\n int count = in.read(buf);\n while( count >= 0 ) {\n out.write(buf, 0, count);\n count = in.read(buf);\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
127,728
|
<p>I'm working with ASP.NET 3.5.
I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.</p>
|
[
{
"answer_id": 127983,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": false,
"text": "protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) \n{\n args.IsValid = ListBox1.Items.Count > 0; \n}\n <script language=\"JavaScript\">\n<!--\n function ListBoxValid(sender, args)\n {\n args.IsValid = sender.options.length > 0;\n }\n// -->\n</script> \n<asp:ListBox ID=\"ListBox1\" runat=\"server\"></asp:ListBox>\n<asp:TextBox ID=\"TextBox1\" runat=\"server\"></asp:TextBox>\n<asp:Button ID=\"Button1\" runat=\"server\" onclick=\"Button1_Click\" Text=\"Button\" ValidationGroup=\"NOVALID\" />\n<asp:Button ID=\"Button2\" runat=\"server\" Text=\"ButtonsUBMIT\" />\n\n<asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" \nErrorMessage=\"CustomValidator\" \nonservervalidate=\"CustomValidator1_ServerValidate\" ClientValidationFunction=\"ListBoxValid\"></asp:CustomValidator>\n"
},
{
"answer_id": 307187,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<asp:CustomValidator \n runat=\"server\" \n ControlToValidate=\"listbox1\"\n ErrorMessage=\"Add some items yo!\" \n ClientValidationFunction=\"checkListBox\"\n/>\n\n<script type=\"Text/JavaScript\">\n function checkListBox(sender, args)\n {\n args.IsValid = sender.options.length > 0;\n }\n</script> \n"
},
{
"answer_id": 344206,
"author": "Naeem Sarfraz",
"author_id": 40986,
"author_profile": "https://Stackoverflow.com/users/40986",
"pm_score": 3,
"selected": false,
"text": "function ListBoxValid(sender, args) \n{\n args.IsValid = sender.options.length > 0; \n}\n function ListBoxValid(sender, args)\n{\n var ctlDropDown = document.getElementById(sender.controltovalidate);\n args.IsValid = ctlDropDown.options.length > 0; \n}\n"
},
{
"answer_id": 2759991,
"author": "Zack Rose",
"author_id": 331654,
"author_profile": "https://Stackoverflow.com/users/331654",
"pm_score": 1,
"selected": false,
"text": "function ListBoxValid(sender, args)\n{\n\n var listBox = document.getElementById(sender.controltovalidate);\n\n var listBoxCnt = 0;\n\n for (var x =0; x<listBox.options.length; x++)\n {\n if (listBox.options[x].selected) listBoxCnt++;\n }\n\n args.IsValid = (listBoxCnt>0)\n\n}\n"
},
{
"answer_id": 6308126,
"author": "Tiago",
"author_id": 792930,
"author_profile": "https://Stackoverflow.com/users/792930",
"pm_score": 2,
"selected": false,
"text": "Display=\"Dynamic\" ValidateEmptyText=\"True\"\n"
},
{
"answer_id": 40650365,
"author": "Summao",
"author_id": 4826879,
"author_profile": "https://Stackoverflow.com/users/4826879",
"pm_score": 0,
"selected": false,
"text": "<script language=\"JavaScript\">\n function CheckListBox(sender, args)\n {\n args.IsValid = document.getElementById(\"<%=ListBox1.ClientID%>\").options.length > 0;\n }\n</script> \n<asp:ListBox ID=\"ListBox1\" runat=\"server\"></asp:ListBox>\n<asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" \nErrorMessage=\"*Required\" ClientValidationFunction=\"CheckListBox\"></asp:CustomValidator>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
127,736
|
<p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p>
<p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p>
<p>I need the following operations: </p>
<ul>
<li>check if the transition has a label</li>
<li>get this label</li>
<li>add a label to a transition</li>
<li>check if the transition has a condition </li>
<li>get this condition</li>
<li>check for equality</li>
</ul>
<p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p>
<pre><code>class Transition(object):
def __init__(self, start, end):
self.start = start
self.end = end
def get_label(self):
return None
def has_label(self):
return False
def collect_decorations(self, decorations):
return decorations
def internal_equality(self, my_decorations, other):
try:
return (self.start == other.start
and self.end == other.end
and my_decorations = other.collect_decorations())
def __eq__(self, other):
return self.internal_equality(self.collect_decorations({}), other)
class Labeled(object):
def __init__(self, label, base):
self.base = base
self.label = label
def has_label(self):
return True
def get_label(self):
return self.label
def collect_decorations(self, decorations):
assert 'label' not in decorations
decorations['label'] = self.label
return self.base.collect_decorations(decorations)
def __getattr__(self, attribute):
return self.base.__getattr(attribute)
</code></pre>
<p>Is this a clean approach? Am I missing something?</p>
<p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p>
<pre><code>class Transition(object):
def __init__(self, **kwargs):
# init is pythons MI-madness ;-)
super(Transition, self).__init__(**kwargs)
self.start = kwargs['start']
self.end = kwargs['end']
def get_label(self):
return None
def get_condition(self):
return None
def __eq__(self, other):
try:
return self.start == other.start and self.end == other.end
except AttributeError:
return False
class LabeledTransition(Transition):
def __init__(self, **kwargs):
super(LabeledTransition).__init__(**kwargs)
self.label = kwargs['label']
def get_label(self):
return self.label
def __eq__(self):
super_result = super(LabeledTransition, self).__eq__(other)
try:
return super_result and self.label == other.label
except AttributeError:
return False
class ConditionalTransition(Transition):
def __init__(self, **kwargs):
super(ConditionalTransition, self).__init__(**kwargs)
self.condition = kwargs['condition']
def get_condition(self):
return self.condition
def __eq__(self, other):
super_result = super(ConditionalTransition, self).__eq__(other)
try:
return super_result and self.condition = other.condition
except AttributeError:
return False
# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
pass
</code></pre>
<p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p>
<p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p>
<p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p>
<p><em>EDIT</em>:
Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
|
[
{
"answer_id": 128005,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 0,
"selected": false,
"text": "return self.label is not None\n ConditionalTransition"
},
{
"answer_id": 219303,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": true,
"text": "class State(object):\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.name\n\nclass Automaton(object):\n def __init__(self, instance, start):\n self._state = start\n self.transitions = instance.transitions()\n\n def get_state(self):\n return self._state\n\n def set_state(self, target):\n transition = self.transitions.get((self.state, target))\n if transition:\n action, condition = transition\n if condition:\n if condition():\n if action:\n action()\n self._state = target\n else:\n self._state = target\n else:\n self._state = target\n\n state = property(get_state, set_state)\n\nclass Door(object):\n open = State('open')\n closed = State('closed')\n\n def __init__(self, blocked=False):\n self.blocked = blocked\n\n def close(self):\n print 'closing door'\n\n def do_open(self):\n print 'opening door'\n\n def not_blocked(self):\n return not self.blocked\n\n def transitions(self):\n return {\n (self.open, self.closed):(self.close, self.not_blocked),\n (self.closed, self.open):(self.do_open, self.not_blocked),\n }\n\nif __name__ == '__main__':\n door = Door()\n automaton = Automaton(door, door.open)\n\n print 'door is', automaton.state\n automaton.state = door.closed\n print 'door is', automaton.state\n automaton.state = door.open\n print 'door is', automaton.state\n door.blocked = True\n automaton.state = door.closed\n print 'door is', automaton.state\n door is open\nclosing door\ndoor is closed\nopening door\ndoor is open\ndoor is open\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17663/"
] |
127,739
|
<pre><code> $a = '{ "tag": "<b></b>" }';
echo json_encode( json_decode($a) );
</code></pre>
<p>This outputs:</p>
<pre><code>{"tag":"<b><\/b>"}
</code></pre>
<p>when you would think it would output exactly the input. For some reason json_encode adds an extra slash.</p>
|
[
{
"answer_id": 127775,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 5,
"selected": true,
"text": "any-Unicode-character-\n except-\"-or-\\-or-\n control-character\n\\\"\n\\\\\n\\/ <---- see here?\n\\b\n\\f\n\\n\n\\r\n\\t\n\\u four-hex-digits\n"
},
{
"answer_id": 127801,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "\\/ /"
},
{
"answer_id": 48148605,
"author": "symi khan",
"author_id": 8344330,
"author_profile": "https://Stackoverflow.com/users/8344330",
"pm_score": 2,
"selected": false,
"text": "echo json_encode($a,JSON_HEX_TAG)\n [\"\\u003C\\u003E\"]\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19087/"
] |
127,753
|
<p>Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?</p>
<pre><code>public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while (in.read(buf) >= 0 ) {
out.append(buf.flip());
buf.clear();
}
}
</code></pre>
<p>[EDIT] Please note the <code>Reader</code> and <code>Writer</code> are <em>given</em>. The correct answer will demonstrate how to take <code>in</code> and <code>out</code> and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where <code>in</code> and <code>out</code> are an <code>InputStream</code> and an <code>OutputStream</code> (preferably with a conversion from/to <code>Reader</code>/<code>Writer</code>). I will not accept answers where either <code>in</code> or <code>out</code> is a <em>subclass</em> of <code>Reader</code>/<code>InputStream</code> or <code>Writer</code>/<code>OutputStrem</code>.</p>
|
[
{
"answer_id": 331854,
"author": "Henning",
"author_id": 7034,
"author_profile": "https://Stackoverflow.com/users/7034",
"pm_score": 4,
"selected": true,
"text": "IOUtils.copy(in, out) Stream Reader Writer"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
127,761
|
<p>Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see <code>Windows -> Preferences -> Aptana -> Editors -> PHP -> PHP Interpreters</code> in my menu (I have <code>PHP plugin</code> installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. <code>Xdebug</code> is installed, confirmed through <code>php info</code>.</p>
|
[
{
"answer_id": 131722,
"author": "phatduckk",
"author_id": 3896,
"author_profile": "https://Stackoverflow.com/users/3896",
"pm_score": 3,
"selected": true,
"text": "[Zend Modules] \nZend Debugger\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
127,771
|
<p>My problem is:</p>
<p>I have a perl script which uses lot of memory (expected behaviour because of caching). But, I noticed that the more I do caching, slower it gets and the process spends most of the time in sleep mode.</p>
<p>I thought pre-allocating memory to the process might speed up the performance.</p>
<p>Does someone have any ideas here?</p>
<p><strong>Update</strong>:</p>
<p>I think I am not being very clear here. I will put question in clearer way:</p>
<p>I am not looking for the ways of pre-allocating inside the perl script. I dont think that would help me much here. What I am interested in is a way to tell OS to allocate X amount of memory for my perl script so that it does not have to compete with other processes coming in later.</p>
<p>Assume that I cant get away with the memory usage. Although, I am exploring ways of reducing that too but dont expect much improvement there.
FYI, I am working on a solaris 10 machine.</p>
|
[
{
"answer_id": 127978,
"author": "douglashunter",
"author_id": 13838,
"author_profile": "https://Stackoverflow.com/users/13838",
"pm_score": 0,
"selected": false,
"text": "my @array;\n$#array = 1_000_000; # pre-extend array to one million elements,\n # http://perldoc.perl.org/perldata.html#Scalar-values\n\nmy %hash;\nkeys(%hash) = 8192; # pre-allocate hash buckets \n # (same documentation section)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
127,776
|
<p>Where can I find the specifications for the various C# languages?</p>
<p><em>(EDIT: it appears people voted down because you could 'google' this, however, my original intent was to put an answer with information not found on google. I've accepted the answer with the best google results, as they are relevant to people who haven't paid for VS)</em></p>
|
[
{
"answer_id": 127789,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 4,
"selected": false,
"text": ".\\Microsoft Visual Studio 8\\VC#\\Specifications\\1033\n .\\Microsoft Visual Studio 9.0\\VC#\\Specifications\\1033\n .\\Microsoft Visual Studio 10.0\\VC#\\Specifications\\1033\n .\\Microsoft Visual Studio 11.0\\VC#\\Specifications\\1033\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7116/"
] |
127,794
|
<p>Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)</p>
<p>I basically have a <code>StyledWindow</code> control, which is essentially a glorified <code>Panel</code> with ability to do other bits (like add borders etc).</p>
<p>Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:</p>
<pre><code> protected override void CreateChildControls()
{
_panel = new Panel();
if (_editable != null)
_editable.InstantiateIn(_panel);
_regions = new List<IAttributeAccessor>();
_regions.Add(_panel);
}
</code></pre>
<p>The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the <code>RegisterClientScriptBlock</code> is the only reason I need the page ref).</p>
<p>Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] <code>Page</code> object.</p>
<p>What's confusing me is that the control works fine as a standalone, but when placed in the <code>StyledWindow</code> it all goes horribly wrong!</p>
<p><strong>So, it looks like I am missing something in either my <code>StyledWindow</code> or <code>ChildControl</code>. Any ideas?</strong></p>
<h2>Update</h2>
<p>As <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824">Brad Wilson</a> quite rightly pointed out, you do not see the controls being added to the <code>Controls</code> collection. This is what the <code>_panel</code> is for, this was there to handle that for me, basically then override <code>Controls</code> (I got this from a guide somewhere):</p>
<pre><code> Panel _panel; // Sub-Control to store the "Content".
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _panel.Controls;
}
}
</code></pre>
<p>I hope that helps clarify things. Apologies.</p>
<h2>Update Following <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299">Longhorn213's Answer</a></h2>
<p>Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.</p>
<p>The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's <code>OnLoad</code> event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D</p>
<p>Thanks for your help guys, appreciated :)</p>
|
[
{
"answer_id": 128299,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "protected override void OnLoad(EventArgs e)\n{\n\n // Do something to get the script\n string script = GetScript();\n\n this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), \"SomeJavaScriptName\", script);\n\n // Could also use this function to determine if the script has been register. i.e. more than 1 of the controls exists\n this.Page.ClientScript.IsClientScriptBlockRegistered(\"SomeJavaScriptName\");\n\n base.OnLoad(e);\n}\n"
},
{
"answer_id": 132377,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "OnLoad Controls Controls Controls Panel ctl.Controls[0].Controls[0] Panel Controls Controls Panel Panel"
},
{
"answer_id": 133412,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": true,
"text": "Panel MyCtl.Controls[0].Controls Panel <cc1:TemplatedControl ID=\"MyCtl\" runat=\"server\">\n <Template>\n <!-- Templated Content Goes Here -->\n </Template>\n</cc1:TemplatedControl> \n public class DummyWebControl : WebControl\n{\n // Acts as the surrogate for the templated controls.\n // This is essentially the \"interface\" for the templated data.\n}\n ITemplate _template;\n // Surrogate to hold the controls instantiated from \n // within the template.\n DummyWebControl _owner;\n\n protected override void CreateChildControls()\n {\n // Note we are calling base.Controls here\n // (you will see why in a min).\n base.Controls.Clear();\n _owner = new DummyWebControl();\n\n // Load the Template Content\n ITemplate template = _template;\n if (template == null)\n template = new StyledWindowDefaultTemplate();\n template.InstantiateIn(_owner);\n\n base.Controls.Add(_owner);\n ChildControlsCreated = true;\n }\n public override ControlCollection Controls\n {\n get\n {\n EnsureChildControls();\n return _owner.Controls;\n }\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
127,803
|
<p>I need to parse <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p>
<p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>strptime</code></a> in the Python standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
|
[
{
"answer_id": 127825,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": ">>> datetime.datetime.strptime(\"2008-08-12T12:20:30.656234Z\", \"%Y-%m-%dT%H:%M:%S.Z\")\nValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z\n >>> def gt(dt_str):\n dt, _, us= dt_str.partition(\".\")\n dt= datetime.datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n us= int(us.rstrip(\"Z\"), 10)\n return dt + datetime.timedelta(microseconds=us)\n\n>>> gt(\"2008-08-12T12:20:30.656234Z\")\ndatetime.datetime(2008, 8, 12, 12, 20, 30, 656234)\n"
},
{
"answer_id": 127872,
"author": "Ted",
"author_id": 7972,
"author_profile": "https://Stackoverflow.com/users/7972",
"pm_score": 5,
"selected": false,
"text": "import re\nimport datetime\ns = \"2008-09-03T20:56:35.450686Z\"\nd = datetime.datetime(*map(int, re.split(r'[^\\d]', s)[:-1]))\n"
},
{
"answer_id": 127972,
"author": "sethbc",
"author_id": 21722,
"author_profile": "https://Stackoverflow.com/users/21722",
"pm_score": 8,
"selected": false,
"text": ">>> datetime.datetime.strptime(\"2008-09-03T20:56:35.450686Z\", \"%Y-%m-%dT%H:%M:%S.%fZ\")\n"
},
{
"answer_id": 6772287,
"author": "Gordon Wrigley",
"author_id": 10471,
"author_profile": "https://Stackoverflow.com/users/10471",
"pm_score": 1,
"selected": false,
"text": "calendar.timegm(time.strptime(date.split(\".\")[0]+\"UTC\", \"%Y-%m-%dT%H:%M:%S%Z\"))\n"
},
{
"answer_id": 15228038,
"author": "Flimm",
"author_id": 247696,
"author_profile": "https://Stackoverflow.com/users/247696",
"pm_score": 9,
"selected": false,
"text": "isoparse dateutil.parser.isoparse >>> import dateutil.parser\n>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())\n>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only\ndatetime.datetime(2008, 9, 3, 0, 0)\n dateutil.parser.parse isoparse datetime.datetime.fromisoformat dateutil.parser.isoparse fromisoformat fromisoformat fromisoformat"
},
{
"answer_id": 18150817,
"author": "user2646026",
"author_id": 2646026,
"author_profile": "https://Stackoverflow.com/users/2646026",
"pm_score": 2,
"selected": false,
"text": "from dateutil import parser\nds = '2012-60-31'\ntry:\n dt = parser.parse(ds)\nexcept ValueError, e:\n print '\"%s\" is an invalid date' % ds\n"
},
{
"answer_id": 22700869,
"author": "enchanter",
"author_id": 3015344,
"author_profile": "https://Stackoverflow.com/users/3015344",
"pm_score": 4,
"selected": false,
"text": "def from_utc(utcTime,fmt=\"%Y-%m-%dT%H:%M:%S.%fZ\"):\n \"\"\"\n Convert UTC time string to time.struct_time\n \"\"\"\n # change datetime.datetime to time, return time.struct_time type\n return datetime.datetime.strptime(utcTime, fmt)\n from_utc(\"2007-03-04T21:08:12.123Z\")\n datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)\n"
},
{
"answer_id": 28528461,
"author": "Ilker Kesen",
"author_id": 1797064,
"author_profile": "https://Stackoverflow.com/users/1797064",
"pm_score": 5,
"selected": false,
"text": ">>> import arrow\n>>> date = arrow.get(\"2008-09-03T20:56:35.450686Z\")\n>>> date.datetime\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())\n"
},
{
"answer_id": 28979667,
"author": "Benjamin Riggs",
"author_id": 161366,
"author_profile": "https://Stackoverflow.com/users/161366",
"pm_score": 3,
"selected": false,
"text": "from datetime import datetime, timezone, timedelta\ndatetime.strptime(timestamp, \"%Y-%m-%dT%H:%M:%S.%fZ\").replace(\n tzinfo=timezone(timedelta(0)))\n >>> datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))\n... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)\n"
},
{
"answer_id": 30696682,
"author": "Mark Amery",
"author_id": 1709587,
"author_profile": "https://Stackoverflow.com/users/1709587",
"pm_score": 8,
"selected": false,
"text": "datetime.datetime.strptime from datetime import datetime\n\ndef parse_rfc3339(datetime_str: str) -> datetime:\n try:\n return datetime.strptime(datetime_str, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n except ValueError:\n # Perhaps the datetime has a whole number of seconds with no decimal\n # point. In that case, this will work:\n return datetime.strptime(datetime_str, \"%Y-%m-%dT%H:%M:%S%z\")\n 2022-01-01T12:12:12.123Z 2022-01-01T12:12:12Z T datetime_str = datetime_str.replace(' ', 'T') +0500 2009-W01-1 %z +0500 -0430 +0000 +05:00 -04:30 Z"
},
{
"answer_id": 35991099,
"author": "omikron",
"author_id": 719457,
"author_profile": "https://Stackoverflow.com/users/719457",
"pm_score": 1,
"selected": false,
"text": "class FixedOffset(tzinfo):\n \"\"\"Fixed offset in minutes: `time = utc_time + utc_offset`.\"\"\"\n def __init__(self, offset):\n self.__offset = timedelta(minutes=offset)\n hours, minutes = divmod(offset, 60)\n #NOTE: the last part is to remind about deprecated POSIX GMT+h timezones\n # that have the opposite sign in the name;\n # the corresponding numeric value is not used e.g., no minutes\n self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)\n def utcoffset(self, dt=None):\n return self.__offset\n def tzname(self, dt=None):\n return self.__name\n def dst(self, dt=None):\n return timedelta(0)\n def __repr__(self):\n return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)\n def __getinitargs__(self):\n return (self.__offset.total_seconds()/60,)\n\ndef parse_isoformat_datetime(isodatetime):\n try:\n return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')\n except ValueError:\n pass\n try:\n return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')\n except ValueError:\n pass\n pat = r'(.*?[+-]\\d{2}):(\\d{2})'\n temp = re.sub(pat, r'\\1\\2', isodatetime)\n naive_date_str = temp[:-5]\n offset_str = temp[-5:]\n naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')\n offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])\n if offset_str[0] == \"-\":\n offset = -offset\n return naive_dt.replace(tzinfo=FixedOffset(offset))\n"
},
{
"answer_id": 38085175,
"author": "theannouncer",
"author_id": 738924,
"author_profile": "https://Stackoverflow.com/users/738924",
"pm_score": 2,
"selected": false,
"text": "CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm] 2016-06-29T19:36:29.3453Z datetime.datetime.strptime(timestamp.translate(None, ':-'), \"%Y%m%dT%H%M%S.%fZ\")\n 2016-06-29T19:36:29.3453-0400 2008-09-03T20:56:35.450686+05:00 20080903T205635.450686+0500 import re\n# this regex removes all colons and all \n# dashes EXCEPT for the dash indicating + or - utc offset for the timezone\nconformed_timestamp = re.sub(r\"[:]|([-](?!((\\d{2}[:]\\d{2})|(\\d{4}))$))\", '', timestamp)\ndatetime.datetime.strptime(conformed_timestamp, \"%Y%m%dT%H%M%S.%f%z\" )\n %z ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' Z %z import re\nimport datetime\n\n# this regex removes all colons and all \n# dashes EXCEPT for the dash indicating + or - utc offset for the timezone\nconformed_timestamp = re.sub(r\"[:]|([-](?!((\\d{2}[:]\\d{2})|(\\d{4}))$))\", '', timestamp)\n\n# split on the offset to remove it. use a capture group to keep the delimiter\nsplit_timestamp = re.split(r\"[+|-]\",conformed_timestamp)\nmain_timestamp = split_timestamp[0]\nif len(split_timestamp) == 3:\n sign = split_timestamp[1]\n offset = split_timestamp[2]\nelse:\n sign = None\n offset = None\n\n# generate the datetime object without the offset at UTC time\noutput_datetime = datetime.datetime.strptime(main_timestamp +\"Z\", \"%Y%m%dT%H%M%S.%fZ\" )\nif offset:\n # create timedelta based on offset\n offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))\n # offset datetime with timedelta\n output_datetime = output_datetime + offset_delta\n"
},
{
"answer_id": 38848051,
"author": "Denny Weinberg",
"author_id": 1833539,
"author_profile": "https://Stackoverflow.com/users/1833539",
"pm_score": -1,
"selected": false,
"text": "def parseISO8601DateTime(datetimeStr):\n import time\n from datetime import datetime, timedelta\n\n def log_date_string(when):\n gmt = time.gmtime(when)\n if time.daylight and gmt[8]:\n tz = time.altzone\n else:\n tz = time.timezone\n if tz > 0:\n neg = 1\n else:\n neg = 0\n tz = -tz\n h, rem = divmod(tz, 3600)\n m, rem = divmod(rem, 60)\n if neg:\n offset = '-%02d%02d' % (h, m)\n else:\n offset = '+%02d%02d' % (h, m)\n\n return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset\n\n dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')\n timestamp = dt.timestamp()\n return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)\n Z %z"
},
{
"answer_id": 39150189,
"author": "Damian Yerrick",
"author_id": 2738262,
"author_profile": "https://Stackoverflow.com/users/2738262",
"pm_score": 3,
"selected": false,
"text": "datetime.datetime #!/usr/bin/env python\nfrom __future__ import with_statement, division, print_function\nimport sqlite3\nimport datetime\n\ntesttimes = [\n \"2016-08-25T16:01:26.123456Z\",\n \"2016-08-25T16:01:29\",\n]\ndb = sqlite3.connect(\":memory:\")\nc = db.cursor()\nfor timestring in testtimes:\n c.execute(\"SELECT strftime('%s', ?)\", (timestring,))\n converted = c.fetchone()[0]\n print(\"%s is %s after epoch\" % (timestring, converted))\n dt = datetime.datetime.fromtimestamp(int(converted))\n print(\"datetime is %s\" % dt)\n 2016-08-25T16:01:26.123456Z is 1472140886 after epoch\ndatetime is 2016-08-25 12:01:26\n2016-08-25T16:01:29 is 1472140889 after epoch\ndatetime is 2016-08-25 12:01:29\n"
},
{
"answer_id": 39387583,
"author": "Artem Vasilev",
"author_id": 5829882,
"author_profile": "https://Stackoverflow.com/users/5829882",
"pm_score": 3,
"selected": false,
"text": "parse_datetime() parse_datetime('2016-08-09T15:12:03.65478Z') =\ndatetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=<UTC>)\n from django.utils import formats\nfrom django.forms.fields import DateTimeField\nfrom django.utils.dateparse import parse_datetime\n\nclass DateTimeFieldFixed(DateTimeField):\n def strptime(self, value, format):\n if format == 'iso-8601':\n return parse_datetime(value)\n return super().strptime(value, format)\n\nDateTimeField.strptime = DateTimeFieldFixed.strptime\nformats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')\n"
},
{
"answer_id": 40254277,
"author": "Marc Wilson",
"author_id": 1368306,
"author_profile": "https://Stackoverflow.com/users/1368306",
"pm_score": 3,
"selected": false,
"text": ">>> from iso8601utils import parsers\n>>> parsers.datetime('2008-09-03T20:56:35.450686Z')\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n"
},
{
"answer_id": 42515962,
"author": "Blairg23",
"author_id": 1224827,
"author_profile": "https://Stackoverflow.com/users/1224827",
"pm_score": 4,
"selected": false,
"text": "python-dateutil >>> import dateutil.parser as dp\n>>> t = '1984-06-02T19:05:00.000Z'\n>>> parsed_t = dp.parse(t)\n>>> print(parsed_t)\ndatetime.datetime(1984, 6, 2, 19, 5, tzinfo=tzutc())\n"
},
{
"answer_id": 43054101,
"author": "movermeyer",
"author_id": 6460914,
"author_profile": "https://Stackoverflow.com/users/6460914",
"pm_score": 4,
"selected": false,
"text": ">>> import ciso8601\n>>> ciso8601.parse_datetime('2014-01-09T21')\ndatetime.datetime(2014, 1, 9, 21, 0)\n>>> ciso8601.parse_datetime('2014-01-09T21:48:00.921000+05:30')\ndatetime.datetime(2014, 1, 9, 21, 48, 0, 921000, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))\n>>> ciso8601.parse_rfc3339('2014-01-09T21:48:00.921000+05:30')\ndatetime.datetime(2014, 1, 9, 21, 48, 0, 921000, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))\n"
},
{
"answer_id": 48539157,
"author": "Andreas Profous",
"author_id": 1214398,
"author_profile": "https://Stackoverflow.com/users/1214398",
"pm_score": 6,
"selected": false,
"text": "import datetime\n\ndef parse_date_string(date_string: str) -> datetime.datetime\n try:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z')\n except ValueError:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')\n datetime.fromisoformat()"
},
{
"answer_id": 49784038,
"author": "Taku",
"author_id": 6622817,
"author_profile": "https://Stackoverflow.com/users/6622817",
"pm_score": 9,
"selected": false,
"text": "datetime datetime.isoformat() datetime.fromisoformat(date_string) datetime T >>> from datetime import datetime\n>>> datetime.fromisoformat('2011-11-04')\ndatetime.datetime(2011, 11, 4, 0, 0)\n>>> datetime.fromisoformat('20111104')\ndatetime.datetime(2011, 11, 4, 0, 0)\n>>> datetime.fromisoformat('2011-11-04T00:05:23')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n>>> datetime.fromisoformat('2011-11-04T00:05:23Z')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n>>> datetime.fromisoformat('20111104T000523')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n>>> datetime.fromisoformat('2011-W01-2T00:05:23.283')\ndatetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n>>> datetime.fromisoformat('2011-11-04 00:05:23.283')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, 283000)\n>>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)\n>>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') \ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))\n"
},
{
"answer_id": 52485205,
"author": "jrc",
"author_id": 594211,
"author_profile": "https://Stackoverflow.com/users/594211",
"pm_score": 2,
"selected": false,
"text": ">>> import maya\n>>> str = '2008-09-03T20:56:35.450686Z'\n>>> maya.MayaDT.from_rfc3339(str).datetime()\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=<UTC>)\n"
},
{
"answer_id": 56140670,
"author": "A T",
"author_id": 587021,
"author_profile": "https://Stackoverflow.com/users/587021",
"pm_score": -1,
"selected": false,
"text": "from operator import neg, pos\nfrom time import strptime, mktime\nfrom datetime import datetime, tzinfo, timedelta\n\nclass MyUTCOffsetTimezone(tzinfo):\n @staticmethod\n def with_offset(offset_no_signal, signal): # type: (str, str) -> MyUTCOffsetTimezone\n return MyUTCOffsetTimezone((pos if signal == '+' else neg)(\n (datetime.strptime(offset_no_signal, '%H:%M') - datetime(1900, 1, 1))\n .total_seconds()))\n\n def __init__(self, offset, name=None):\n self.offset = timedelta(seconds=offset)\n self.name = name or self.__class__.__name__\n\n def utcoffset(self, dt):\n return self.offset\n\n def tzname(self, dt):\n return self.name\n\n def dst(self, dt):\n return timedelta(0)\n\n\ndef to_datetime_tz(dt): # type: (str) -> datetime\n fmt = '%Y-%m-%dT%H:%M:%S.%f'\n if dt[-6] in frozenset(('+', '-')):\n dt, sign, offset = strptime(dt[:-6], fmt), dt[-6], dt[-5:]\n return datetime.fromtimestamp(mktime(dt),\n tz=MyUTCOffsetTimezone.with_offset(offset, sign))\n elif dt[-1] == 'Z':\n return datetime.strptime(dt, fmt + 'Z')\n return datetime.strptime(dt, fmt)\n from datetime import datetime\n\n\ndef to_datetime_tz(dt): # type: (str) -> datetime\n fmt = '%Y-%m-%dT%H:%M:%S.%f'\n if dt[-6] in frozenset(('+', '-')):\n return datetime.strptime(dt, fmt + '%z')\n elif dt[-1] == 'Z':\n return datetime.strptime(dt, fmt + 'Z')\n return datetime.strptime(dt, fmt)\n for dt_in, dt_out in (\n ('2019-03-11T08:00:00.000Z', '2019-03-11T08:00:00'),\n ('2019-03-11T08:00:00.000+11:00', '2019-03-11T08:00:00+11:00'),\n ('2019-03-11T08:00:00.000-11:00', '2019-03-11T08:00:00-11:00')\n ):\n isoformat = to_datetime_tz(dt_in).isoformat()\n assert isoformat == dt_out, '{} != {}'.format(isoformat, dt_out)\n"
},
{
"answer_id": 58080430,
"author": "zawuza",
"author_id": 6110751,
"author_profile": "https://Stackoverflow.com/users/6110751",
"pm_score": 3,
"selected": false,
"text": "from dateutil import parser\n\ndate = parser.isoparse(\"2008-09-03T20:56:35.450686+01:00\")\nprint(date)\n 2008-09-03 20:56:35.450686+01:00\n"
},
{
"answer_id": 62769371,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 5,
"selected": false,
"text": "'Z' '+00:00' fromisoformat from datetime import datetime\n\ns = \"2008-09-03T20:56:35.450686Z\"\n\ndatetime.fromisoformat(s.replace('Z', '+00:00'))\n# datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=datetime.timezone.utc)\n strptime 'Z' fromisoformat %timeit datetime.fromisoformat(s.replace('Z', '+00:00'))\n388 ns ± 48.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n%timeit dateutil.parser.isoparse(s)\n11 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n%timeit datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')\n15.8 µs ± 1.32 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n%timeit dateutil.parser.parse(s)\n87.8 µs ± 8.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n"
},
{
"answer_id": 68562189,
"author": "Michael Dorner",
"author_id": 1864294,
"author_profile": "https://Stackoverflow.com/users/1864294",
"pm_score": 3,
"selected": false,
"text": "pandas Timestamp pandas ts_1 = pd.Timestamp('2020-02-18T04:27:58.000Z') \nts_2 = pd.Timestamp('2020-02-18T04:27:58.000')\n"
},
{
"answer_id": 74370010,
"author": "Ash Nazg",
"author_id": 17527642,
"author_profile": "https://Stackoverflow.com/users/17527642",
"pm_score": 0,
"selected": false,
"text": "datetime.fromisoformat() >>> from datetime import datetime\n>>> datetime.fromisoformat('2011-11-04T00:05:23Z')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n>>> datetime.fromisoformat('20111104T000523')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n>>> datetime.fromisoformat('2011-W01-2T00:05:23.283')\ndatetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70293/"
] |
127,817
|
<p>I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand. </p>
<p>I have the following class :</p>
<pre><code>public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
public AccountStatement(IPeriod period, int accountID)
{
StatementCharges = new List<IAccountStatementCharge>();
StartDate = new Date(period.PeriodStartDate);
EndDate = new Date(period.PeriodEndDate);
AccountID = accountID;
}
public void AddStatementCharge(IAccountStatementCharge charge)
{
StatementCharges.Add(charge);
}
</code></pre>
<p>}</p>
<p>(note startdate,enddate,accountID are automatic property to...)</p>
<p>If I use it this way :</p>
<pre><code>var accountStatement = new AccountStatement{
StartDate = new Date(2007, 1, 1),
EndDate = new Date(2007, 1, 31),
StartingBalance = 125.05m
};
</code></pre>
<p>When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null"</p>
|
[
{
"answer_id": 127840,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 5,
"selected": true,
"text": "public AccountStatement()\n{\n new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);\n}\n public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)\n{\n}\n"
},
{
"answer_id": 127852,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "public AccountStatement() : this(new Period(new NullDate().DateTime,newNullDate().DateTime), 0) { }\n public AccountStatement()\n {\n new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);\n }\n"
},
{
"answer_id": 127887,
"author": "Borek Bernard",
"author_id": 21728,
"author_profile": "https://Stackoverflow.com/users/21728",
"pm_score": -1,
"selected": false,
"text": "var accountStatement = new AccountStatement(period, accountId) {\n StartDate = new Date(2007, 1, 1),\n EndDate = new Date(2007, 1, 31),\n StartingBalance = 125.05m\n };\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419/"
] |
127,842
|
<p>We are writing a search application that saves the search criteria to session state and executes the search inside of an asp.net updatepanel. Sometimes when we execute multiple searches successively the 2nd or 3rd search will sometimes return results from the first set of search criteria. </p>
<p>Example: our first search we do a look up on "John Smith" -> John Smith results are displayed. The second search we do a look up on "Bob Jones" -> John Smith results are displayed. </p>
<p>We save all of the search criteria in session state as I said, and read it from session state inside of the ajax request to format the DB query. When we put break points in VS everything behaves as normal, but without them we get the original search criteria and results.</p>
<p>My guess is because they are saved in session, that the ajax request somehow gets its own session and saves the criteria to that, and then retrieves the criteria from that session every time, but the non-async stuff is able to see when the criteria is modified and saves the changes to state accordingly, but because they are from two different sessions there is a disparity in what is saved and read.</p>
<p>EDIT:::
To elaborate more, there was a suggestion of appending the search criteria to the query string which normally is good practice and I agree thats how it should be but following our requirements I don't see it as being viable. They want it so the user fills out the input controls hits search and there is no page reload, the only thing they see is a progress indicator on the page, and they still have the ability to navigate and use other features on the current page. If I were to add criteria to the query string I would have to do another request causing the whole page to load, which depending on the search criteria can take a really long time. This is why we are using an ajax call to perform the search and why we aren't causing another full page request..... I hope this clarifies the situation.</p>
|
[
{
"answer_id": 127903,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": false,
"text": "[WebMethod( EnableSession=true )]\npublic static void DoSomething(){\n /// ....\n}\n"
},
{
"answer_id": 2916755,
"author": "Sorin",
"author_id": 113934,
"author_profile": "https://Stackoverflow.com/users/113934",
"pm_score": 0,
"selected": false,
"text": "public class ActionRequest : IHttpHandler, IRequiresSessionState\n{\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19840/"
] |
127,867
|
<p>I have great doubts about this forum, but I am willing to be pleasantly surprised ;) <strong>Kudos and great karma to those who get me back on track.</strong></p>
<p>I am attempting to use the blitz implementation of JavaSpaces (<a href="http://www.dancres.org/blitz/blitz_js.html" rel="nofollow noreferrer">http://www.dancres.org/blitz/blitz_js.html</a>) to implement the ComputeFarm example provided at <a href="http://today.java.net/pub/a/today/2005/04/21/farm.html" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2005/04/21/farm.html</a></p>
<p>The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:</p>
<p>(yes <strong><code>com.sun.jini.mahalo.TxnMgrProxy</code></strong> is in the class path)</p>
<pre><code>2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task.
java.rmi.ServerException: RemoteException in server thread; nested exception is:
java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108)
at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101)
at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659)
at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528)
at $Proxy0.take(Unknown Source)
at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157)
at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138)
at example.squares.SquaresJob.collectResults(SquaresJob.java:47)
at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28)
Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138)
at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221)
at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049)
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599)
... 17 more
</code></pre>
|
[
{
"answer_id": 128936,
"author": "deltaVee",
"author_id": 21707,
"author_profile": "https://Stackoverflow.com/users/21707",
"pm_score": 0,
"selected": false,
"text": "C:\\dev\\jini\\blitz>javap com.sun.jini.mahalo.TxnMgrProxy\nCompiled from \"TxnMgrProxy.java\"\nclass com.sun.jini.mahalo.TxnMgrProxy extends java.lang.Object implements net.jini.core.transaction.server.TransactionManager,net.jini.admin.Admi\nnistrable,java.io.Serializable,net.jini.id.ReferentUuid{\n final com.sun.jini.mahalo.TxnManager backend;\n final net.jini.id.Uuid proxyID;\n static com.sun.jini.mahalo.TxnMgrProxy create(com.sun.jini.mahalo.TxnManager, net.jini.id.Uuid);\n public net.jini.core.transaction.server.TransactionManager$Created create(long) throws net.jini.core.lease.LeaseDeniedException, java.r\nmi.RemoteException;\n public void join(long, net.jini.core.transaction.server.TransactionParticipant, long) throws net.jini.core.transaction.UnknownTransacti\nonException, net.jini.core.transaction.CannotJoinException, net.jini.core.transaction.server.CrashCountException, java.rmi.RemoteException;\n public int getState(long) throws net.jini.core.transaction.UnknownTransactionException, java.rmi.RemoteException;\n public void commit(long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotCommitException,\n java.rmi.RemoteException;\n public void commit(long, long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotCommitExce\nption, net.jini.core.transaction.TimeoutExpiredException, java.rmi.RemoteException;\n public void abort(long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotAbortException, j\nava.rmi.RemoteException;\n public void abort(long, long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotAbortExcept\nion, net.jini.core.transaction.TimeoutExpiredException, java.rmi.RemoteException;\n public java.lang.Object getAdmin() throws java.rmi.RemoteException;\n public net.jini.id.Uuid getReferentUuid();\n public int hashCode();\n public boolean equals(java.lang.Object);\n com.sun.jini.mahalo.TxnMgrProxy(com.sun.jini.mahalo.TxnManager, net.jini.id.Uuid, com.sun.jini.mahalo.TxnMgrProxy$1);\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21707/"
] |
127,886
|
<p>I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.</p>
<p>Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.</p>
<p>Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter?</p>
|
[
{
"answer_id": 128045,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": true,
"text": " public ActionResult NotAuthorized()\n {\n return View();\n }\n public ActionResult NotAuthorized()\n {\n return View(\"Foo\");\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
127,890
|
<p>Is there a specfic <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="nofollow noreferrer">Gang Of Four Design Pattern</a> that you frequently use, yet hardly see used in other peoples designs? If possible, please describe a simple example where this pattern can be useful. It doesn't have to necessarily be a Gang Of Four pattern, but please include a hyperlink to the pattern's description if you choose a non-GoF pattern.</p>
<p>Put another way:<br>
<strong>What are some good/useful design patterns that I, or someone else who does have a passing knowledge of the main patterns, may not already know?</strong></p>
|
[
{
"answer_id": 274993,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": false,
"text": "SendTo() Message MessageRecipient #include <iostream>\n#include <ostream>\nusing namespace std;\n\n// Downside: note the cyclic dependencies, typically expressed in\n// real life as include file dependency. \nstruct StartMessage;\nstruct StopMessage;\n\nclass MessageRecipient\n{\npublic:\n // Downside: hard to add new messages\n virtual void handleMessage(const StartMessage& start) = 0;\n virtual void handleMessage(const StopMessage& stop) = 0;\n};\n\nstruct Message\n{\n virtual void dispatchTo(MessageRecipient& r) const = 0;\n};\n\nstruct StartMessage : public Message\n{\n void dispatchTo(MessageRecipient& r) const\n {\n r.handleMessage(*this);\n }\n // public member data ...\n};\n\nstruct StopMessage : public Message\n{\n StopMessage() {}\n\n void dispatchTo(MessageRecipient& r) const\n {\n r.handleMessage(*this);\n }\n // public member data ...\n};\n\n// Upside: easy to add new recipient\nclass RobotArm : public MessageRecipient\n{\npublic:\n void handleMessage(const StopMessage& stop)\n {\n cout << \"Robot arm stopped\" << endl;\n }\n\n void handleMessage(const StartMessage& start)\n {\n cout << \"Robot arm started\" << endl;\n }\n};\n\nclass Conveyor : public MessageRecipient\n{\npublic:\n void handleMessage(const StopMessage& stop)\n {\n cout << \"Conveyor stopped\" << endl;\n }\n\n void handleMessage(const StartMessage& start)\n {\n cout << \"Conveyor started\" << endl;\n }\n};\n\nvoid SendTo(const Message& m, MessageRecipient& r)\n{\n // magic double dispatch\n m.dispatchTo(r);\n}\n\nint main()\n{\n Conveyor c;\n RobotArm r;\n\n SendTo(StartMessage(), c);\n SendTo(StartMessage(), r);\n SendTo(StopMessage(), r);\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16448/"
] |
127,899
|
<p>i have a control that is organized like this</p>
<p><img src="https://dl-web.getdropbox.com/get/jsstructure.GIF?w=faef1ed3" alt="alt text"></p>
<p>and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js.</p>
<p>Here is what i have so far (in the user control )</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsClientScriptBlockRegistered("jqModal"))
Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js"));
if (!Page.IsClientScriptBlockRegistered("jQuery"))
Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js"));
if (!Page.IsClientScriptBlockRegistered("tellAFriend"))
Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js"));
}
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 127935,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "public static class PageHelper {\n public static void RegisterClientScriptIfNeeded( Page page, string key, string url ) {\n if( false == page.IsClientScriptBlockRegistered( key )) {\n page.ClientScript.RegisterClientScriptInclude( key , ResolveClientUrl( url ));\n }\n }\n}\n"
},
{
"answer_id": 127988,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 0,
"selected": false,
"text": " protected override void Render(HtmlTextWriter writer)\n {\n base.Render(writer);\n string[] items = new string[] { \"jqModal\", \"jQuery\", \"tellAFriend\" };\n //Check if the Script has already been rendered during this request.\n foreach(string jsFile in items)\n { \n if (!Context.Items.Contain(sjsFile))\n {\n //Specify that the Script has been rendered during this request.\n Context.Items.Add(jsFile,true);\n //Write the script to the page via the control\n writer.Write(string.Format(SCRIPTTAG, ResolveUrl(jsFile)));\n }\n }\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
] |
127,912
|
<p>Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid. </p>
<p>I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win32api directly from IronPython. Is there a way to do this using built-in .net classes? Most of the stuff I have come across recommends using win32api, such as below.</p>
<p><a href="https://stackoverflow.com/questions/79111/net-c-getting-child-windows-when-you-only-have-a-process-handle-or-pid">.NET (C#): Getting child windows when you only have a process handle or PID?</a></p>
<p>UPDATE: I found a work-around to what I was trying to do. Answer below. </p>
|
[
{
"answer_id": 11841411,
"author": "Jonas Lundgren",
"author_id": 1482659,
"author_profile": "https://Stackoverflow.com/users/1482659",
"pm_score": 2,
"selected": false,
"text": "import ctypes\nbuffer = ctypes.create_string_buffer(100)\nctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))\nprint buffer.value\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9267/"
] |
127,932
|
<p>I get this error when I do an <code>svn update</code>:</p>
<blockquote>
<p>Working copy XXXXXXXX locked Please
execute "Cleanup" command</p>
</blockquote>
<p>When I run cleanup, I get</p>
<blockquote>
<p>Cleanup failed to process the
following paths: XXXXXXXX</p>
</blockquote>
<p>How do I get out of this loop?</p>
|
[
{
"answer_id": 1125468,
"author": "Intu",
"author_id": 138079,
"author_profile": "https://Stackoverflow.com/users/138079",
"pm_score": 8,
"selected": false,
"text": ".svn lock .svn find . -name 'lock' -exec rm -v {} \\;\n .svn"
},
{
"answer_id": 1344837,
"author": "BradS",
"author_id": 10537,
"author_profile": "https://Stackoverflow.com/users/10537",
"pm_score": 9,
"selected": false,
"text": "svn cleanup"
},
{
"answer_id": 3964859,
"author": "The Love Of Ocde",
"author_id": 479975,
"author_profile": "https://Stackoverflow.com/users/479975",
"pm_score": 1,
"selected": false,
"text": "find \"/the/path/to/your/directory\" -name .svn -type d | xargs chmod 0777 -R\n cleanup"
},
{
"answer_id": 9416442,
"author": "brian.clear",
"author_id": 181947,
"author_profile": "https://Stackoverflow.com/users/181947",
"pm_score": -1,
"selected": false,
"text": "http://itunes.apple.com/gb/app/easyfind/id411673888?mt=12\n"
},
{
"answer_id": 10537284,
"author": "Karthik",
"author_id": 456408,
"author_profile": "https://Stackoverflow.com/users/456408",
"pm_score": 0,
"selected": false,
"text": "chmod +w <dir_name>\n"
},
{
"answer_id": 12326057,
"author": "Gad D Lord",
"author_id": 69358,
"author_profile": "https://Stackoverflow.com/users/69358",
"pm_score": 7,
"selected": false,
"text": "delete from WC_LOCK\n WORK_QUEUE"
},
{
"answer_id": 15782484,
"author": "algreat",
"author_id": 755223,
"author_profile": "https://Stackoverflow.com/users/755223",
"pm_score": 0,
"selected": false,
"text": "Tortoise SVN clean up"
},
{
"answer_id": 31747092,
"author": "swiftBoy",
"author_id": 1371853,
"author_profile": "https://Stackoverflow.com/users/1371853",
"pm_score": 0,
"selected": false,
"text": "svn cleanup <Dir path of my SVN project code>"
},
{
"answer_id": 31747299,
"author": "dreamzor",
"author_id": 1280800,
"author_profile": "https://Stackoverflow.com/users/1280800",
"pm_score": 1,
"selected": false,
"text": "$ svn cleanup\nsvn: E155004: Run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)\nsvn: E155004: Working copy locked; try running 'svn cleanup' on the root of the working copy ('/my/directory') instead.\nsvn: E155004: Working copy '/my/directory' locked\nsvn: E200030: sqlite[S14]: unable to open database file\nsvn: E200030: Additional errors:\nsvn: E200030: sqlite[S14]: unable to open database file\n"
},
{
"answer_id": 35192644,
"author": "Hiren Patel",
"author_id": 4233197,
"author_profile": "https://Stackoverflow.com/users/4233197",
"pm_score": 7,
"selected": false,
"text": "Clean up working copy status Break locks Fix time stamps Vacuum pristine copies Refresh shell overlays Include externals"
},
{
"answer_id": 36406608,
"author": "Alejandro Pablo Tkachuk",
"author_id": 4987783,
"author_profile": "https://Stackoverflow.com/users/4987783",
"pm_score": 0,
"selected": false,
"text": "update checkout $sudo"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
127,936
|
<p>I have an application that has created a number of custom event log sources to help filter its output. How can I delete the custom sources from the machine WITHOUT writing any code as running a quick program using System.Diagnostics.EventLog.Delete is not possible.</p>
<p>I've tried using RegEdit to remove the custom sources from [HKEY_LOCAL_MACHINE\SYSTEM\ControlSetXXX\Services\Eventlog] however the application acts as if the logs still exist behind the scenes.</p>
<p>What else am I missing?</p>
|
[
{
"answer_id": 28902869,
"author": "Kapé",
"author_id": 465942,
"author_profile": "https://Stackoverflow.com/users/465942",
"pm_score": 5,
"selected": false,
"text": "Remove-EventLog -LogName \"Custom log name\"\n\nRemove-EventLog -Source \"Custom source name\"\n"
},
{
"answer_id": 37416804,
"author": "Moondustt",
"author_id": 1918728,
"author_profile": "https://Stackoverflow.com/users/1918728",
"pm_score": 3,
"selected": false,
"text": "[System.Diagnostics.EventLog]::Delete(\"WrongNamedEventLog\");\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15570/"
] |
127,973
|
<p>I've been aware of Steve Yegge's advice to <a href="http://steve.yegge.googlepages.com/effective-emacs#item1" rel="nofollow noreferrer">swap Ctrl and Caps Lock</a> for a while now, although I don't use Emacs. I've just tried swapping them over as an experiment and I'm finding it difficult to adjust. There are several shortcuts that are second nature to me now and I hadn't realised quite how ingrained they are in how I use the keyboard.</p>
<p>In particular, I keep going to the old Ctrl key for <kbd>Ctrl</kbd>+<kbd>Z</kbd> (undo), and for cut, copy & paste operations (<kbd>Ctrl</kbd>+ <kbd>X</kbd>, <kbd>C</kbd> and <kbd>V</kbd>). Experimenting with going from the home position to <kbd>Ctrl</kbd>+<kbd>Z</kbd> I don't know which finger to put on <kbd>Z</kbd>, as it feels awkward with either my ring, middle or index finger. Is this something I'll get used to the same way I've got used to the original position and I should just give it time or <strong>is this arrangement not suited to windows keyboard shortcuts</strong>.</p>
<p>I'd be interested to hear from people who have successfully made the transition as well as those who have tried it and move back, but particularly from people who were doing it on <strong>windows</strong>. </p>
<p>Will it lead to any improvement in my typing speed or comfort when typing.</p>
<p>Do you have any tips for finger positions or typing training to speed up the transition.</p>
|
[
{
"answer_id": 35177791,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 3,
"selected": true,
"text": "#IfWinActive\n ^+Capslock::Capslock ; make CTRL+SHIFT+Caps-Lock the Caps Lock toggle\nreturn\n"
},
{
"answer_id": 39603656,
"author": "One In a Million Apps",
"author_id": 6542138,
"author_profile": "https://Stackoverflow.com/users/6542138",
"pm_score": 0,
"selected": false,
"text": "REGEDIT4\n\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n\"Scancode Map\"=hex:00,00,00,00,00,00,00,00,03,00,00,00,1d,00,3a,00,3a,00,1d,00,00,00,00,00\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] |
127,974
|
<p>SQL is not my forte, but I'm working on it - thank you for the replies.</p>
<p>I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard.</p>
<p>I've gotten as far as calculating the total percent complete for each individual service for a specific Contract_ServiceID, but how do I return all the services percentages for all the contracts? Something like this:</p>
<p>Contract Service Percent complete
<hr>
abc Company service 1 98%<br>
abc Company service 2 100%<br>
xyz Company service 1 50%
<br>
<br>
Here's what I have so far:</p>
<pre><code>SELECT
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
WHERE Contract_ServiceId = '[an id]'
GROUP BY Contract_ServiceID
</code></pre>
<p>This gets me too:<br><br>
Contract_serviceid Percent Complete
<hr>
[an id] 100%</p>
<p>EDIT: Tables didn't show up in post.</p>
|
[
{
"answer_id": 128017,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 1,
"selected": false,
"text": "SELECT \n Contract,\n Contract_ServiceId, \n (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as \"Percent Complete\" \nFROM dbo.Standard sta WITH (NOLOCK) \n INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY Contract, Contract_ServiceID\n"
},
{
"answer_id": 128020,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": true,
"text": "SELECT con.ContractId, \n con.Contract,\n conSer.Contract_ServiceID,\n conSer.Service, \n (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as \"Percent Complete\" \nFROM dbo.Standard sta WITH (NOLOCK) \n INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId\n INNER JOIN dbo.Contract con ON con.ContractId = conSer.ContractId\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service\n"
},
{
"answer_id": 128200,
"author": "Chuck",
"author_id": 9714,
"author_profile": "https://Stackoverflow.com/users/9714",
"pm_score": 1,
"selected": false,
"text": "SELECT \n ContractID\n ISNULL(Contract_ServiceId, '-1') -- or some other stand in value\n ISNULL((SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100, 0) as \"Percent Complete\" \nFROM \n Contract AS con\n LEFT OUTER JOIN dbo.Contract_Service conSer ON con.ContractID = conSer.ContractID\n LEFT OUTER JOIN dbo.Standard sta WITH (NOLOCK) ON conSer.ServiceId = sta.StandardID\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY \n ContractID, Contract_ServiceID\n"
},
{
"answer_id": 128662,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/127974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21717/"
] |
128,008
|
<p>When I iterate over the values or keys are they going to correlate? Will the second key map to the second value?</p>
|
[
{
"answer_id": 128025,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "Map<Integer, Integer> a = new HashMap<Integer, Integer>(2);\na.put(1, 2);\na.put(2, 3);\nfor (Map.Entry<Integer, Integer> entry : a.entrySet()) {\n System.out.println(entry.getKey() + \" => \" + entry.getValue());\n}\n 1 => 2\n2 => 3\n3 => 3\n"
},
{
"answer_id": 128085,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 3,
"selected": false,
"text": "Map<String, String> map = new HashMap<String, String>();\n\n// populate hashmap\n\nfor (Map.Entry<String, String> entry : map.entrySet()) {\n String key = entry.getKey();\n String value = entry.getValue();\n // your code here\n}\n"
},
{
"answer_id": 128801,
"author": "oreoshake",
"author_id": 402777,
"author_profile": "https://Stackoverflow.com/users/402777",
"pm_score": 0,
"selected": false,
"text": "for (Map.Entry<Integer, Integer> entry : a.entrySet()) \n"
},
{
"answer_id": 1701684,
"author": "Adam Al-Salman",
"author_id": 207033,
"author_profile": "https://Stackoverflow.com/users/207033",
"pm_score": 2,
"selected": false,
"text": "public class Test {\n public static void main(String[] args) {\n HashMap <String,String> hashmap = new HashMap<String,String>();\n hashmap.put(\"one\", \"1\");\n hashmap.put(\"two\", \"2\");\n hashmap.put(\"three\", \"3\");\n hashmap.put(\"four\", \"4\");\n hashmap.put(\"five\", \"5\");\n hashmap.put(\"six\", \"6\");\n\n Iterator <String> keyIterator = hashmap.keySet().iterator();\n Iterator <String> valueIterator = hashmap.values().iterator();\n\n while(keyIterator.hasNext()) {\n System.out.println(\"key: \"+keyIterator.next());\n }\n\n while(valueIterator.hasNext()) {\n System.out.println(\"value: \"+valueIterator.next());\n }\n }\n}\n\nkey: two\nkey: five\nkey: one\nkey: three\nkey: four\nkey: six\nvalue: 2\nvalue: 5\nvalue: 1\nvalue: 3\nvalue: 4\nvalue: 6\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
128,011
|
<p>In a <code>CakePHP 1.2</code> app, I'm using </p>
<pre><code><?php $session->flash();?>
</code></pre>
<p>to output messages like "Record edited". It's working great.</p>
<p>However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.</p>
<p>The flash message wraps itself in a <code>DIV tag</code>. I want to insert my dismiss code into that div, but I don't know how.</p>
|
[
{
"answer_id": 128033,
"author": "Justin",
"author_id": 43,
"author_profile": "https://Stackoverflow.com/users/43",
"pm_score": 2,
"selected": true,
"text": "layouts/message.ctp\n <?php echo $content_for_layout; ?>\n $this->Session->setFlash('Your record has been created! Wicked!','message');\n"
},
{
"answer_id": 747226,
"author": "RichardAtHome",
"author_id": 7032,
"author_profile": "https://Stackoverflow.com/users/7032",
"pm_score": 1,
"selected": false,
"text": "$(document).ready(function() {\n\n $(\"#flashMessage\").each(function() {\n $close = $(\"<span class='close'>Close</span>\");\n $close.click(function () {\n $(this).parent().hide(\"slow\");\n });\n $(this).append($close);\n });\n\n});\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
128,012
|
<p>I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells.</p>
<p>Here's my code so far:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"EntryCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
textView.numberOfLines = 0;
textView.text = [entries objectAtIndex:[indexPath row]];
[cell.contentView addSubview:textView];
[textView release];
return cell;
}
</code></pre>
<p>This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size.</p>
<p><code>[textView sizeToFit]</code> and/or <code>[cell sizeToFit]</code> don't seem to work.</p>
<p>Here's how I want the UITableView to look:</p>
<pre><code>----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
</code></pre>
<p>Does anyone know how to do this properly?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 2358335,
"author": "Olof",
"author_id": 283153,
"author_profile": "https://Stackoverflow.com/users/283153",
"pm_score": 1,
"selected": false,
"text": "- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n\n if(indexPath.row<[notesModel numberOfNotes]){\n NSString *cellText = [@\"Your text...\"];\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:12.0];\n CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);\n CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];\n\n return labelSize.height + 20;\n }\n else {\n return 20;\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119/"
] |
128,015
|
<p>Normal OSX applications eat the first mouse click when not focused to first focus the application. Then future clicks are processed by the application. iTunes play/pause button and Finder behave differently, the first click is acted on even when not focused. I am looking for a way to force an existing application (Remote Desktop Connection.app) to act on the first click and not just focus.</p>
|
[
{
"answer_id": 28377340,
"author": "johndpope",
"author_id": 284895,
"author_profile": "https://Stackoverflow.com/users/284895",
"pm_score": 0,
"selected": false,
"text": "- (void)loadView {\n NSLog(@\"loadView\");\n\n\n self.view = [[NSView alloc] initWithFrame:\n [[app.window contentView] frame]];\n [self.view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];\n\n int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways);\n trackingArea0 = [[NSTrackingArea alloc] initWithRect:self.view.bounds\n options:opts\n owner:self\n userInfo:nil];\n [self.view addTrackingArea:trackingArea0];\n\n\n}\n- (void)mouseEntered:(NSEvent *)theEvent {\n NSLog(@\"entered\");\n\n\n if ([[NSApplication sharedApplication] respondsToSelector:@selector(activateIgnoringOtherApps:)]) {\n [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];\n }\n\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21737/"
] |
128,016
|
<p>I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a <code>JFileChooser</code>; when it is closed, the absolute path of the selected file is written to a <code>JTextField</code>.</p>
<p>The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.</p>
<p>I've tried this, but it didn't do anything, the text field is still too wide:</p>
<pre><code>fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));
</code></pre>
<p>Currently, when it is empty, it is already 400px long, because of <code>GridBagConstraints</code> attached to it.</p>
<p>I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.</p>
<p>So, how do I set the max size for a <code>JTextField</code> ?</p>
|
[
{
"answer_id": 128040,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 5,
"selected": true,
"text": "filedNameTextField = new JTextField(80); // 80 == columns\n JScrollPane setMaximumSize setPreferredWidth"
},
{
"answer_id": 128191,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 2,
"selected": false,
"text": "setMaximumSize"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
128,028
|
<p>We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.</p>
<p>For example, the page at the URL <a href="http://oursite/Page.aspx?a=1&b=2" rel="nofollow noreferrer">http://oursite/Page.aspx?a=1&b=2</a> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />"</p>
<p>We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).</p>
<p>One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.</p>
<p>One of the parameters is always a "P" followed by 9 integers.
The other parameter is always 15 alpha-numeric characters.
(Thanks Liam for suggesting I make that clear).</p>
<p>Does anybody have any suggestions for us?</p>
<p>Thank you very much for your time.</p>
|
[
{
"answer_id": 128703,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 5,
"selected": true,
"text": "let searchParams/*: URLSearchParams*/ = new URL(\n myUrl,\n // Supply a base URL whose scheme allows\n // query parameters in case `myUrl` is scheme or\n // path relative.\n 'http://example.com/'\n).searchParams;\nconsole.log(searchParams.get('paramName')); // One value\nconsole.log(searchParams.getAll('paramName'));\n .get .getAll /path?foo=bar&foo=baz function queryParameters(query) {\n var keyValuePairs = query.split(/[&?]/g);\n var params = {};\n for (var i = 0, n = keyValuePairs.length; i < n; ++i) {\n var m = keyValuePairs[i].match(/^([^=]+)(?:=([\\s\\S]*))?/);\n if (m) {\n var key = decodeURIComponent(m[1]);\n (params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));\n }\n }\n return params;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21732/"
] |
128,035
|
<p>Note: while the use-case described is about using submodules within a project, the same applies to a normal <code>git clone</code> of a repository over HTTP.</p>
<p>I have a project under Git control. I'd like to add a submodule:</p>
<pre><code>git submodule add http://github.com/jscruggs/metric_fu.git vendor/plugins/metric_fu
</code></pre>
<p>But I get</p>
<pre><code>...
got 1b0313f016d98e556396c91d08127c59722762d0
got 4c42d44a9221209293e5f3eb7e662a1571b09421
got b0d6414e3ca5c2fb4b95b7712c7edbf7d2becac7
error: Unable to find abc07fcf79aebed56497e3894c6c3c06046f913a under http://github.com/jscruggs/metri...
Cannot obtain needed commit abc07fcf79aebed56497e3894c6c3c06046f913a
while processing commit ee576543b3a0820cc966cc10cc41e6ffb3415658.
fatal: Fetch failed.
Clone of 'http://github.com/jscruggs/metric_fu.git' into submodule path 'vendor/plugins/metric_fu'
</code></pre>
<p>I have my HTTP_PROXY set up:</p>
<pre><code>c:\project> echo %HTTP_PROXY%
http://proxy.mycompany:80
</code></pre>
<p>I even have a global Git setting for the http proxy:</p>
<pre><code>c:\project> git config --get http.proxy
http://proxy.mycompany:80
</code></pre>
<p>Has anybody gotten HTTP fetches to consistently work through a proxy? What's really strange is that a few project on GitHub work fine (<a href="http://github.com/collectiveidea/awesome_nested_set/" rel="noreferrer"><code>awesome_nested_set</code></a> for example), but others consistently fail (<a href="http://github.com/rails/rails/" rel="noreferrer">rails</a> for example).</p>
|
[
{
"answer_id": 128198,
"author": "sethbc",
"author_id": 21722,
"author_profile": "https://Stackoverflow.com/users/21722",
"pm_score": 6,
"selected": false,
"text": "GIT_CURL_VERBOSE=1\n"
},
{
"answer_id": 397642,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 8,
"selected": true,
"text": "http_proxy HTTP_PROXY"
},
{
"answer_id": 3406766,
"author": "Derek Mahar",
"author_id": 107158,
"author_profile": "https://Stackoverflow.com/users/107158",
"pm_score": 9,
"selected": false,
"text": "http.proxy git config --global http.proxy http://proxy.mycompany:80\n git config --global http.proxy http://mydomain\\\\myusername:mypassword@myproxyserver:8080/\n"
},
{
"answer_id": 9449944,
"author": "steve98177",
"author_id": 1191400,
"author_profile": "https://Stackoverflow.com/users/1191400",
"pm_score": 3,
"selected": false,
"text": "git: git clone git://github.com/miksago/node-websocket-server.git\n curl github.com http_proxy http git clone http://github.com/miksago/node-websocket-server.git\n\n->>> fatal: Unable to find remote helper for 'http' <<<-\n ./configure --with-curl --with-expat\n curl --with-curl git yum install curl-devel\n(expat-devel-1.95.8-8.3.el5_5.3.i386 was already installed).\n git /usr/local git* /usr/local/share /usr/local/libexec curl expat configure export CURLDIR=/usr/include \nexport EXPATDIR=/usr/include\n configure configure ./configure --with-curl --with-expat\n http git git clone http://github.com/miksago/node-websocket-server.git\nCloning into 'node-websocket-server'...\n* Couldn't find host github.com in the .netrc file, using defaults\n* About to connect() to proxy proxy.entp.attws.com port 8080\n* Trying 135.214.40.30... * connected\n...\n"
},
{
"answer_id": 12970322,
"author": "Stéphane B.",
"author_id": 281600,
"author_profile": "https://Stackoverflow.com/users/281600",
"pm_score": 4,
"selected": false,
"text": "[http]\n proxy = http://proxy.mycompany:80\n"
},
{
"answer_id": 14750116,
"author": "Max MacLeod",
"author_id": 2044766,
"author_profile": "https://Stackoverflow.com/users/2044766",
"pm_score": 7,
"selected": false,
"text": "Server: myproxyserver\nPort: 8080\nUsername: mydomain\\myusername\nPassword: mypassword\n .gitconfig git config --global http.proxy http://mydomain\\\\myusername:mypassword@myproxyserver:8080\n https .gitconfig cat .gitconfig [http]\n proxy = http://mydomain\\\\myusername:mypassword@myproxyserver:8080\n"
},
{
"answer_id": 15342043,
"author": "bbaassssiiee",
"author_id": 571517,
"author_profile": "https://Stackoverflow.com/users/571517",
"pm_score": 5,
"selected": false,
"text": "git config --global http.proxy http://proxy:8081\n"
},
{
"answer_id": 16794492,
"author": "Carlosin",
"author_id": 659360,
"author_profile": "https://Stackoverflow.com/users/659360",
"pm_score": 4,
"selected": false,
"text": "http.proxy GIT_PROXY_COMMAND authfile user_name:password user_name password echo \"username:password\" > ~/.ssh/authfile ~/.ssh/config 644 chmod 644 ~/.ssh/config ~/.ssh/config Host github.com\n HostName github.com\n ProxyCommand /usr/local/bin/corkscrew <your.proxy> <proxy port> %h %p <path/to/authfile>\n User git\n git@github.com"
},
{
"answer_id": 21903948,
"author": "Boris Brodski",
"author_id": 1860309,
"author_profile": "https://Stackoverflow.com/users/1860309",
"pm_score": 4,
"selected": false,
"text": "[http]\n proxy = http://localhost:3128 # change port as necessary\n"
},
{
"answer_id": 22512965,
"author": "Rob Koch",
"author_id": 73382,
"author_profile": "https://Stackoverflow.com/users/73382",
"pm_score": 0,
"selected": false,
"text": "Microsoft Windows [Version 6.1.7601]\nCopyright (c) 2009 Microsoft Corporation. All rights reserved.\n\nc:\\git\\meantest>git clone http://github.com/linnovate/mean.git\nCloning into 'mean'...\nfatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect\nto github.com:80; No error\n\nc:\\git\\meantest>git clone https://github.com/linnovate/mean.git\nCloning into 'mean'...\nremote: Reusing existing pack: 2587, done.\nremote: Counting objects: 27, done.\nremote: Compressing objects: 100% (24/24), done.\nrRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects: 98% (2562/26\n\nReceiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.\nResolving deltas: 100% (1166/1166), done.\nChecking connectivity... done\n"
},
{
"answer_id": 27630424,
"author": "alijandro",
"author_id": 4326936,
"author_profile": "https://Stackoverflow.com/users/4326936",
"pm_score": 6,
"selected": false,
"text": "-c, --config <key=value> git clone $ git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git --config \"http.proxy=proxyHost:proxyPort\"\n"
},
{
"answer_id": 29534591,
"author": "Lesswire",
"author_id": 1348335,
"author_profile": "https://Stackoverflow.com/users/1348335",
"pm_score": 3,
"selected": false,
"text": "sudo apt-get install socat\n #!/bin/sh \n_proxy=192.168.192.1 \n_proxyport=3128 \nexec socat STDIO PROXY:$_proxy:$1:$2,proxyport=$_proxyport\n chmod a+x gitproxy\n export PATH=$BIN_PATH:$PATH\ngit config --global core.gitproxy gitproxy\n"
},
{
"answer_id": 32744849,
"author": "TonyT_32909023190",
"author_id": 2188765,
"author_profile": "https://Stackoverflow.com/users/2188765",
"pm_score": 4,
"selected": false,
"text": "git config --global url.\"https://github.com/\".insteadOf git://github.com/\n"
},
{
"answer_id": 35148754,
"author": "School Boy",
"author_id": 833024,
"author_profile": "https://Stackoverflow.com/users/833024",
"pm_score": 2,
"selected": false,
"text": "proxy = https://your_proxy:your_port\n proxy = http://your_proxy:your_port\n"
},
{
"answer_id": 35750908,
"author": "Ravi Parekh",
"author_id": 410439,
"author_profile": "https://Stackoverflow.com/users/410439",
"pm_score": 0,
"selected": false,
"text": "Goto ->\n**Windows**\n1. msysgit\\installer-tmp\\etc\\gitconfig\n Under [http]\n proxy = http://user:pass@url:port\n\n**Linux**\n1. msysgit\\installer-tmp\\setup-msysgit.sh\n export HTTP_PROXY=\"http://USER:PASS@proxy.abc.com:8080\"\n"
},
{
"answer_id": 36470209,
"author": "DomTomCat",
"author_id": 1150303,
"author_profile": "https://Stackoverflow.com/users/1150303",
"pm_score": 0,
"selected": false,
"text": "git:// http[s]://"
},
{
"answer_id": 40210253,
"author": "Vagner Nogueira",
"author_id": 5484266,
"author_profile": "https://Stackoverflow.com/users/5484266",
"pm_score": 3,
"selected": false,
"text": "git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port\n"
},
{
"answer_id": 40787525,
"author": "Clairton Luz",
"author_id": 2795762,
"author_profile": "https://Stackoverflow.com/users/2795762",
"pm_score": 3,
"selected": false,
"text": "git config --global http.proxy http://user:password@domain:port\n git config --global http.proxy http://clairton:123456@proxy.clairtonluz.com.br:8080\n"
},
{
"answer_id": 42374063,
"author": "Montells",
"author_id": 818094,
"author_profile": "https://Stackoverflow.com/users/818094",
"pm_score": 2,
"selected": false,
"text": "git config --add http.proxy http://user:password@proxy_host:proxy_port\n"
},
{
"answer_id": 42955161,
"author": "Fangxing",
"author_id": 5615038,
"author_profile": "https://Stackoverflow.com/users/5615038",
"pm_score": 2,
"selected": false,
"text": "proxychains git pull ...\n"
},
{
"answer_id": 51867766,
"author": "Thor88",
"author_id": 2415156,
"author_profile": "https://Stackoverflow.com/users/2415156",
"pm_score": 3,
"selected": false,
"text": "git config --global credential.helper wincred\n git config -l\n git config --system --unset credential.helper\n git config --global http.proxy http://<YOUR WIN LOGIN NAME>@proxy:80\n git config --global -l\n"
},
{
"answer_id": 59062896,
"author": "Nguyen Van Duc",
"author_id": 5398157,
"author_profile": "https://Stackoverflow.com/users/5398157",
"pm_score": 2,
"selected": false,
"text": "echo 'export http_proxy=http://username:password@roxy_host:port/' >> ~/.bash_profile\necho 'export https_proxy=http://username:password@roxy_host:port' >> ~/.bash_profile\n"
},
{
"answer_id": 59282697,
"author": "gratinierer",
"author_id": 4994931,
"author_profile": "https://Stackoverflow.com/users/4994931",
"pm_score": 2,
"selected": false,
"text": "git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port\n git config --global http.proxy proxy_user@proxy_ip:proxy_port\n"
},
{
"answer_id": 66889806,
"author": "Rosen Matev",
"author_id": 1630648,
"author_profile": "https://Stackoverflow.com/users/1630648",
"pm_score": 2,
"selected": false,
"text": "git config https://github.com/ git config --global 'http.https://github.com/.proxy' http://proxy.mycompany:80\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
128,038
|
<p>I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?</p>
<h3>To clarify:</h3>
<p>I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.</p>
|
[
{
"answer_id": 128119,
"author": "KC Baltz",
"author_id": 9910,
"author_profile": "https://Stackoverflow.com/users/9910",
"pm_score": 4,
"selected": false,
"text": "java.nio.channels.FileChannel.lock()"
},
{
"answer_id": 128168,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 8,
"selected": true,
"text": "try (\n FileInputStream in = new FileInputStream(file);\n java.nio.channels.FileLock lock = in.getChannel().lock();\n Reader reader = new InputStreamReader(in, charset)\n) {\n ...\n}\n"
},
{
"answer_id": 9020391,
"author": "ayengin",
"author_id": 633719,
"author_profile": "https://Stackoverflow.com/users/633719",
"pm_score": 6,
"selected": false,
"text": "java.io java.nio FileLock FileChannel try {\n // Get a file channel for the file\n File file = new File(\"filename\");\n FileChannel channel = new RandomAccessFile(file, \"rw\").getChannel();\n\n // Use the file channel to create a lock on the file.\n // This method blocks until it can retrieve the lock.\n FileLock lock = channel.lock();\n\n /*\n use channel.lock OR channel.tryLock();\n */\n\n // Try acquiring the lock without blocking. This method returns\n // null or throws an exception if the file is already locked.\n try {\n lock = channel.tryLock();\n } catch (OverlappingFileLockException e) {\n // File is already locked in this thread or virtual machine\n }\n\n // Release the lock - if it is not null!\n if( lock != null ) {\n lock.release();\n }\n\n // Close the file\n channel.close();\n } catch (Exception e) {\n }\n"
},
{
"answer_id": 44148720,
"author": "Ajay Kumar",
"author_id": 2685581,
"author_profile": "https://Stackoverflow.com/users/2685581",
"pm_score": 1,
"selected": false,
"text": " public static void main(String[] args) throws InterruptedException {\n File file = new File(FILE_FULL_PATH_NAME);\n RandomAccessFile in = null;\n try {\n in = new RandomAccessFile(file, \"rw\");\n FileLock lock = in.getChannel().lock();\n try {\n\n while (in.read() != -1) {\n System.out.println(in.readLine());\n }\n } finally {\n lock.release();\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }finally {\n try {\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n"
},
{
"answer_id": 63380116,
"author": "Vamsi",
"author_id": 1711465,
"author_profile": "https://Stackoverflow.com/users/1711465",
"pm_score": 1,
"selected": false,
"text": "public static void isFileReady(File entry) throws Exception {\n long realFileSize = entry.length();\n long currentFileSize = 0;\n do {\n try (FileInputStream fis = new FileInputStream(entry);) {\n currentFileSize = 0;\n while (fis.available() > 0) {\n byte[] b = new byte[1024];\n int nResult = fis.read(b);\n currentFileSize += nResult;\n if (nResult == -1)\n break;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"currentFileSize=\" + currentFileSize + \", realFileSize=\" + realFileSize);\n } while (currentFileSize != realFileSize);\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11906/"
] |
128,042
|
<p>In Java, I use a class in which some fields can be <code>null</code>. For example:</p>
<pre><code>class Foo {
String bar;
//....
}
</code></pre>
<p>I want to write a BarComparator for this class,</p>
<pre><code> private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
{
// Implementation goes here
}
}
</code></pre>
<p>Is there a standard way to deal with the fact that any of <code>o1</code>, <code>o2</code>, <code>o1.bar</code>, <code>o2.bar</code> can be <code>null</code>, without writing lots of nested <code>if</code>...<code>else</code>?</p>
<p>Cheers!</p>
|
[
{
"answer_id": 128084,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "if(o1==null) return x;\nif(o2==null) return x;\nif(o1.getBar()==null) return x;\nif(o2.getBar()==null) return x;\n\n// No null checks needed from this point.\n"
},
{
"answer_id": 128220,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": true,
"text": "static <T extends Comparable<T>> int cp(T a, T b) {\n return\n a==null ?\n (b==null ? 0 : Integer.MIN_VALUE) :\n (b==null ? Integer.MAX_VALUE : a.compareTo(b));\n}\n public int compare( final Foo o1, final Foo o2 ) {\n return cp(o1.field, o2.field);\n}\n"
},
{
"answer_id": 133668,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 3,
"selected": false,
"text": "private static class BarComparator\n implements Comparator<Foo>\n{\n public int compare( final Foo o1, final Foo o2 )\n {\n // o1.bar & o2.bar nulleness is taken care of by the NullComparator.\n // Easy to extend to more fields.\n return NULL_COMPARATOR.compare(o1.bar, o2.bar);\n }\n\n private final static NullComparator NULL_COMPARATOR =\n new NullComparator(false);\n}\n bar"
},
{
"answer_id": 134577,
"author": "Martin Probst",
"author_id": 22227,
"author_profile": "https://Stackoverflow.com/users/22227",
"pm_score": 1,
"selected": false,
"text": "private static class BarComparator\n implements Comparator<Foo> {\n private NullComparator delegate = new NullComparator(false);\n\n public int compare( final Foo o1, final Foo o2 )\n {\n return delegate.compare(o1.bar, o2.bar);\n }\n}\n"
},
{
"answer_id": 32914048,
"author": "savanibharat",
"author_id": 2793109,
"author_profile": "https://Stackoverflow.com/users/2793109",
"pm_score": 2,
"selected": false,
"text": " Collections.sort(list, new Comparator<Person>() {\n @Override\n public int compare(Person a, Person b) {\n if (a == null) {\n if (b == null) {\n return 0;\n }\n return -1;\n } else if (b == null) {\n return 1;\n }\n return a.getName().compareTo(b.getName());\n }\n });\n // Push nulls at the end of List\nCollections.sort(subjects1, Comparator.nullsLast(String::compareTo));\n\n// Push nulls at the beginning of List\nCollections.sort(subjects1, Comparator.nullsFirst(String::compareTo));\n"
},
{
"answer_id": 33392030,
"author": "Wim Deblauwe",
"author_id": 40064,
"author_profile": "https://Stackoverflow.com/users/40064",
"pm_score": 2,
"selected": false,
"text": "org.springframework.util.comparator.NullSafeComparator SortedSet<Foo> foos = new TreeSet<>( ( o1, o2 ) -> {\n return new NullSafeComparator<>( String::compareTo, true ).compare( o1.getBar(), o2.getBar() );\n } );\n\n foos.add( new Foo(null) );\n foos.add( new Foo(\"zzz\") );\n foos.add( new Foo(\"aaa\") );\n\n foos.stream().forEach( System.out::println );\n Foo{bar='null'}\nFoo{bar='aaa'}\nFoo{bar='zzz'}\n"
},
{
"answer_id": 48227943,
"author": "Mr.Koçak",
"author_id": 4976651,
"author_profile": "https://Stackoverflow.com/users/4976651",
"pm_score": 2,
"selected": false,
"text": "Comparator<Customer> compareCustomer = Comparator.nullsLast((c1,c2) -> c1.getCustomerId().compareTo(c2.getCustomerId()));\n Comparator<Customer> compareByName = Comparator.comparing(Customer::getName,nullsLast(String::compareTo));\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] |
128,043
|
<p>I have several log files of events (one event per line). The logs can possibly overlap. The logs are generated on separate client machines from possibly multiple time zones (but I assume I know the time zone). Each event has a timestamp that was normalized into a common time (by instantianting each log parsers calendar instance with the timezone appropriate to the log file and then using getTimeInMillis to get the UTC time). The logs are already sorted by timestamp. Multiple events can occur at the same time, but they are by no means equal events.</p>
<p>These files can be relatively large, as in, 500000 events or more in a single log, so reading the entire contents of the logs into a simple Event[] is not feasible.</p>
<p>What I am trying do is merge the events from each of the logs into a single log. It is kinda like a mergesort task, but each log is already sorted, I just need to bring them together. The second component is that the same event can be witnessed in each of the separate log files, and I want to "remove duplicate events" in the file output log.</p>
<p>Can this be done "in place", as in, sequentially working over some small buffers of each log file? I can't simply read in all the files into an Event[], sort the list, and then remove duplicates, but so far my limited programming capabilities only enable me to see this as the solution. Is there some more sophisticated approach that I can use to do this as I read events from each of the logs concurrently?</p>
|
[
{
"answer_id": 128098,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 3,
"selected": false,
"text": "def merge_files(files, key_func):\n # Populate the current array with the first line from each file\n current = [file.readline() for file in files]\n while len(current) > 0:\n # Find and return the row with the lowest key according to key_func\n min_idx = min(range(len(files)), key=lambda x: return key_func(current[x]))\n yield current[min_idx]\n new_line = files[min_idx].readline()\n if not new_line:\n # EOF, remove this file from consideration\n del current[min_idx]\n del files[min_idx]\n else:\n current[min_idx] = new_line\n"
},
{
"answer_id": 128132,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 0,
"selected": false,
"text": " StringReader fileStream1;\n StringReader fileStream2;\n Event eventCursorFile1 = Event.Parse(fileStream1.ReadLine());\n Event eventCursorFile2 = Event.Parse(fileStream2.ReadLine());\n\n while !(fileStream1.EOF && fileStream2.EOF)\n {\n if (eventCursorFile1.TimeStamp < eventCursorFile2.TimeStamp)\n {\n WriteToMasterFile(eventCursorFile1);\n eventCursorFile1 = Event.Parse(fileStream1.ReadLine());\n }\n else if (eventCursorFile1.TimeStamp == eventCursorFile2.TimeStamp)\n {\n WriteToMasterFile(eventCursorFile1);\n eventCursorFile1 = Event.Parse(fileStream1.ReadLine());\n eventCursorFile2 = Event.Parse(fileStream2.ReadLine());\n }\n else\n {\n WriteToMasterFile(eventCursorFile1);\n eventCursorFile2 = Event.Parse(fileStream2.ReadLine());\n } \n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
] |
128,083
|
<p>I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.</p>
<p>I cannot seem to find an easyway to essentially do the following:</p>
<pre><code>if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
</code></pre>
<p>Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work</p>
|
[
{
"answer_id": 128101,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": true,
"text": "Visible=<%= Eval(\"type\").tostring() == \"text\") %>\n"
},
{
"answer_id": 199914,
"author": "vmarquez",
"author_id": 10740,
"author_profile": "https://Stackoverflow.com/users/10740",
"pm_score": 2,
"selected": false,
"text": "<asp:Repeater ID=\"myRepeater\" runat=\"server\" OnItemCreated=\"myRepeater_ItemCreated\">\n <ItemTemplate>\n <asp:PlaceHolder ID=\"myPlaceHolder1\" runat=\"server\"></asp:PlaceHolder>\n <br />\n </ItemTemplate>\n</asp:Repeater>\n dim plh as placeholder\ndim uc as usercontrol\nprotected sub myRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)\n if TypeOf e Is ListItemType.Item Or TypeOf e Is ListItemType.AlternatingItem Then\n plh = ctype(e.item.findcontrol(\"myPlaceHolder1\"), Placeholder)\n uc = Page.LoadControl(\"~/usercontrols/myUserControl.ascx\")\n plh.controls.add(uc)\n end if\nend sub\n"
},
{
"answer_id": 67708290,
"author": "mybrave",
"author_id": 1755565,
"author_profile": "https://Stackoverflow.com/users/1755565",
"pm_score": 0,
"selected": false,
"text": "<asp:Repeater ID=\"ItemsRepeater\" runat=\"server\" OnItemDataBound=\"ItemRepeater_ItemDataBound\">\n <itemtemplate>\n <div>\n <asp:PlaceHolder ID=\"ItemControlPlaceholder\" runat=\"server\"></asp:PlaceHolder>\n </div>\n </itemtemplate>\n</asp:Repeater>\n protected void ItemRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n var placeholder = e.Item.FindControl(\"ItemControlPlaceholder\") as PlaceHolder;\n var col = (ItemData)e.Item.DataItem;\n\n placeholder.Controls.Add(new HiddenField { Value = col.Name });\n placeholder.Controls.Add(CreateControl(col));\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032/"
] |
128,103
|
<p>Given an <code>Item</code> that has been appended to a <code>Form</code>, whats the best way to find out what index that item is at on the Form?</p>
<p><code>Form.append(Item)</code> will give me the index its initially added at, but if I later insert items before that the index will be out of sync.</p>
|
[
{
"answer_id": 128355,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": true,
"text": "private int getItemIndex(Item item, Form form) {\n for(int i = 0, size = form.size(); i < size; i++) {\n if(form.get(i).equals(item)) {\n return i;\n }\n }\n return -1;\n}\n"
},
{
"answer_id": 229418,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 0,
"selected": false,
"text": "indexOf(Item) Item Item size get Form"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
] |
128,104
|
<p>What is a good implementation of a IsLeapYear function in VBA? </p>
<p><b>Edit: </b>I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).</p>
|
[
{
"answer_id": 128105,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 6,
"selected": true,
"text": "Public Function isLeapYear(Yr As Integer) As Boolean \n\n ' returns FALSE if not Leap Year, TRUE if Leap Year \n\n isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2) \n\nEnd Function \n"
},
{
"answer_id": 128138,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 4,
"selected": false,
"text": "public function isLeapYear (yr as integer) as boolean\n isLeapYear = false\n if (mod(yr,400)) = 0 then isLeapYear = true\n elseif (mod(yr,100)) = 0 then isLeapYear = false\n elseif (mod(yr,4)) = 0 then isLeapYear = true\nend function\n"
},
{
"answer_id": 130093,
"author": "Brent.Longborough",
"author_id": 9634,
"author_profile": "https://Stackoverflow.com/users/9634",
"pm_score": 3,
"selected": false,
"text": "public function isLeapYear (yr as integer) as boolean\n if (mod(yr,4)) <> 0 then isLeapYear = false\n elseif (mod(yr,400)) = 0 then isLeapYear = true\n elseif (mod(yr,100)) = 0 then isLeapYear = false\n else isLeapYear = true\nend function\n"
},
{
"answer_id": 130864,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 2,
"selected": false,
"text": "Public Function IsLeapYear(Year As Varient) As Boolean\n IsLeapYear = IsDate(\"29-Feb-\" & Year)\nEnd Function \n"
},
{
"answer_id": 6978005,
"author": "RonnieDickson",
"author_id": 319044,
"author_profile": "https://Stackoverflow.com/users/319044",
"pm_score": 2,
"selected": false,
"text": "Public Function isLeapYear(Yr As Integer) As Boolean \n\n ' returns FALSE if not Leap Year, TRUE if Leap Year \n\n isLeapYear = (DAY(DateSerial(Yr, 3, 0)) = 29) \n\nEnd Function\n"
},
{
"answer_id": 19068554,
"author": "Bob",
"author_id": 2826585,
"author_profile": "https://Stackoverflow.com/users/2826585",
"pm_score": 1,
"selected": false,
"text": "Public Function ISLeapYear(Y As Integer) AS Boolean\n ' Uses a 2 or 4 digit year\n'To determine whether a year is a leap year, follow these steps:\n'1 If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.\n'2 If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.\n'3 If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.\n'4 The year is a leap year (it has 366 days).\n'5 The year is not a leap year (it has 365 days).\n\nIf Y Mod 4 = 0 Then ' This is Step 1 either goto step 2 else step 5\n If Y Mod 100 = 0 Then ' This is Step 2 either goto step 3 else step 4\n If Y Mod 400 = 0 Then ' This is Step 3 either goto step 4 else step 5\n ISLeapYear = True ' This is Step 4 from step 3\n Exit Function\n Else: ISLeapYear = False ' This is Step 5 from step 3\n Exit Function\n End If\n Else: ISLeapYear = True ' This is Step 4 from Step 2\n Exit Function\n End If\nElse: ISLeapYear = False ' This is Step 5 from Step 1\nEnd If\n\n\nEnd Function\n"
},
{
"answer_id": 25376739,
"author": "Dan",
"author_id": 3955115,
"author_profile": "https://Stackoverflow.com/users/3955115",
"pm_score": 1,
"selected": false,
"text": "Public Function isLeapYear(Optional intYear As Variant) As Boolean\n\n If IsMissing(intYear) Then\n intYear = Year(Date)\n End If\n\n If intYear Mod 400 = 0 Then\n isLeapYear = True\n ElseIf intYear Mod 4 = 0 And intYear Mod 100 <> 0 Then\n isLeapYear = True\n End If\n\nEnd Function\n"
},
{
"answer_id": 33808939,
"author": "AndrewJD",
"author_id": 5582161,
"author_profile": "https://Stackoverflow.com/users/5582161",
"pm_score": 0,
"selected": false,
"text": "Leap_Day_Check = Day(DateValue(\"01/03/\" & Required_Year) - 1)\n"
},
{
"answer_id": 43382759,
"author": "Harry S",
"author_id": 4476460,
"author_profile": "https://Stackoverflow.com/users/4476460",
"pm_score": 1,
"selected": false,
"text": " Function IsYLeapYear(Y%) As Boolean\n If Y Mod 4 <> 0 Then GoTo NoLY ' get rid of 75% of them\n If Y Mod 400 <> 0 And Y Mod 100 = 0 Then GoTo NoLY\n IsYLeapYear = True\n End Function\n"
},
{
"answer_id": 50692059,
"author": "chris neilsen",
"author_id": 445425,
"author_profile": "https://Stackoverflow.com/users/445425",
"pm_score": 2,
"selected": false,
"text": "Integer Long Function IsLeapYear1(Y As Integer) As Boolean\n If Y Mod 4 Then Exit Function\n If Y Mod 100 Then\n ElseIf Y Mod 400 Then Exit Function\n End If\n IsLeapYear1 = True\nEnd Function\n Public Function IsLeapYear2(yr As Integer) As Boolean\n IsLeapYear2 = Month(DateSerial(yr, 2, 29)) = 2\nEnd Function\n IsLeapYear Sub Test()\n Dim n As Long, i As Integer, j As Long\n Dim d As Long\n Dim t1 As Single, t2 As Single\n Dim b As Boolean\n\n n = 1000\n\n Debug.Print \"=============================\"\n t1 = Timer()\n For j = 1 To n\n For i = 100 To 9999\n b = IsYLeapYear1(i)\n Next i, j\n t2 = Timer()\n Debug.Print 1, (t2 - t1) * 1000\n\n t1 = Timer()\n For j = 1 To n\n For i = 100 To 9999\n b = IsLeapYear2(i)\n Next i, j\n t2 = Timer()\n Debug.Print 2, (t2 - t1) * 1000\nEnd Sub\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
128,162
|
<p>My program generates relatively simple PDF documents on request, but I'm having trouble with unicode characters, like kanji or odd math symbols. To write a normal string in PDF, you place it in brackets:</p>
<pre><code>(something)
</code></pre>
<p>There is also the option to escape a character with octal codes:</p>
<pre><code>(\527)
</code></pre>
<p>but this only goes up to 512 characters. How do you encode or escape higher characters? I've seen references to byte streams and hex-encoded strings, but none of the references I've read seem to be willing to tell me how to actually do it.</p>
<hr>
<p><strong>Edit:</strong> Alternatively, point me to a good Java PDF library that will do the job for me. The one I'm currently using is a version of gnujpdf (which I've fixed several bugs in, since the original author appears to have gone AWOL), that allows you to program against an AWT Graphics interface, and ideally any replacement should do the same.</p>
<p>The alternatives seem to be either HTML -> PDF, or a programmatic model based on paragraphs and boxes that feels very much like HTML. iText is an example of the latter. This would mean rewriting my existing code, and I'm not convinced they'd give me the same flexibility in laying out.</p>
<hr>
<p><strong>Edit 2:</strong> I didn't realise before, but the iText library has a Graphics2D API and seems to handle unicode perfectly, so that's what I'll be using. Though it isn't an answer to the question as asked, it solves the problem for me.</p>
<hr>
<p><strong>Edit 3:</strong> iText is working nicely for me. I guess the lesson is, when faced with something that seems pointlessly difficult, look for somebody who knows more about it than you.</p>
|
[
{
"answer_id": 31831124,
"author": "Algoman",
"author_id": 507970,
"author_profile": "https://Stackoverflow.com/users/507970",
"pm_score": 2,
"selected": false,
"text": "std::map<std::string, std::vector<wchar_t> > Codepage;\nstd::map<std::string, std::map<wchar_t, int> > LookupTable;\n for(std::wstring::const_iterator i = str.begin(); i != str.end(); i++)\n{ \n if(LookupTable[fontname].find(*i) == LookupTable[fontname].end())\n {\n LookupTable[fontname][*i] = Codepage[fontname].size();\n Codepage[fontname].push_back(*i);\n }\n}\n static std::string hex = \"0123456789ABCDEF\";\nstd::string result = \"<\";\nfor(std::wstring::const_iterator i = str.begin(); i != str.end(); i++)\n{ \n int id = LookupTable[fontname][*i] + 1;\n result += hex[(id & 0x00F0) >> 4];\n result += hex[(id & 0x000F)];\n}\nresult += \">\";\n 5 0 obj \n<<\n /F1\n <<\n /Type /Font\n /Subtype /Type1\n /BaseFont /Times-Roman\n /Encoding\n <<\n /Type /Encoding\n /Differences [ 1 /H /Euro /l /o /space /W /r /d /exclam ]\n >>\n >> \n>>\nendobj \n ObjectOffsets.push_back(stream->tellp()); // xrefs entry\n(*stream) << ObjectCounter++ << \" 0 obj \\n<<\\n\";\nint fontid = 1;\nfor(std::list<std::string>::iterator i = Fonts.begin(); i != Fonts.end(); i++)\n{\n (*stream) << \" /F\" << fontid++ << \" << /Type /Font /Subtype /Type1 /BaseFont /\" << *i;\n\n (*stream) << \" /Encoding << /Type /Encoding /Differences [ 1 \\n\";\n for(std::vector<wchar_t>::iterator j = Codepage[*i].begin(); j != Codepage[*i].end(); j++)\n (*stream) << \" /\" << GlyphName(*j) << \"\\n\";\n (*stream) << \" ] >>\";\n\n (*stream) << \" >> \\n\";\n}\n(*stream) << \">>\\n\";\n(*stream) << \"endobj \\n\\n\";\n const std::string GlyphName(wchar_t UnicodeCodepoint)\n{\n switch(UnicodeCodepoint)\n {\n case 0x00A0: return \"nonbreakingspace\";\n case 0x00A1: return \"exclamdown\";\n case 0x00A2: return \"cent\";\n ...\n }\n}\n"
},
{
"answer_id": 36820254,
"author": "dredkin",
"author_id": 2854853,
"author_profile": "https://Stackoverflow.com/users/2854853",
"pm_score": 4,
"selected": false,
"text": "cmap GetFontData cmap"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000/"
] |
128,190
|
<p>I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio.</p>
<p>I can get a message without any argument substitution like this:</p>
<pre><code>SELECT MSG.description from master.dbo.sysmessages MSG
INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid
WHERE MSG.error=@err AND LANG.langid=@@LANGID
</code></pre>
<p>But I have not found any way of finding out the error arguments. I want to see:</p>
<p>Constraint violation MYCONSTRAINT2 on table MYTABLE7</p>
<p>not</p>
<p>Constraint violation %s on table %s</p>
<p>Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement?</p>
|
[
{
"answer_id": 128421,
"author": "Dave Jackson",
"author_id": 12328,
"author_profile": "https://Stackoverflow.com/users/12328",
"pm_score": 1,
"selected": false,
"text": "RAISERROR ( { msg_id | msg_str } { , severity , state } \n [ , argument [ ,...n ] ] ) \n [ WITH option [ ,...n ] ] \n d or I Signed integer \no Unsigned octal \np Pointer \ns String \nu Unsigned integer \nx or X Unsigned hexadecimal \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945/"
] |
128,217
|
<p>If I create an event using <code>CreateEvent</code> in Windows, how can I check if that event is signaled or not using the debugger in Visual Studio? <code>CreateEvent</code> returns back a handle, which doesn't give me access to much information. Before I call <code>WaitForSingleObject()</code>, I want to check to see if the event is signaled before I step into the function.</p>
|
[
{
"answer_id": 131417,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 2,
"selected": false,
"text": "0:000> !handle 8 f \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21745/"
] |
128,232
|
<p>I am trying to do the following in <code>SQL*PLUS</code> in <code>ORACLE</code>.</p>
<ul>
<li>Create a variable</li>
<li>Pass it as output variable to my method invocation</li>
<li>Print the value from output variable</li>
</ul>
<p>I get</p>
<blockquote>
<p><em>undeclared variable</em></p>
</blockquote>
<p>error. I am trying to create a variable that persists in the session till i close the <code>SQL*PLUS</code> window.</p>
<pre><code>variable subhandle number;
exec MYMETHOD - (CHANGE_SET => 'SYNC_SET', - DESCRIPTION => 'Change data for emp',
- SUBSCRIPTION_HANDLE => :subhandle);
print subhandle;
</code></pre>
|
[
{
"answer_id": 128280,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "SQL> create procedure myproc (p1 out number)\n 2 is\n 3 begin\n 4 p1 := 42;\n 5 end;\n 6 /\n\nProcedure created.\n\nSQL> variable subhandle number\nSQL> exec myproc(:subhandle)\n\nPL/SQL procedure successfully completed.\n\nSQL> print subhandle\n\n SUBHANDLE\n----------\n 42\n"
},
{
"answer_id": 134880,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 0,
"selected": false,
"text": "&&variable select &&subhandle from dual\n subhandle"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15425/"
] |
128,239
|
<p>I'm using the Crystal Reports included with VisualStudio 2005. I would like to change the image that is displayed on the report at runtime ideally by building a path to the image file and then have that image displayed on the report.</p>
<p>Has anyone been able to accomplish this with this version of Crystal Reports?</p>
|
[
{
"answer_id": 582454,
"author": "e-holder",
"author_id": 22252,
"author_profile": "https://Stackoverflow.com/users/22252",
"pm_score": 2,
"selected": false,
"text": "byte[] private static byte[] m_Bitmap = null;\n\npublic byte[] Bitmap\n{\n get\n {\n FileStream fs = new FileStream(bitmapPath, FileMode.Open);\n BinaryReader br = new BinaryReader(fs);\n int length = (int)br.BaseStream.Length;\n m_Bitmap = new byte[length];\n m_Bitmap = br.ReadBytes(length);\n br.Close();\n fs.Close();\n return m_Bitmap;\n }\n}\n Bitmap"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/128239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16419/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.