qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
111,478
<p>Why is it wrong to use <code>std::auto_ptr&lt;&gt;</code> with standard containers?</p>
[ { "answer_id": 111492, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 6, "selected": false, "text": "auto_ptr auto_ptr auto_ptr auto_ptrs" }, { "answer_id": 111531, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 8, "selected": true, "text": "std::auto_ptr class X\n{\n};\n\nstd::vector<std::auto_ptr<X> > vecX;\nvecX.push_back(new X);\n\nstd::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL.\n std::unique_ptr std::shared_ptr std::weak_ptr" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129/" ]
111,504
<p>I'm trying to create a UDF in <code>SQL Server 2005 Express</code> as below:</p> <pre><code>CREATE FUNCTION [CombineValues] () RETURNS VARCHAR(8000) AS BEGIN DECLARE @CuisineList VARCHAR(8000); RETURN ( SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines ) END </code></pre> <p>Cuisines has the structure:</p> <pre><code>CuisineID INT PK, Cuisine VARCHAR(20) </code></pre> <p>When I try to create the function as above, I get an error: </p> <blockquote> <p>Msg 102, Level 15, State 1, Procedure CombineValues, Line 10 Incorrect syntax near '='.</p> </blockquote> <p>What am I doing wrong?</p>
[ { "answer_id": 111520, "author": "Donnie Thomas", "author_id": 6939, "author_profile": "https://Stackoverflow.com/users/6939", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n\nSELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines;\n\nRETURN \n(\nSELECT @CuisineList\n)\nEND\n" }, { "answer_id": 111592, "author": "TMarshall", "author_id": 8847, "author_profile": "https://Stackoverflow.com/users/8847", "pm_score": 1, "selected": true, "text": "CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n\nSELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines;\n\nRETURN \n(\nSELECT @CuisineList\n)\nEND\n" }, { "answer_id": 112429, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 1, "selected": false, "text": "1 Blah\n2 NULL\n3 Foo\n4 Cracker\n CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + \n CAST(Cuisine AS varchar(20))\n FROM Cuisines\n WHERE Cuisine Is Not NULL\n\nRETURN @CuisineList\nEND\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939/" ]
111,517
<p>When adding new properties to classes, I find myself typing the same things over and over in xcode:</p> <ol> <li><code>add TYPE *NAME;</code> (in .h interface)</li> <li><code>add @property (nonatomic, retain) TYPE *NAME;</code> (in .h)</li> <li><code>add @synthesize NAME;</code> (in .m)</li> <li><code>add [NAME release];</code> (in .m dealloc)</li> </ol> <p>(I'm in a non-garbage collected environment.)</p> <p>How can I do this automatically?</p>
[ { "answer_id": 184750, "author": "Jablair", "author_id": 24168, "author_profile": "https://Stackoverflow.com/users/24168", "pm_score": 0, "selected": false, "text": "-copyWithZone: -initWithCoder: -encodeWithCoder: -isEqual: -dealloc" }, { "answer_id": 1028743, "author": "Cal", "author_id": 87507, "author_profile": "https://Stackoverflow.com/users/87507", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python\n\nthisfile = '''%%%{PBXFilePath}%%%'''\ncode = '''%%%{PBXAllText}%%%'''\nselmark = '''%%%{PBXSelection}%%%'''\n\nimport re\n\nif thisfile.endswith('.h'):\n variableEnd = code.find('\\n', code.find('}'))\n properties = []\n memre = re.compile('\\s+(?:IBOutlet)?\\s+([^\\-+@].*? \\*?.*?;)')\n for match in memre.finditer(code[:variableEnd]):\n member = match.group(1)\n retain = member.find('*') != -1 and ', retain' or ''\n property = '@property (nonatomic%s) %s' % (retain,member)\n if code.find(property) == -1:\n properties.append(property)\n if properties:\n print '%s\\n\\n%s%s%s%s' % (code[:variableEnd],selmark,'\\n'.join(properties),selmark,code[variableEnd:])\nelif thisfile.endswith('.m'):\n headerfile = thisfile.replace('.m','.h')\n properties = []\n retains = []\n propre = re.compile('@property\\s\\((.*?)\\)\\s.*?\\s\\*?(.*?);')\n header = open(headerfile).read()\n for match in propre.finditer(header):\n if match.group(1).find('retain') != -1:\n retains.append(match.group(2))\n property = '@synthesize %s;' % match.group(2)\n if code.find(property) == -1:\n properties.append(property)\n pindex = code.find('\\n', code.find('@implementation'))\n if properties and pindex != -1:\n output = '%s\\n\\n%s%s%s' % (code[:pindex],selmark,'\\n'.join(properties),selmark)\n if retains:\n dindex = code.find('\\n', code.find('(void)dealloc'))\n output += code[pindex:dindex]\n retainsstr = '\\n\\t'.join(['[%s release];' % retain for retain in retains])\n output += '\\n\\t%s' % retainsstr\n pindex = dindex\n output += code[pindex:]\n print output\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
111,529
<p>Is there any way to create the <em>query parameters</em> for doing a <em>GET request</em> in JavaScript?</p> <p>Just like in Python you have <a href="http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html" rel="noreferrer"><code>urllib.urlencode()</code></a>, which takes in a dictionary (or list of two tuples) and creates a string like <code>'var1=value1&amp;var2=value2'</code>.</p>
[ { "answer_id": 111537, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "escape() unescape() function urlencode(str) {\nstr = escape(str);\nstr = str.replace('+', '%2B');\nstr = str.replace('%20', '+');\nstr = str.replace('*', '%2A');\nstr = str.replace('/', '%2F');\nstr = str.replace('@', '%40');\nreturn str;\n}\n\nfunction urldecode(str) {\nstr = str.replace('+', ' ');\nstr = unescape(str);\nreturn str;\n}\n" }, { "answer_id": 111545, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 9, "selected": true, "text": "function encodeQueryData(data) {\n const ret = [];\n for (let d in data)\n ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));\n return ret.join('&');\n}\n const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };\nconst querystring = encodeQueryData(data);\n" }, { "answer_id": 12040639, "author": "Manav", "author_id": 141220, "author_profile": "https://Stackoverflow.com/users/141220", "pm_score": 6, "selected": false, "text": "function encodeData(data) {\n return Object.keys(data).map(function(key) {\n return [key, data[key]].map(encodeURIComponent).join(\"=\");\n }).join(\"&\");\n} \n" }, { "answer_id": 19100387, "author": "Mat Ryer", "author_id": 117601, "author_profile": "https://Stackoverflow.com/users/117601", "pm_score": 3, "selected": false, "text": "var querystring = Arg.url({name: \"Mat\", state: \"CO\"});\n var name = Arg(\"name\");\n var params = Arg.all();\n ?query=true #hash=true Arg.query() Arg.hash()" }, { "answer_id": 31599255, "author": "Kirby", "author_id": 266531, "author_profile": "https://Stackoverflow.com/users/266531", "pm_score": 5, "selected": false, "text": "jQuery.param() const params = jQuery.param({\n var1: 'value',\n var2: 'value'\n});\n params \"var1=value&var2=value\"\n" }, { "answer_id": 40488487, "author": "Clayton K. N. Passos", "author_id": 3119452, "author_profile": "https://Stackoverflow.com/users/3119452", "pm_score": 2, "selected": false, "text": " public encodeData(data: any): string {\n return Object.keys(data).map((key) => {\n return [key, data[key]].map(encodeURIComponent).join(\"=\");\n }).join(\"&\");\n }\n" }, { "answer_id": 44273682, "author": "pscl", "author_id": 1628461, "author_profile": "https://Stackoverflow.com/users/1628461", "pm_score": 3, "selected": false, "text": "npm" }, { "answer_id": 49326302, "author": "eaorak", "author_id": 1095213, "author_profile": "https://Stackoverflow.com/users/1095213", "pm_score": 3, "selected": false, "text": "const createQueryParams = params => \n Object.keys(params)\n .map(k => `${k}=${encodeURI(params[k])}`)\n .join('&');\n const params = { name : 'John', postcode: 'W1 2DL'}\nconst queryParams = createQueryParams(params)\n name=John&postcode=W1%202DL\n" }, { "answer_id": 50436226, "author": "Przemek", "author_id": 959552, "author_profile": "https://Stackoverflow.com/users/959552", "pm_score": 4, "selected": false, "text": "Object.entries() [key, value] {a: 1, b: 2} [['a', 1], ['b', 2]] const buildURLQuery = obj =>\n Object.entries(obj)\n .map(pair => pair.map(encodeURIComponent).join('='))\n .join('&');\n buildURLQuery({name: 'John', gender: 'male'});\n \"name=John&gender=male\"\n" }, { "answer_id": 52028292, "author": "Andrew Palmer", "author_id": 4089018, "author_profile": "https://Stackoverflow.com/users/4089018", "pm_score": 8, "selected": false, "text": "const data = {\n var1: 'value1',\n var2: 'value2'\n};\n\nconst searchParams = new URLSearchParams(data);\n\n// searchParams.toString() === 'var1=value1&var2=value2'\n const querystring = require('querystring');\n\nconst data = {\n var1: 'value1',\n var2: 'value2'\n};\n\nconst searchParams = querystring.stringify(data);\n\n// searchParams === 'var1=value1&var2=value2'\n" }, { "answer_id": 64260142, "author": "Roman Morozov", "author_id": 13278378, "author_profile": "https://Stackoverflow.com/users/13278378", "pm_score": 0, "selected": false, "text": "function encodeQueryData(data) {\n const ret = [];\n for (let d in data) {\n if (typeof data[d] === 'object' || typeof data[d] === 'array') {\n for (let arrD in data[d]) {\n ret.push(`${encodeURIComponent(d)}[]=${encodeURIComponent(data[d][arrD])}`)\n }\n } else if (typeof data[d] === 'null' || typeof data[d] === 'undefined') {\n ret.push(encodeURIComponent(d))\n } else {\n ret.push(`${encodeURIComponent(d)}=${encodeURIComponent(data[d])}`)\n }\n\n }\n return ret.join('&');\n}\n\n let data = {\n user: 'Mark'\n fruits: ['apple', 'banana']\n}\n\nencodeQueryData(data) // user=Mark&fruits[]=apple&fruits[]=banana\n" }, { "answer_id": 68150539, "author": "EuberDeveloper", "author_id": 10140665, "author_profile": "https://Stackoverflow.com/users/10140665", "pm_score": 0, "selected": false, "text": "val: true value value=true const { encode } = require('queryencoder');\n\nconst object = {\n date: new Date('1999-04-23')\n};\n\n// The result is 'date=1999-04-23'\nconst queryUrl = encode(object, {\n dateParser: date => date.toISOString().slice(0, 10)\n});\n" }, { "answer_id": 70941990, "author": "Patrick José Pereira", "author_id": 7988054, "author_profile": "https://Stackoverflow.com/users/7988054", "pm_score": 0, "selected": false, "text": "let my_url = new URL(\"https://stackoverflow.com\")\nmy_url.pathname = \"/questions\"\n\nconst parameters = {\n title: \"just\",\n body: 'test'\n}\n\nObject.entries(parameters).forEach(([name, value]) => my_url.searchParams.set(name, value))\n\nconsole.log(my_url.href)\n\n" }, { "answer_id": 73678107, "author": "Amir Achhodi", "author_id": 11386802, "author_profile": "https://Stackoverflow.com/users/11386802", "pm_score": 2, "selected": false, "text": "URL URL URL let url = new URL(\"https://google.com/search\");\nurl.searchParams.set('var1', \"value1\");\nurl.searchParams.set('var2', \"value2\");\nurl.searchParams.set('var3', \"value3\");\n\nconsole.log(url)" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
111,543
<p>I'm trying to setup a new computer to synchronize with my SVN repository that's hosted with cvsdude.com.</p> <p>I get this error:</p> <p>![SVN Error][1] - <em>removed image shack image that had been replaced by an advert</em></p> <p>Here's what I did (these have worked in the past):</p> <ol> <li><p>Downloaded and installed TortoiseSVN</p></li> <li><p>Created a new folder C:\aspwebsite</p></li> <li><p>Right-clicked, chose SVN Checkout...</p></li> <li><p>Entered the following information, clicked OK:</p> <ul> <li>URL of repository: <a href="https://&lt;reponame&gt;-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://&lt;reponame&gt;-svn.cvsdude.com/aspwebsite</a></li> <li>Checkout directory: C:\aspwebsite</li> <li>Checkout depth: Fully recursive</li> <li>Omit externals: Unchecked</li> <li>Revision: HEAD revision</li> </ul></li> <li><p>Got TortoiseSVN error:</p> <ul> <li>OPTIONS of '<a href="https://&lt;reponame&gt;-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://&lt;reponame&gt;-svn.cvsdude.com/aspwebsite</a>': could not connect to server (<a href="https://&lt;reponame&gt;-svn.cvsdude.com" rel="nofollow noreferrer">https://&lt;reponame&gt;-svn.cvsdude.com</a>)</li> </ul></li> </ol> <p>Rather than getting the error, TortoiseSVN should have asked for my username and password and then downloaded about 90MB.</p> <p>Why can't I checkout from my Subversion repository?</p> <hr> <blockquote> <p><a href="https://stackoverflow.com/users/15614/kent-fredric">Kent Fredric</a> wrote:</p> <p>Either their security certificate has expired, or their hosting is broken/down.</p> <p>Contact CVSDude and ask them whats up.</p> <p>It could also be a timeout, because for me their site is <em>exhaustively</em> slow..</p> </blockquote> <p>It errors after only a couple seconds. I don't think it's a timeout.</p> <blockquote> <p><a href="https://stackoverflow.com/users/2590/matt">Matt</a> wrote:</p> <p>Try visiting <a href="https://[redacted]-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://[redacted]-svn.cvsdude.com/aspwebsite</a> and see what happens. If you can visit it in your browser, you ought to be able to get the files in your SVN client and we can work from there. If it fails, then there's your answer.</p> </blockquote> <p>I can access the site in a web browser.</p>
[ { "answer_id": 1478120, "author": "Wouter van Nifterick", "author_id": 38813, "author_profile": "https://Stackoverflow.com/users/38813", "pm_score": 5, "selected": false, "text": "C:\\Documents and Settings\\[username]\\Application Data\\Subversion\\ http-proxy-exceptions was empty [global]\nhttp-proxy-exceptions = 10.1.1.11\nhttp-proxy-host = 197.132.0.223\nhttp-proxy-port = 8080\nhttp-proxy-username = defaultusername\nhttp-proxy-password = defaultpassword\nhttp-compression = no\n" }, { "answer_id": 2246140, "author": "mcgyver5", "author_id": 188803, "author_profile": "https://Stackoverflow.com/users/188803", "pm_score": 3, "selected": false, "text": "http-proxy-host = \nssl-trust-default-ca = no\nhttp-proxy-username = \nhttp-proxy-password = \n" }, { "answer_id": 4316843, "author": "opyate", "author_id": 51280, "author_profile": "https://Stackoverflow.com/users/51280", "pm_score": 3, "selected": false, "text": "svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only\n svn --config-option servers:global:http-proxy-host=MY_PROXY_HOST --config-option servers:global:http-proxy-port=MY_PROXY_PORT checkout http://v8.googlecode.com/svn/trunk/ v8-read-only\n" }, { "answer_id": 15531509, "author": "capdragon", "author_id": 442580, "author_profile": "https://Stackoverflow.com/users/442580", "pm_score": 0, "selected": false, "text": "OPTIONS" }, { "answer_id": 16129975, "author": "user815693", "author_id": 815693, "author_profile": "https://Stackoverflow.com/users/815693", "pm_score": 0, "selected": false, "text": "svn ls https://server-ip:443/svn/project/trunk OPTIONS of 'https://…' could not connect to server (…)\n VisualSVN server 2.5.9" }, { "answer_id": 18728235, "author": "Diana", "author_id": 1182515, "author_profile": "https://Stackoverflow.com/users/1182515", "pm_score": 1, "selected": false, "text": "http-proxy-exceptions = *.repo.domain.com http-proxy-exceptions = XXX.XX.X.X" }, { "answer_id": 54089716, "author": "selma", "author_id": 7177758, "author_profile": "https://Stackoverflow.com/users/7177758", "pm_score": 0, "selected": false, "text": "AppData\\Roaming\\Subversion" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
111,568
<p>I imported a series of blogger posts (via xml) into WordPress, and the YouTube embed tags were removed. YouTube URLs in posts are not identified. Instead, just the text of the url is left. Possibly as opposed to full embed tags. I'm trying to restore the embed codes so it's seen.</p> <p>Another fact that is notable in the XML import is that [EMBLED CONTENT] appears instead of the url, that is, the video...</p>
[ { "answer_id": 6710981, "author": "LouieGeetoo", "author_id": 560089, "author_profile": "https://Stackoverflow.com/users/560089", "pm_score": 3, "selected": false, "text": "<embed> <iframe> /wp-includes kses.php kses.php //Post filtering // Post filtering\n#add_filter('content_save_pre', 'wp_filter_post_kses');\n#add_filter('excerpt_save_pre', 'wp_filter_post_kses');\n#add_filter('content_filtered_save_pre', 'wp_filter_post_kses');\n" }, { "answer_id": 16298770, "author": "Josh", "author_id": 2335630, "author_profile": "https://Stackoverflow.com/users/2335630", "pm_score": 0, "selected": false, "text": "/wp-includes kses.php kses.php //Post filtering // Post filtering\n#add_filter('content_save_pre', 'wp_filter_post_kses');\n#add_filter('excerpt_save_pre', 'wp_filter_post_kses');\n#add_filter('content_filtered_save_pre', 'wp_filter_post_kses');\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
111,578
<p>Also, where would I find them?</p>
[ { "answer_id": 32458246, "author": "mgttlinger", "author_id": 1876344, "author_profile": "https://Stackoverflow.com/users/1876344", "pm_score": 0, "selected": false, "text": "hgview tig" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
111,587
<p>How do I name a result group in a Regex? (.Net)</p>
[ { "answer_id": 111594, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "(?<NameOfGroup>[a-z]*)\n" }, { "answer_id": 111607, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "(?<first>group)(?'second'group). \n" }, { "answer_id": 111610, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "(?<NAME>EXPRESSION) or (?'NAME'EXPRESSION)\n" }, { "answer_id": 2308326, "author": "Fadrian Sudaman", "author_id": 276556, "author_profile": "https://Stackoverflow.com/users/276556", "pm_score": 0, "selected": false, "text": "(?<name>.*)\n" }, { "answer_id": 65258881, "author": "RKTM", "author_id": 14617408, "author_profile": "https://Stackoverflow.com/users/14617408", "pm_score": 0, "selected": false, "text": "(?<name>subpattern)\n (?<words>\\w+)\n \\w+" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
111,597
<p>Basically I’ve heard that certain conditions will cause .NET to blow past the <code>finally</code> block. Does anyone know what those conditions are?</p>
[ { "answer_id": 111617, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 7, "selected": true, "text": "StackOverflowException ExecutionEngineException Environment.FailFast()" }, { "answer_id": 40722083, "author": "Navneet", "author_id": 3759549, "author_profile": "https://Stackoverflow.com/users/3759549", "pm_score": 2, "selected": false, "text": "Finally background thread main foreground thread background thread background thread class Program\n{\n\n static void Main(string[] args)\n {\n Program prgm = new Program();\n Thread backgroundThread = new Thread(prgm.CheckBgThread);\n backgroundThread.IsBackground = true;\n backgroundThread.Start();\n Console.WriteLine(\"Closing the program....\");\n }\n\n void CheckBgThread()\n {\n try\n {\n Console.WriteLine(\"Doing some work...\");\n Thread.Sleep(500);\n }\n finally\n {\n Console.WriteLine(\"This should be always executed\");\n }\n }\n}\n" }, { "answer_id": 62217212, "author": "Melvyn", "author_id": 755986, "author_profile": "https://Stackoverflow.com/users/755986", "pm_score": 1, "selected": false, "text": "static class Program\n{\n [STAThread]\n static void Main()\n {\n async void ThreadExecutionAsync()\n {\n try\n {\n SynchronizationContext.SetSynchronizationContext(\n new WindowsFormsSynchronizationContext());\n\n await Task.Yield(); // Yield to the context\n\n // The WindowsFormsSynchronizationContext will schedule the continuation\n // on the main thread, so the current thread will die\n // and we will never get here...\n Debugger.Break();\n }\n finally\n {\n // Will never get here either...\n Debugger.Break();\n }\n }\n\n var thread = new Thread(ThreadExecutionAsync);\n thread.Start();\n\n Application.Run();\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
111,605
<p>No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables.</p> <p>But what kind of prefix do you use?</p> <p>I have been working on projects where we used <strong>m_</strong> as prefix, on other projects we used an underscore only (which I personally don't like, because an underscore only is not demonstrative enough).</p> <p>On another project we used a long prefix form, that also included the variable type. <strong>mul_</strong> for example is the prefix of a <strong>m</strong>ember variable of type <strong>u</strong>nsigned <strong>l</strong>ong.</p> <p>Now let me know what kind of prefix you use (and please give a reason for it).</p> <p><strong>EDIT:</strong> Most of you seem to code without special prefixes for member variables! Does this depend on the language? From my experience, <strong>C++ code</strong> tends to use an underscore or <strong>m_</strong> as a prefix for member variables. What about other languages?</p>
[ { "answer_id": 111625, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 7, "selected": true, "text": "m_ LPCSTR" }, { "answer_id": 111647, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 4, "selected": false, "text": "this this.data this->data this." }, { "answer_id": 111654, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "class CFoo \n{ \nprivate: \n int m_nAge; \n CString m_strAddress; \npublic: \n int GetAge() const { return m_nAge; } \n void SetAge(int n) { m_nAge = n; } \n CString GetAddress() const { return m_strAddress; \n void SetAddress(LPCTSTR lpsz) { m_strAddress = lpsz; } \n};\n class foo \n{ \nprivate: \n int age_; \n std::string address_; \npublic: \n int age() const { return age_; } \n void age(int a) { age_ = a; } \n std::string address() const { return address_; } \n void address(const std::string& str) { address_ = str; } \n};\n" }, { "answer_id": 111719, "author": "Phenwoods", "author_id": 16970, "author_profile": "https://Stackoverflow.com/users/16970", "pm_score": -1, "selected": false, "text": "m_" }, { "answer_id": 111749, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Dim _valueName As Integer\n\nPublic Property ValueName() As Integer\n" }, { "answer_id": 111860, "author": "goric", "author_id": 940, "author_profile": "https://Stackoverflow.com/users/940", "pm_score": 2, "selected": false, "text": "class SomeClass {\n private int mCount;\n ...\n private void SomeFunction(string pVarName) {...}\n}\n" }, { "answer_id": 111971, "author": "user10178", "author_id": 10178, "author_profile": "https://Stackoverflow.com/users/10178", "pm_score": 1, "selected": false, "text": "private int fooBar;\npublic int FooBar\n{\n get { return fooBar; }\n set { fooBar = value; }\n}\n" }, { "answer_id": 111981, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "TGpHttpRequest = class(TOmniWorker)\nstrict private\n hrHttpClient : THttpCli;\n hrPageContents: string;\n hrPassword : string;\n hrPostData : string;\n TGpHttpRequest = class(TOmniWorker)\nstrict private\n FHttpClient : THttpCli;\n FPageContents: string;\n FPassword : string;\n FPostData : string;\n" }, { "answer_id": 111997, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": -1, "selected": false, "text": "p-> __EXTERN_GLOBAL_hungariannotationvariabletypeVendorName-my_member_prefix-Category-VariableName\n" }, { "answer_id": 4416636, "author": "Igor Popov", "author_id": 354009, "author_profile": "https://Stackoverflow.com/users/354009", "pm_score": 2, "selected": false, "text": "_ this. _ this. public class Person {\n private String _name;\n\n public Person(String name) {\n _name = name;\n }\n}\n public class Person {\n private String name;\n\n public Person(String name) {\n this.name = name;\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
111,629
<p>I am interested to know what strategies people have to keep their code AND work versioned across multiple machines. For example I have a desktop PC running XP, a macbook running OSX and VMWare running XP as well as a sales laptop for running product demos. I want to know how I can always have these in sync. Subversion is a possibility for this but i find it less useful for dealing with binary files - maybe I have overlooked something here. What do other people use as they must have similar issues? Do they keep all files on a USB drive and never on the local file system. I am not always online so remote storage is not really an option.</p>
[ { "answer_id": 111668, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": ".zshrc" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20026/" ]
111,630
<p>Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):</p> <pre><code>HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL); </code></pre> <p>I'm using native C++ with the Windows API, no managed code.</p>
[ { "answer_id": 112617, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "//-- This define is normally part of the SDK but define it if this \n//-- is an older version of the SDK.\n#ifndef RT_MANIFEST\n#define RT_MANIFEST 24\n#endif\n\n//-- Add the MyApp XP Manifest file\nCREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST \"MyApp.manifest\"\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n<assemblyIdentity\n version=\"1.0.0.1\"\n processorArchitecture=\"X86\"\n name=\"Microsoft.Windows.MyApp\"\n type=\"win32\"\n/>\n<description>MyApp</description>\n</assembly>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"X86\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n />\n</dependentAssembly>\n<dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.VC80.CRT\"\n version=\"8.0.50608.0\"\n processorArchitecture=\"x86\"\n publicKeyToken=\"1fc8b3b9a1e18e3b\" />\n</dependentAssembly>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467/" ]
111,631
<p>I am working with a Visual Studio 2005 C++ solution that includes multiple projects (about 30). Based upon my experience, it often becomes annoying to maintain all the properties of the projects (i.e include path, lib path, linked libs, code generation options, ...), as you often have to click each and every project in order to modify them. The situation becomes even worse when you have multiple configurations (Debug, Release, Release 64 bits, ...).</p> <p>Real life examples:</p> <ul> <li>Assume you want to use a new library, and you need to add the include path to this library to all projects. How will you avoid to have to edit the properties of each an every project?</li> <li>Assume you want to test drive a new version of library (say version 2.1beta) so that you need to quickly change the include paths / library path / linked library for a set of projects?</li> </ul> <p>Notes:</p> <ul> <li>I am aware that it is possible to select multiple projects at a time, then make a right click and select "properties". However this method only works for properties that were already exactly identical for the different projects : you can not use it in order to add an include path to a set of project that were using different include path.</li> <li>I also know that it is possible to modify globally the environment options (Tools/Options/Project And solutions/Directories), however it is not that satisfying since it can not be integrated into a SCM</li> <li>I also know that one can add "Configurations" to a solutions. It does not helps since it makes another set of project properties to maintain</li> <li>I know that codegear C++ Builder 2009 offers a viable answer to this need through so called "Option sets" which can be inherited by several projects (I use both Visual Studio and C++ Builder, and I still thinks C++ Builder rocks on certain aspects as compared to Visual Studio) </li> <li>I expect that someone will suggest an "autconf" such as CMake, however is it possible to import vcproj files into such a tool?</li> </ul>
[ { "answer_id": 111671, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 4, "selected": false, "text": "XmlDocument #include <stdio.h>\n#include <tchar.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <boost/filesystem/convenience.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/regex.hpp>\n#include <boost/timer.hpp>\n\nusing boost::regex;\nusing boost::filesystem::path;\nusing namespace std;\n\nvector<path> GetFileList(path dir, bool recursive, regex matchExp);\nvoid FixProjectFile(path file);\nstring ReadFile( path &file );\nvoid ReplaceRuntimeLibraries( string& contents );\nvoid WriteFile(path file, string contents);\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n boost::timer stopwatch;\n boost::filesystem::path::default_name_check(boost::filesystem::native);\n regex projFileRegex(\"(.*)\\\\.vcproj\");\n path rootPath(\"D:\\\\Programming\\\\Projects\\\\IPP_Decoder\");\n\n vector<path> targetFiles = GetFileList(rootPath, true, projFileRegex);\n double listTimeTaken = stopwatch.elapsed();\n\n std::for_each(targetFiles.begin(), targetFiles.end(), FixProjectFile);\n\n double totalTimeTaken = stopwatch.elapsed();\n return 0;\n}\n\nvoid FixProjectFile(path file) {\n string contents = ReadFile(file);\n ReplaceRuntimeLibraries(contents);\n WriteFile(file, contents);\n}\n\nvector<path> GetFileList(path dir, bool recursive, regex matchExp) {\n vector<path> paths;\n try {\n boost::filesystem::directory_iterator di(dir);\n boost::filesystem::directory_iterator end_iter;\n while (di != end_iter) {\n try {\n if (is_directory(*di)) {\n if (recursive) {\n vector<path> tempPaths = GetFileList(*di, recursive, matchExp);\n paths.insert(paths.end(), tempPaths.begin(), tempPaths.end());\n }\n } else {\n if (regex_match(di->string(), matchExp)) {\n paths.push_back(*di);\n }\n }\n }\n catch (std::exception& e) {\n string str = e.what();\n cout << str << endl;\n int breakpoint = 0;\n }\n ++di;\n }\n }\n catch (std::exception& e) {\n string str = e.what();\n cout << str << endl;\n int breakpoint = 0;\n }\n return paths;\n}\n\nstring ReadFile( path &file ) {\n// cout << \"Reading file: \" << file.native_file_string() << \"\\n\";\n ifstream infile (file.native_file_string().c_str(), ios::in | ios::ate);\n assert (infile.is_open());\n\n streampos sz = infile.tellg();\n infile.seekg(0, ios::beg);\n\n vector<char> v(sz);\n infile.read(&v[0], sz);\n\n string str (v.empty() ? string() : string (v.begin(), v.end()).c_str());\n\n return str;\n}\n\nvoid ReplaceRuntimeLibraries( string& contents ) {\n regex releaseRegex(\"RuntimeLibrary=\\\"2\\\"\");\n regex debugRegex(\"RuntimeLibrary=\\\"3\\\"\");\n string releaseReplacement(\"RuntimeLibrary=\\\"0\\\"\");\n string debugReplacement(\"RuntimeLibrary=\\\"1\\\"\");\n contents = boost::regex_replace(contents, releaseRegex, releaseReplacement);\n contents = boost::regex_replace(contents, debugRegex, debugReplacement);\n}\n\nvoid WriteFile(path file, string contents) {\n ofstream out(file.native_file_string().c_str() ,ios::out|ios::binary|ios::trunc); \n out.write(contents.c_str(), contents.length());\n}\n using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml;\nusing System.IO;\n\nnamespace ProjectUpdater\n{\n class Program\n {\n static public String rootPath = \"D:\\\\dev\\\\src\\\\co\\\\UMC6\\\\\";\n static void Main(string[] args)\n {\n String path = \"D:/dev/src/co/UMC6/UMC.vcproj\";\n FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n XmlDocument xmldoc = new XmlDocument();\n xmldoc.Load(fs);\n XmlNodeList oldFiles = xmldoc.GetElementsByTagName(\"Files\");\n XmlNode rootNode = oldFiles[0].ParentNode;\n rootNode.RemoveChild(oldFiles[0]);\n\n XmlNodeList priorNode = xmldoc.GetElementsByTagName(\"References\");\n XmlElement filesNode = xmldoc.CreateElement(\"Files\");\n rootNode.InsertAfter(filesNode, priorNode[0]);\n\n DirectoryInfo di = new DirectoryInfo(rootPath);\n foreach (DirectoryInfo thisDir in di.GetDirectories())\n {\n AddAllFiles(xmldoc, filesNode, thisDir.FullName);\n }\n\n\n List<String> allDirectories = GetAllDirectories(rootPath);\n for (int i = 0; i < allDirectories.Count; ++i)\n {\n allDirectories[i] = allDirectories[i].Replace(rootPath, \"$(ProjectDir)\");\n }\n String includeDirectories = \"\\\"D:\\\\dev\\\\lib\\\\inc\\\\ipp\\\\\\\"\";\n foreach (String dir in allDirectories) \n {\n includeDirectories += \";\\\"\" + dir + \"\\\"\";\n }\n\n XmlNodeList toolNodes = xmldoc.GetElementsByTagName(\"Tool\");\n foreach (XmlNode node in toolNodes)\n {\n if (node.Attributes[\"Name\"].Value == \"VCCLCompilerTool\") {\n try\n {\n node.Attributes[\"AdditionalIncludeDirectories\"].Value = includeDirectories;\n }\n catch (System.Exception e)\n {\n XmlAttribute newAttr = xmldoc.CreateAttribute(\"AdditionalIncludeDirectories\");\n newAttr.Value = includeDirectories;\n node.Attributes.InsertBefore(newAttr, node.Attributes[\"PreprocessorDefinitions\"]);\n }\n\n }\n }\n String pathOut = \"D:/dev/src/co/UMC6/UMC.xml\";\n FileStream fsOut = new FileStream(pathOut, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);\n xmldoc.Save(fsOut);\n\n }\n static void AddAllFiles(XmlDocument doc, XmlElement parent, String path) {\n DirectoryInfo di = new DirectoryInfo(path);\n XmlElement thisElement = doc.CreateElement(\"Filter\");\n thisElement.SetAttribute(\"Name\", di.Name);\n foreach (FileInfo fi in di.GetFiles())\n {\n XmlElement thisFile = doc.CreateElement(\"File\");\n String relPath = fi.FullName.Replace(rootPath, \".\\\\\");\n thisFile.SetAttribute(\"RelativePath\", relPath);\n thisElement.AppendChild(thisFile);\n }\n foreach (DirectoryInfo thisDir in di.GetDirectories())\n {\n AddAllFiles(doc, thisElement, thisDir.FullName);\n }\n parent.AppendChild(thisElement);\n }\n static List<String> GetAllDirectories(String dir)\n {\n DirectoryInfo di = new DirectoryInfo(dir);\n Console.WriteLine(dir);\n\n List<String> files = new List<String>();\n foreach (DirectoryInfo subDir in di.GetDirectories())\n {\n List<String> newList = GetAllDirectories(subDir.FullName);\n files.Add(subDir.FullName);\n files.AddRange(newList);\n }\n return files;\n }\n static List<String> GetAllFiles(String dir)\n {\n DirectoryInfo di = new DirectoryInfo(dir);\n Console.WriteLine(dir);\n\n List<String> files = new List<String>();\n foreach (DirectoryInfo subDir in di.GetDirectories())\n {\n List<String> newList = GetAllFiles(subDir.FullName);\n files.AddRange(newList);\n }\n foreach (FileInfo fi in di.GetFiles())\n {\n files.Add(fi.FullName);\n }\n return files;\n }\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19816/" ]
111,643
<p>I'm currently convering my ASP.NET v2 application to serialize/deserialize it's objects because I want to shift from inproc session state to stateserver. This is because my host, webhost4life, has a nasty tendency to recycle the worker process frequently thus causing session timeouts. Anyway... the question...</p> <p>I'm trying to not serialize things I don't need to, i.e. variables that are re-initialised each page, don't need to be serialised. Here's one of them:</p> <p> Private RollbackQueue As New Queue(Of DataServer.Rollback)</p> <p>On deserialisation, will RollbackQueue be a) nothing or b) an empty queue? My guess is that when .NET deserialises, it creates the parent object as normal and then fills in the fields one by one. Therefore, the NEW bit will fire.</p> <p>But that is a guess.</p> <p>Thanks, Rob.</p>
[ { "answer_id": 111646, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 3, "selected": true, "text": "Initialize()" }, { "answer_id": 111691, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 0, "selected": false, "text": "[Serializable]\nclass TestClass\n{\n [NonSerialized]\n public Queue<string> queue = new Queue<string>();\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var obj = new TestClass();\n Console.WriteLine(\"Original is null? {0}\", obj.queue == null);\n var stream = new MemoryStream();\n var formatter = new BinaryFormatter();\n formatter.Serialize(stream, obj);\n stream.Position = 0L;\n var copy = (TestClass)formatter.Deserialize(stream);\n Console.WriteLine(\"Copy is null? {0}\", copy.queue == null);\n Console.ReadLine();\n }\n}\n Original is null? False \nCopy is null? True\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18128/" ]
111,676
<p>Does anyone have any advice for a consistent way to unit test a multithreaded application? I have done one application where our mock "worker threads" had a thread.sleep with a time that was specified by a public member variable. We would use this so we could set how long a particular thread would take to complete its work, then we could do our assertions. Any ideas of a better way to do this? Any good mock frameworks for .Net that can handle this?</p>
[ { "answer_id": 111778, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 4, "selected": false, "text": "bool WaitUntilTrue(Func<bool> func,\n int timeoutInMillis,\n int timeBetweenChecksMillis)\n{\n Stopwatch stopwatch = Stopwatch.StartNew();\n\n while(stopwatch.ElapsedMilliseconds < timeoutInMillis)\n {\n if (func())\n return true;\n Thread.Sleep(timeBetweenChecksMillis);\n } \n return false;\n}\n volatile bool backgroundThreadHasFinished = false;\n//run your multithreaded test and make sure the thread sets the above variable.\n\nAssert.IsTrue(WaitUntilTrue(x => backgroundThreadHasFinished, 1000, 10));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19840/" ]
111,687
<p>Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?</p> <p>If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:</p> <pre><code>class Foo def initialize @@log = Syslog.open("foo") end end </code></pre> <p>I don't immediately see the place where the <code>Syslog.close</code> call should be, but what do you recommend?</p>
[ { "answer_id": 111724, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": true, "text": "class Foo\n def do_something\n Syslog.open do\n # work with the syslog here\n end\n end\nend\n" }, { "answer_id": 111805, "author": "whoisjake", "author_id": 2609, "author_profile": "https://Stackoverflow.com/users/2609", "pm_score": 1, "selected": false, "text": "class Foo\n def initialize\n @@log = Syslog.open(\"foo\")\n end\n\n def Foo.finalize(id)\n @@log.close if @@log\n end\nend\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
111,700
<p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p> <p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p> <p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p> <p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p> <p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p> <pre><code>0 - BRK 1 - ORA (D,X) 2 - COP b </code></pre> <p>etc</p> <p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p> <p>Is anyone familiar with this CPU's memory model?</p> <p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p> <p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p> <p>I uploaded the source:</p> <p><a href="https://archive.codeplex.com/?p=cpu6502" rel="nofollow noreferrer">https://archive.codeplex.com/?p=cpu6502</a></p> <p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
[ { "answer_id": 111754, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "HEX LEN TIM\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
111,707
<p>I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work.</p> <p>Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure <strong>by design</strong> that no SQL deadlock will be encountered - ever.</p> <p>For example, in C# multithreaded programming, a simple design rule such as <em>the locks must be taken following their lexicographical order</em> ensures that no deadlock will <em>ever</em> happen.</p> <p>Are there any SQL coding patterns guaranteed to be deadlock-proof?</p>
[ { "answer_id": 112896, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 4, "selected": false, "text": "SET ISOLATION LEVEL" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18858/" ]
111,744
<ul> <li>The GoDiagram object model has a GoDocument. </li> <li>GoViews have a reference to a GoDocument.</li> <li>If the user does any modification on the diagramming surface, a GoDocument.Changed event is raised with the relevant information in the event arguments.</li> </ul> <p>I would like to be notified when some user-actions happen, so that I can confer with my Controller (disallow/cancel it if need be) and then issue view-update orders from there that actually modify the <strong>Northwoods GoDiagram</strong> third party component.<br> The Changed event is a notification that something just happened (past tense) - Doing all of the above in the event handler results in a .... (<em>wait for it</em>)... StackOverflowException. (GoDocument.Changed handler > Updates GoDocument > Firing new Changed events.. )</p> <p>So question, how do I get a BeforeEditing or BeforeResizing kind of notification model in GoDiagrams? Has anyone who's been there lived to tell a tale?</p>
[ { "answer_id": 130039, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 0, "selected": false, "text": "OnChanged(GoChangedEventArgs e)\n{\n if(NotAllowed)\n {\n e.Undo();\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
111,769
<p>I searched the net and handbook, but I only managed to learn what is the masked package, and not how to install it. I did find some commands, but they don't seem to work on 2008 (looking at it, it seems those are for earlier versions). I have something like this:</p> <pre><code>localhost ~ # emerge flamerobin Calculating dependencies !!! All ebuilds that could satisfy "dev-db/flamerobin" have been masked. !!! One of the following masked packages is required to complete your request: - dev-db/flamerobin-0.8.6 (masked by: ~x86 keyword) - dev-db/flamerobin-0.8.3 (masked by: ~x86 keyword) </code></pre> <p>I would like to install version 0.8.6, but don't know how? I found some instructions, but they tell me to edit or write to some files under /etc/portage. However, I don't have /etc/portage on my system:</p> <pre><code>localhost ~ # ls /etc/portage ls: cannot access /etc/portage: No such file or directory </code></pre>
[ { "answer_id": 455780, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 3, "selected": false, "text": "/etc/portage/package.keywords man portage package.keywords /etc/portage/package.unmask package.unmask" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
111,792
<p>For example:</p> <pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); </code></pre> <p>or:</p> <pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); </code></pre>
[ { "answer_id": 111803, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 3, "selected": true, "text": "Income income = new Income\n{\n Initials = something,\n CheckNumber = something,\n CheckDate = something,\n BranchNumber = something\n};\n return new Report.ReportData { ReportName = something, Formulas = something};\n" }, { "answer_id": 111836, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "root.Nodes.Add(new TNode() {\n Foo1 = bar1, \n Foo2 = bar2, \n Foo3 = bar3\n});\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
111,812
<p>What is the best practice for naming UI controls (textboxes, drop-downs, etc.) on forms and reports for reference in the code-behind pages?</p> <p>I develop a lot of reports and forms in my office. I have several web applications providing about 80+ "live" reports being generated from various and multiple data sources (Access, SQL, Oracle). These reports are considered "live" because they accept user set paramaters from a form, then query the database to produce a report based on the current information available.</p> <p>So, the process starts with obtaining the values set by the user, passing those to the database query, receiving the dataset, and finally assigning the dataset to the report. In some cases, additional fields displayed on the report need to be calculated from the dataset before the report can be generated. This requires referencing the output controls on the report to assign the calculated value.</p> <p>While I don't really care to use prefixes in my code for variables or member fields, I do use them to identify the UI controls. For example, txtFirstName to reference the report control to assign the data from the FirstName field in the dataset to the display control on the report. Is there a better practice for naming/referencing UI controls on forms and reports?</p>
[ { "answer_id": 112007, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "btn Button\ncbo ComboBox\nchk CheckBox\nclb CheckedListBox\ngrp GroupBox\niml ImageList\nlbl Label\nlnk Hyperlink\nmnu Menu\npbr ProgressBar\npic Picture\npnl Panel\nrtb RichTextBox\ntmr Timer\ntvw TreeView\ntxt TextBox\n" }, { "answer_id": 46744374, "author": "erkanyildiz", "author_id": 624808, "author_profile": "https://Stackoverflow.com/users/624808", "pm_score": 0, "selected": false, "text": "bt_ UIButton lb_ UILabel tx_ UITextField tv_ UITextView vw_ UIView im_ UIImageView sc_ UIScrollView tb_ UITableView cl_ UICollectionView st_ UIStackView pk_ UIPickerView pr_ UIProgressView ai_ UIActivityIndicatorView wb_ UIWebView / WKWebView mp_ MKMapView gr_ UIGestureRecognizer sw_ UISwitch sl_ UISlider sp_ UIStepper sg_ UISegmentedControl pg_ UIPageControl dp_ UIDatePicker" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19747/" ]
111,852
<p>What tools do you use to develop Oracle stored procedures, in a team :</p> <ul> <li>To automatically "lock" the current procedure you are working with, so nobody else in the team can make changes to it until you are finished.</li> <li>To automatically send the changes you make in the stored procedure, in an Oracle database, to a Subversion, CVS, ... repository</li> </ul> <p>Thanks!</p>
[ { "answer_id": 1001493, "author": "asalamon74", "author_id": 21348, "author_profile": "https://Stackoverflow.com/users/21348", "pm_score": 0, "selected": false, "text": "SELECT object_type, object_name, \n dbms_metadata.get_ddl(object_type, object_name) object_ddl FROM user_objects\nWHERE OBJECT_TYPE in ('INDEX', 'TRIGGER', 'TABLE', 'VIEW', 'PACKAGE', \n 'FUNCTION', 'PROCEDURE', 'SYNONYM', 'TYPE') \nORDER BY OBJECT_TYPE, OBJECT_NAME\n TTTT TABLE_TTTT.SQL" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20037/" ]
111,866
<p>In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?</p> <p>Thanks,</p> <p>Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;</p> <pre><code>iterator it = someList.begin(); while (it != someList.end()) { if (shouldRemove(it)) it = someList.erase(it); } </code></pre>
[ { "answer_id": 111895, "author": "Jens Ayton", "author_id": 6443, "author_profile": "https://Stackoverflow.com/users/6443", "pm_score": 4, "selected": false, "text": "for (NSInteger i = array.count - 1; i >= 0; --i) {\n for (id object in array) NSEnumerator" }, { "answer_id": 111905, "author": "Pokot0", "author_id": 20042, "author_profile": "https://Stackoverflow.com/users/20042", "pm_score": 3, "selected": false, "text": " NSMutableArray* myArray = ....;\n\n int i;\n for(i=0; i<[myArray count]; i++) {\n id element = [myArray objectAtIndex:i];\n if(element == ...) {\n [myArray removeObjectAtIndex:i];\n i--;\n }\n }\n" }, { "answer_id": 112101, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "[theArray filterUsingPredicate:aPredicate]\n" }, { "answer_id": 112519, "author": "Christopher Ashworth", "author_id": 20021, "author_profile": "https://Stackoverflow.com/users/20021", "pm_score": 10, "selected": true, "text": "NSMutableArray *discardedItems = [NSMutableArray array];\n\nfor (SomeObjectClass *item in originalArrayOfItems) {\n if ([item shouldBeDiscarded])\n [discardedItems addObject:item];\n}\n\n[originalArrayOfItems removeObjectsInArray:discardedItems];\n" }, { "answer_id": 113258, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "NSMutableArray *myArray;\nNSArray *myArrayCopy = [NSArray arrayWithArray:myArray];\n\nfor (NSObject *anObject in myArrayCopy) {\n if (shouldRemove(anObject)) {\n [myArray removeObject:anObject];\n }\n}\n" }, { "answer_id": 126088, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 5, "selected": false, "text": "removeObject: removeObjectsInArray: removeObjectAtIndex: NSMutableArray *array = ...\nNSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];\nfor (id object in array) {\n if (! shouldRemove(object)) {\n [itemsToKeep addObject:object];\n }\n}\n[array setArray:itemsToKeep];\n itemsToKeep setArray: array itemsToKeep [array release];\narray = [itemsToKeep retain];\n" }, { "answer_id": 129942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "NSPredicate *caseInsensitiveBNames = \n[NSPredicate predicateWithFormat:@\"SELF beginswith[c] 'b'\"];\n [namesArray filterUsingPredicate:caseInsensitiveBNames];\n" }, { "answer_id": 1019929, "author": "Corey Floyd", "author_id": 48311, "author_profile": "https://Stackoverflow.com/users/48311", "pm_score": 6, "selected": false, "text": "NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];\nSomeObjectClass *item;\nNSUInteger index = 0;\n\nfor (item in originalArrayOfItems) {\n if ([item shouldBeDiscarded])\n [discardedItems addIndex:index];\n index++;\n}\n\n[originalArrayOfItems removeObjectsAtIndexes:discardedItems];\n" }, { "answer_id": 8972160, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 1, "selected": false, "text": "@implementation NSMutableArray (Filtering)\n\n- (void)filterUsingTest:(BOOL (^)(id obj, NSUInteger idx))predicate {\n NSMutableIndexSet *indexesFailingTest = [[NSMutableIndexSet alloc] init];\n\n NSUInteger index = 0;\n for (id object in self) {\n if (!predicate(object, index)) {\n [indexesFailingTest addIndex:index];\n }\n ++index;\n }\n [self removeObjectsAtIndexes:indexesFailingTest];\n\n [indexesFailingTest release];\n}\n\n@end\n [myMutableArray filterUsingTest:^BOOL(id obj, NSUInteger idx) {\n return [self doIWantToKeepThisObject:obj atIndex:idx];\n}];\n" }, { "answer_id": 12020354, "author": "zavié", "author_id": 284811, "author_profile": "https://Stackoverflow.com/users/284811", "pm_score": 4, "selected": false, "text": "passingTest NSMutableArray – indexesOfObjectsPassingTest: NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:\n ^BOOL(id obj, NSUInteger idx, BOOL *stop) {\n return [self shouldRemove:obj];\n}];\n[someList removeObjectsAtIndexes:indexesToBeRemoved];\n" }, { "answer_id": 16905821, "author": "user1032657", "author_id": 1032657, "author_profile": "https://Stackoverflow.com/users/1032657", "pm_score": 4, "selected": false, "text": "removeObjectAtIndex: removeObjectsAtIndexes: removeObjects:" }, { "answer_id": 18456913, "author": "Hot Licks", "author_id": 581994, "author_profile": "https://Stackoverflow.com/users/581994", "pm_score": 6, "selected": false, "text": "for (NSInteger i = array.count - 1; i >= 0; i--) {\n ElementType* element = array[i];\n if ([element shouldBeRemoved]) {\n [array removeObjectAtIndex:i];\n }\n}\n" }, { "answer_id": 18478113, "author": "Matjan", "author_id": 1137246, "author_profile": "https://Stackoverflow.com/users/1137246", "pm_score": 3, "selected": false, "text": "for (LineItem *item in [NSArray arrayWithArray:self.lineItems]) \n{\n if ([item.toBeRemoved boolValue] == YES) \n {\n [self.lineItems removeObject:item];\n }\n}\n" }, { "answer_id": 18478301, "author": "vikingosegundo", "author_id": 106435, "author_profile": "https://Stackoverflow.com/users/106435", "pm_score": 4, "selected": false, "text": "NSMutableArray *array = [@[@{@\"name\": @\"a\", @\"shouldDelete\": @(YES)},\n @{@\"name\": @\"b\", @\"shouldDelete\": @(NO)},\n @{@\"name\": @\"c\", @\"shouldDelete\": @(YES)},\n @{@\"name\": @\"d\", @\"shouldDelete\": @(NO)}] mutableCopy];\n\n[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if([obj[@\"shouldDelete\"] boolValue])\n [array removeObjectAtIndex:idx];\n}];\n (\n {\n name = b;\n shouldDelete = 0;\n },\n {\n name = d;\n shouldDelete = 0;\n }\n)\n [array filterUsingPredicate:[NSPredicate predicateWithFormat:@\"shouldDelete == NO\"]];\n" }, { "answer_id": 31913311, "author": "aremvee", "author_id": 1542458, "author_profile": "https://Stackoverflow.com/users/1542458", "pm_score": 0, "selected": false, "text": "NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];\n\n for (id object in array)\n {\n if ( [object isNotEqualTo:@\"whatever\"]) {\n [itemsToKeep addObject:object ];\n }\n }\n array = nil;\n array = [[NSMutableArray alloc]initWithArray:itemsToKeep];\n" }, { "answer_id": 32246289, "author": "Werner Altewischer", "author_id": 480467, "author_profile": "https://Stackoverflow.com/users/480467", "pm_score": 1, "selected": false, "text": "@implementation NSMutableArray(BMCommons)\n\n- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {\n if (predicate != nil) {\n NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];\n for (id obj in self) {\n BOOL shouldRemove = predicate(obj);\n if (!shouldRemove) {\n [newArray addObject:obj];\n }\n }\n [self setArray:newArray];\n }\n}\n\n@end\n NSMutableArray *dates = ...;\n[dates removeObjectsWithPredicate:^BOOL(id obj) {\n NSDate *date = (NSDate *)obj;\n return [date timeIntervalSinceNow] < 0;\n}];\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
111,868
<p>The one-liner should:</p> <ul> <li>solve a real-world problem</li> <li>not be extensively cryptic (should be easy to understand and reproduce)</li> <li>be worth the time it takes to write it (should not be too clever)</li> </ul> <p>I'm looking for practical tips and tricks (complementary examples for <code>perldoc perlrun</code>).</p>
[ { "answer_id": 111869, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }'\n my @avi = glob('*.avi');\nmy @srt = glob('*.srt');\n\nfor my $i (0..$#avi)\n{\n my $video_filename = $avi[$i];\n $video_filename =~ s/avi$/srt/; # 'movie1.avi' -> 'movie1.srt'\n\n my $subtitle_filename = $srt[$i]; # 'film1.srt'\n rename($subtitle_filename, $video_filename); # 'film1.srt' -> 'movie1.srt'\n}\n" }, { "answer_id": 112339, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": -1, "selected": false, "text": "srt=(*.srt); for foo in *.avi; mv $srt[1] ${foo:r}.srt && srt=($srt[2,-1])\n" }, { "answer_id": 112624, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 4, "selected": false, "text": "perl -pe's/([\\d.]+)/localtime $1/e;' access.log\n tail -f tail -f access.log | perl -ne's/([\\d.]+)/localtime $1/e,print if /stackoverflow\\.com/'\n" }, { "answer_id": 113660, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "tail -F /var/log/squid/access.log | \\\nperl -ane 'BEGIN{$|++} $F[6] =~ m{\\Qrad.live.com/ADSAdClient31.dll}\n && printf \"%02d:%02d:%02d %15s %9d\\n\",\n sub{reverse @_[0..2]}->(localtime $F[0]), @F[2,4]'\n" }, { "answer_id": 113716, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 4, "selected": false, "text": "vim $(ack --perl -l 'api/v1/episode' t)\n ack $(ls t/lib/TestPM/|awk -F'.' '{print $1}'|xargs perl -e 'print join \"|\" => @ARGV') aggtests/ t -l\n" }, { "answer_id": 114520, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "function vimify-eval; {\n if [[ ! -z \"$BUFFER\" ]]; then\n if [[ $BUFFER = 'ack'* ]]; then\n BUFFER=\"$BUFFER -l\"\n fi\n BUFFER=\"vim \\$($BUFFER)\"\n zle accept-line\n fi\n}\n\nzle -N vim-eval-widget vimify-eval\n\nbindkey '^P' vim-eval-widget\n ack some-pattern" }, { "answer_id": 114885, "author": "Kwondri", "author_id": 7691, "author_profile": "https://Stackoverflow.com/users/7691", "pm_score": 0, "selected": false, "text": " open STATFILE, \"zcat $logFile|\" or die \"Can't open zcat of $logFile\" ;\n" }, { "answer_id": 117972, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 2, "selected": false, "text": "perl -l -e 'print scalar(localtime($ARGV[0]))'\n alias e2d=\"perl -le \\\"print scalar(localtime($ARGV[0]));\\\"\"\n echo 1219174516 | e2d\n" }, { "answer_id": 120722, "author": "mtk", "author_id": 9437, "author_profile": "https://Stackoverflow.com/users/9437", "pm_score": 2, "selected": false, "text": "perl -00 -ne 'print sort split /^/'\n" }, { "answer_id": 123375, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "perl -pe'1while+s/\\t/\" \"x(8-pos()%8)/e'" }, { "answer_id": 159471, "author": "dr_pepper", "author_id": 18415, "author_profile": "https://Stackoverflow.com/users/18415", "pm_score": 2, "selected": false, "text": "set path=(`echo $path | perl -e 'foreach(split(/ /,<>)){print $_,\" \" unless $s{$_}++;}'`)\n" }, { "answer_id": 160060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "perl -ple '$_=eval'\n" }, { "answer_id": 164978, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "$PATH $ export PATH=$(perl -F: -ane'print join q/:/, grep { !$c{$_}++ } @F'<<<$PATH)\n %PATH% ../ File::Spec->rel2abs Cwd::realpath #!/usr/bin/perl -w\nuse File::Spec; \n\n$, = \"\\n\"; \nprint grep { !$count{$_}++ } \n map { File::Spec->rel2abs($_) } \n File::Spec->path;\n" }, { "answer_id": 165694, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 4, "selected": false, "text": "find ... -exec rm {} \\; rm rm find . -name '*.whatever' | perl -lne unlink\n perl find unlink() $_ $_ -n find -print -exec rm {} \\; find -print0 perl" }, { "answer_id": 508306, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": true, "text": "perl -pe's/([\\d.]+)/localtime $1/e;' access.log ack $(ls t/lib/TestPM/|awk -F'.' '{print $1}'|xargs perl -e 'print join \"|\" => @ARGV') \naggtests/ t -l perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }' find . -name '*.whatever' | perl -lne unlink tail -F /var/log/squid/access.log | perl -ane 'BEGIN{$|++} $F[6] =~ m{\\Qrad.live.com/ADSAdClient31.dll}\n&& printf \"%02d:%02d:%02d %15s %9d\\n\", sub{reverse @_[0..2]}->(localtime $F[0]), @F[2,4]' export PATH=$(perl -F: -ane'print join q/:/, grep { !$c{$_}++ } @F'<<<$PATH) alias e2d=\"perl -le \\\"print scalar(localtime($ARGV[0]));\\\"\" perl -ple '$_=eval' perl -00 -ne 'print sort split /^/' perl -pe'1while+s/\\t/\" \"x(8-pos()%8)/e' tail -f log | perl -ne '$s=time() unless $s; $n=time(); $d=$n-$s; if ($d>=2) { print qq\n($. lines in last $d secs, rate ),$./$d,qq(\\n); $. =0; $s=$n; }' perl -MFile::Spec -e 'print join(qq(\\n),File::Spec->path).qq(\\n)'" }, { "answer_id": 508432, "author": "JDrago", "author_id": 29060, "author_profile": "https://Stackoverflow.com/users/29060", "pm_score": 2, "selected": false, "text": "perl -p -i -e 's/\\r\\n$/\\n/' htdocs/*.asp\n" }, { "answer_id": 510974, "author": "melo", "author_id": 24579, "author_profile": "https://Stackoverflow.com/users/24579", "pm_score": 2, "selected": false, "text": "perl -ne '$s=time() unless $s; $n=time(); $d=$n-$s; if ($d>=2) { print \"$. lines in last $d secs, rate \",$./$d,\"\\n\"; $. =0; $s=$n; }'\n" }, { "answer_id": 1440678, "author": "Peter Mortensen", "author_id": 63550, "author_profile": "https://Stackoverflow.com/users/63550", "pm_score": 2, "selected": false, "text": "perl -nle \"print ' Stack Overflow ' . $1 . ' (no change)' if /\\s{20,99}([0-9,]{3,6})<\\/div>/;\" \"SO.html\" >> SOscores.txt\n" }, { "answer_id": 1440698, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "du perl -e '%h=map{/.\\s/;7x(ord$&&10)+$`,$_}`du -h`;print@h{sort%h}'\n" }, { "answer_id": 1441948, "author": "singingfish", "author_id": 36499, "author_profile": "https://Stackoverflow.com/users/36499", "pm_score": 1, "selected": false, "text": "text description {tag_label}\n {tag_label} perl -ne '($c) = $_ =~ /({.*?})/; print $c,\"\\n\" ' $1 | sort | uniq -c | sort -d\n" }, { "answer_id": 4818495, "author": "Tim Lewis", "author_id": 67865, "author_profile": "https://Stackoverflow.com/users/67865", "pm_score": 2, "selected": false, "text": "perl -e 'print join(\"\\n\",split(\":\",$ENV{\"PATH\"})).\"\\n\"'\n perl -e \"print join(qq(\\n),split(';',$ENV{'PATH'})).qq(\\n)\"\n perl -MFile::Spec -e 'print join(qq(\\n), File::Spec->path).qq(\\n)' # Unix\nperl -MFile::Spec -e \"print join(qq(\\n), File::Spec->path).qq(\\n)\" # Windows\n" }, { "answer_id": 6007412, "author": "Benny", "author_id": 355344, "author_profile": "https://Stackoverflow.com/users/355344", "pm_score": 2, "selected": false, "text": "permit host 10.1.1.0 permit 10.1.1.0 255.255.255.0 perl -ne \"print if /host ([\\w\\-\\.]+){3}\\.0 /\" *.conf\n" }, { "answer_id": 6476684, "author": "Benny", "author_id": 355344, "author_profile": "https://Stackoverflow.com/users/355344", "pm_score": 1, "selected": false, "text": "Interface, Connect to, Vlan\nGi1/0/1, Desktop, 1286\nGi1/0/2, IP Phone, 1317\n interface Gi1/0/1\n description Desktop\n switchport access vlan 1286\n perl -F, -lane \"if ($.==1) {@keys = @F} else{print @keys[$_].$F[$_] foreach(0..$#F)} \" \n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
111,927
<p>I use a <code>System.Timers.Timer</code> in my Asp.Net application and I need to use the <code>HttpServerUtility.MapPath</code> method which seems to be only available via <code>HttpContext.Current.Server.MapPath</code>. The problem is that <code>HttpContext.Current</code> is <code>null</code> when the <code>Timer.Elapsed</code> event fires.</p> <p>Is there another way to get a reference to a HttpServerUtility object ? I could inject it in my class' constructor. Is it safe ? How can I be sure it won't be Garbage Collected at the end of the current request?</p> <p>Thanks!</p>
[ { "answer_id": 112220, "author": "Costo", "author_id": 1130, "author_profile": "https://Stackoverflow.com/users/1130", "pm_score": 8, "selected": true, "text": "HostingEnvironment.MapPath() HttpContext.Current.Server.MapPath() HttpServerUtility MapPath AppDomain.CurrentDomain.BaseDirectory Global Application_Start" }, { "answer_id": 485836, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public static string MapPath(string path)\n{\n if (HttpContext.Current != null)\n return HttpContext.Current.Server.MapPath(path);\n\n return HttpRuntime.AppDomainAppPath + path.Replace(\"~\", string.Empty).Replace('/', '\\\\');\n}\n" }, { "answer_id": 11403754, "author": "Mike", "author_id": 85196, "author_profile": "https://Stackoverflow.com/users/85196", "pm_score": 4, "selected": false, "text": "public class ServerPathMapper : IPathMapper { \n public string MapPath(string relativePath) { \n return HostingEnvironment.MapPath(relativePath); \n } \n} \n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130/" ]
111,928
<p>I can print with <code>printf</code> as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?</p> <p>I am running gcc.</p> <pre><code>printf(&quot;%d %x %o\n&quot;, 10, 10, 10); //prints &quot;10 A 12\n&quot; print(&quot;%b\n&quot;, 10); // prints &quot;%b\n&quot; </code></pre>
[ { "answer_id": 112956, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 7, "selected": false, "text": "#include <stdio.h> /* printf */\n#include <string.h> /* strcat */\n#include <stdlib.h> /* strtol */\n\nconst char *byte_to_binary\n(\n int x\n)\n{\n static char b[9];\n b[0] = '\\0';\n\n int z;\n for (z = 128; z > 0; z >>= 1)\n {\n strcat(b, ((x & z) == z) ? \"1\" : \"0\");\n }\n\n return b;\n}\n\nint main\n(\n void\n)\n{\n {\n /* binary string to int */\n\n char *tmp;\n char *b = \"0101\";\n\n printf(\"%d\\n\", strtol(b, &tmp, 2));\n }\n\n {\n /* byte to binary string */\n\n printf(\"%s\\n\", byte_to_binary(5));\n }\n \n return 0;\n}\n" }, { "answer_id": 657202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "const char* byte_to_binary(int x)\n{\n static char b[sizeof(int)*8+1] = {0};\n int y;\n long long z;\n\n for (z = 1LL<<sizeof(int)*8-1, y = 0; z > 0; z >>= 1, y++) {\n b[y] = (((x & z) == z) ? '1' : '0');\n }\n b[y] = 0;\n\n return b;\n}\n" }, { "answer_id": 1078422, "author": "mrwes", "author_id": 82848, "author_profile": "https://Stackoverflow.com/users/82848", "pm_score": 3, "selected": false, "text": "pBin pBinFill pBinFill pBinFill #define kDisplayWidth 64\n\nchar* pBin(long int x,char *so)\n{\n char s[kDisplayWidth+1];\n int i = kDisplayWidth;\n s[i--] = 0x00; // terminate string\n do { // fill in array from right to left\n s[i--] = (x & 1) ? '1' : '0'; // determine bit\n x >>= 1; // shift right 1 bit\n } while (x > 0);\n i++; // point to last valid character\n sprintf(so, \"%s\", s+i); // stick it in the temp string string\n return so;\n}\n\nchar* pBinFill(long int x, char *so, char fillChar)\n{\n // fill in array from right to left\n char s[kDisplayWidth+1];\n int i = kDisplayWidth;\n s[i--] = 0x00; // terminate string\n do { // fill in array from right to left\n s[i--] = (x & 1) ? '1' : '0';\n x >>= 1; // shift right 1 bit\n } while (x > 0);\n while (i >= 0) s[i--] = fillChar; // fill with fillChar \n sprintf(so, \"%s\", s);\n return so;\n}\n\nvoid test()\n{\n char so[kDisplayWidth+1]; // working buffer for pBin\n long int val = 1;\n do {\n printf(\"%ld =\\t\\t%#lx =\\t\\t0b%s\\n\", val, val, pBinFill(val, so, '0'));\n val *= 11; // generate test data\n } while (val < 100000000);\n}\n 00000001 = 0x000001 = 0b00000000000000000000000000000001\n00000011 = 0x00000b = 0b00000000000000000000000000001011\n00000121 = 0x000079 = 0b00000000000000000000000001111001\n00001331 = 0x000533 = 0b00000000000000000000010100110011\n00014641 = 0x003931 = 0b00000000000000000011100100110001\n00161051 = 0x02751b = 0b00000000000000100111010100011011\n01771561 = 0x1b0829 = 0b00000000000110110000100000101001\n19487171 = 0x12959c3 = 0b00000001001010010101100111000011\n" }, { "answer_id": 3208376, "author": "William Whyte", "author_id": 289138, "author_profile": "https://Stackoverflow.com/users/289138", "pm_score": 8, "selected": false, "text": "#define BYTE_TO_BINARY_PATTERN \"%c%c%c%c%c%c%c%c\"\n#define BYTE_TO_BINARY(byte) \\\n (byte & 0x80 ? '1' : '0'), \\\n (byte & 0x40 ? '1' : '0'), \\\n (byte & 0x20 ? '1' : '0'), \\\n (byte & 0x10 ? '1' : '0'), \\\n (byte & 0x08 ? '1' : '0'), \\\n (byte & 0x04 ? '1' : '0'), \\\n (byte & 0x02 ? '1' : '0'), \\\n (byte & 0x01 ? '1' : '0') \n printf(\"Leading text \"BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));\n printf(\"m: \"BYTE_TO_BINARY_PATTERN\" \"BYTE_TO_BINARY_PATTERN\"\\n\",\n BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));\n BYTE_TO_BINARY" }, { "answer_id": 3829834, "author": "olli", "author_id": 462729, "author_profile": "https://Stackoverflow.com/users/462729", "pm_score": 2, "selected": false, "text": "void print_ulong_bin(const unsigned long * const var, int bits) {\n int i;\n\n #if defined(__LP64__) || defined(_LP64)\n if( (bits > 64) || (bits <= 0) )\n #else\n if( (bits > 32) || (bits <= 0) )\n #endif\n return;\n\n for(i = 0; i < bits; i++) { \n printf(\"%lu\", (*var >> (bits - 1 - i)) & 0x01);\n }\n}\n" }, { "answer_id": 3974138, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "// Assumes little endian\nvoid printBits(size_t const size, void const * const ptr)\n{\n unsigned char *b = (unsigned char*) ptr;\n unsigned char byte;\n int i, j;\n \n for (i = size-1; i >= 0; i--) {\n for (j = 7; j >= 0; j--) {\n byte = (b[i] >> j) & 1;\n printf(\"%u\", byte);\n }\n }\n puts(\"\");\n}\n int main(int argv, char* argc[])\n{\n int i = 23;\n uint ui = UINT_MAX;\n float f = 23.45f;\n printBits(sizeof(i), &i);\n printBits(sizeof(ui), &ui);\n printBits(sizeof(f), &f);\n return 0;\n}\n" }, { "answer_id": 3989932, "author": "Adam", "author_id": 483309, "author_profile": "https://Stackoverflow.com/users/483309", "pm_score": 0, "selected": false, "text": "void PrintBinary( int Value, int Places, char* TargetString)\n{\n int Mask;\n\n Mask = 1 << Places;\n\n while( Places--) {\n Mask >>= 1; /* Preshift, because we did one too many above */\n *TargetString++ = (Value & Mask)?'1':'0';\n }\n *TargetString = 0; /* Null terminator for C string */\n}\n char BinaryString[17];\n...\nPrintBinary( Value, 16, BinaryString);\nprintf( \"yadda yadda %s yadda...\\n\", BinaryString);\n" }, { "answer_id": 4007806, "author": "rakesh jha", "author_id": 485523, "author_profile": "https://Stackoverflow.com/users/485523", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <conio.h>\n\nvoid main()\n{\n clrscr();\n printf(\"Welcome\\n\\n\\n\");\n unsigned char x='A';\n char ch_array[8];\n for(int i=0; x!=0; i++)\n {\n ch_array[i] = x & 1;\n x = x >>1;\n }\n for(--i; i>=0; i--)\n printf(\"%d\", ch_array[i]);\n\n getch();\n}\n" }, { "answer_id": 4839583, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 4, "selected": false, "text": "#define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)\n\nchar *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])\n{\n char *s = buf + FMT_BUF_SIZE;\n *--s = 0;\n if (!x) *--s = '0';\n for (; x; x /= 2) *--s = '0' + x%2;\n return s;\n}\n char tmp[FMT_BUF_SIZE];\nprintf(\"%s\\n\", binary_fmt(x, tmp));\n x" }, { "answer_id": 6546683, "author": "Ben Cordero", "author_id": 824683, "author_profile": "https://Stackoverflow.com/users/824683", "pm_score": 2, "selected": false, "text": "/* Convert an int to it's binary representation */\n\nchar *int2bin(int num, int pad)\n{\n char *str = malloc(sizeof(char) * (pad+1));\n if (str) {\n str[pad]='\\0';\n while (--pad>=0) {\n str[pad] = num & 1 ? '1' : '0';\n num >>= 1;\n }\n } else {\n return \"\";\n }\n return str;\n}\n\n/* example usage */\n\nprintf(\"The number 5 in binary is %s\", int2bin(5, 4));\n/* \"The number 5 in binary is 0101\" */\n" }, { "answer_id": 6724041, "author": "paniq", "author_id": 81145, "author_profile": "https://Stackoverflow.com/users/81145", "pm_score": 3, "selected": false, "text": "inline std::string format_binary(unsigned int x)\n{\n static char b[33];\n b[32] = '\\0';\n\n for (int z = 0; z < 32; z++) {\n b[31-z] = ((x>>z) & 0x1) ? '1' : '0';\n }\n\n return b;\n}\n" }, { "answer_id": 6770517, "author": "luser droog", "author_id": 733077, "author_profile": "https://Stackoverflow.com/users/733077", "pm_score": 0, "selected": false, "text": "int conv_rad (int num, int rad, char *s, int n) {\n char *vec = \"0123456789\" \"ABCDEFGHIJKLM\" \"NOPQRSTUVWXYZ\";\n int off;\n if (n == 0) return 0;\n if (num < rad) { *s = vec[num]; return 1; }\n off = conv_rad(num/rad, rad, s, n);\n if ((off == n) || (off == -1)) return -1;\n s[off] = vec[num%rad];\n return off+1;\n}\n conv_rad putchar()" }, { "answer_id": 7137520, "author": "eMPee584", "author_id": 200509, "author_profile": "https://Stackoverflow.com/users/200509", "pm_score": 2, "selected": false, "text": "char *\nformat_binary(unsigned int x)\n{\n #define MAXLEN 8 // width of output format\n #define MAXCNT 4 // count per printf statement\n static char fmtbuf[(MAXLEN+1)*MAXCNT];\n static int count = 0;\n char *b;\n count = count % MAXCNT + 1;\n b = &fmtbuf[(MAXLEN+1)*count];\n b[MAXLEN] = '\\0';\n for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }\n return b;\n}\n" }, { "answer_id": 8869174, "author": "Yola", "author_id": 312896, "author_profile": "https://Stackoverflow.com/users/312896", "pm_score": 2, "selected": false, "text": "#include <limits>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\ntemplate<class T> string binary_text(T dec, string byte_separator = \" \") {\n char* pch = (char*)&dec;\n string res;\n for (int i = 0; i < sizeof(T); i++) {\n for (int j = 1; j < 8; j++) {\n res.append(pch[i] & 1 ? \"1\" : \"0\");\n pch[i] /= 2;\n }\n res.append(byte_separator);\n }\n return res;\n}\n\nint main() {\n cout << binary_text(5) << endl;\n cout << binary_text(.1) << endl;\n\n return 0;\n}\n" }, { "answer_id": 9287543, "author": "TechplexEngineer", "author_id": 429544, "author_profile": "https://Stackoverflow.com/users/429544", "pm_score": 4, "selected": false, "text": "%B printf /*\n * File: main.c\n * Author: Techplex.Engineer\n *\n * Created on February 14, 2012, 9:16 PM\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <printf.h>\n#include <math.h>\n#include <string.h>\n\nstatic int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)\n{\n /* \"%M\" always takes one argument, a pointer to uint8_t[6]. */\n if (n > 0) {\n argtypes[0] = PA_POINTER;\n }\n return 1;\n}\n\nstatic int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)\n{\n int value = 0;\n int len;\n\n value = *(int **) (args[0]);\n\n // Beginning of my code ------------------------------------------------------------\n char buffer [50] = \"\"; // Is this bad?\n char buffer2 [50] = \"\"; // Is this bad?\n int bits = info->width;\n if (bits <= 0)\n bits = 8; // Default to 8 bits\n\n int mask = pow(2, bits - 1);\n while (mask > 0) {\n sprintf(buffer, \"%s\", ((value & mask) > 0 ? \"1\" : \"0\"));\n strcat(buffer2, buffer);\n mask >>= 1;\n }\n strcat(buffer2, \"\\n\");\n // End of my code --------------------------------------------------------------\n len = fprintf(stream, \"%s\", buffer2);\n return len;\n}\n\nint main(int argc, char** argv)\n{\n register_printf_specifier('B', printf_output_M, printf_arginfo_M);\n\n printf(\"%4B\\n\", 65);\n\n return EXIT_SUCCESS;\n}\n" }, { "answer_id": 12974661, "author": "kapilddit", "author_id": 555911, "author_profile": "https://Stackoverflow.com/users/555911", "pm_score": 3, "selected": false, "text": "char buffer [33];\nitoa(value, buffer, 2);\nprintf(\"\\nbinary: %s\\n\", buffer);\n" }, { "answer_id": 15909072, "author": "Leo", "author_id": 518018, "author_profile": "https://Stackoverflow.com/users/518018", "pm_score": 2, "selected": false, "text": "template<class T>\ninline std::string format_binary(T x)\n{\n char b[sizeof(T)*8+1] = {0};\n\n for (size_t z = 0; z < sizeof(T)*8; z++)\n b[sizeof(T)*8-1-z] = ((x>>z) & 0x1) ? '1' : '0';\n\n return std::string(b);\n}\n unsigned int value32 = 0x1e127ad;\nprintf( \" 0x%x: %s\\n\", value32, format_binary(value32).c_str() );\n\nunsigned long long value64 = 0x2e0b04ce0;\nprintf( \"0x%llx: %s\\n\", value64, format_binary(value64).c_str() );\n 0x1e127ad: 00000001111000010010011110101101\n0x2e0b04ce0: 0000000000000000000000000000001011100000101100000100110011100000\n" }, { "answer_id": 17380787, "author": "Moses", "author_id": 983798, "author_profile": "https://Stackoverflow.com/users/983798", "pm_score": 0, "selected": false, "text": "tmp1 = 1;\nwhile(inint/tmp1 > 1) {\n tmp1 <<= 1;\n}\ndo {\n printf(\"%d\", tmp2=inint/tmp1);\n inint -= tmp1*tmp2;\n} while((tmp1 >>= 1) > 0);\nprintf(\" \");\n" }, { "answer_id": 19470143, "author": "hiteshradia", "author_id": 1980274, "author_profile": "https://Stackoverflow.com/users/1980274", "pm_score": 0, "selected": false, "text": "int print_char_to_binary(char ch)\n{\n int i;\n for (i=7; i>=0; i--)\n printf(\"%hd \", ((ch & (1<<i))>>i));\n printf(\"\\n\");\n return 0;\n}\n" }, { "answer_id": 19885112, "author": "Shahbaz", "author_id": 912144, "author_profile": "https://Stackoverflow.com/users/912144", "pm_score": 6, "selected": false, "text": "const char *bit_rep[16] = {\n [ 0] = \"0000\", [ 1] = \"0001\", [ 2] = \"0010\", [ 3] = \"0011\",\n [ 4] = \"0100\", [ 5] = \"0101\", [ 6] = \"0110\", [ 7] = \"0111\",\n [ 8] = \"1000\", [ 9] = \"1001\", [10] = \"1010\", [11] = \"1011\",\n [12] = \"1100\", [13] = \"1101\", [14] = \"1110\", [15] = \"1111\",\n};\n\nvoid print_byte(uint8_t byte)\n{\n printf(\"%s%s\", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);\n}\n" }, { "answer_id": 19940043, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "6 6 110 \"110\" char buf[] printf() \"%08lu\" \"%*lX\" #include <stdint.h>\n#include <stdio.h>\n#include <inttypes.h>\n\nunsigned long char_to_bin10(char ch) {\n unsigned char uch = ch;\n unsigned long sum = 0;\n unsigned long power = 1;\n while (uch) {\n if (uch & 1) {\n sum += power;\n }\n power *= 10;\n uch /= 2;\n }\n return sum;\n}\n\nuint64_t uint16_to_bin16(uint16_t u) {\n uint64_t sum = 0;\n uint64_t power = 1;\n while (u) {\n if (u & 1) {\n sum += power;\n }\n power *= 16;\n u /= 2;\n }\n return sum;\n}\n\nvoid test(void) {\n printf(\"%lu\\n\", char_to_bin10(0xF1));\n // 11110001\n printf(\"%\" PRIX64 \"\\n\", uint16_to_bin16(0xF731));\n // 1111011100110001\n}\n" }, { "answer_id": 22511317, "author": "Marko", "author_id": 1873877, "author_profile": "https://Stackoverflow.com/users/1873877", "pm_score": 2, "selected": false, "text": "void print_binary(unsigned char c)\n{\n unsigned char i1 = (1 << (sizeof(c)*8-1));\n for(; i1; i1 >>= 1)\n printf(\"%d\",(c&i1)!=0);\n}\n\nvoid get_binary(unsigned char c, unsigned char bin[])\n{\n unsigned char i1 = (1 << (sizeof(c)*8-1)), i2=0;\n for(; i1; i1>>=1, i2++)\n bin[i2] = ((c&i1)!=0);\n}\n" }, { "answer_id": 25108449, "author": "ideasman42", "author_id": 432509, "author_profile": "https://Stackoverflow.com/users/432509", "pm_score": 5, "selected": false, "text": "int8 16 32 64 INT8 /* --- PRINTF_BYTE_TO_BINARY macro's --- */\n#define PRINTF_BINARY_PATTERN_INT8 \"%c%c%c%c%c%c%c%c\"\n#define PRINTF_BYTE_TO_BINARY_INT8(i) \\\n (((i) & 0x80ll) ? '1' : '0'), \\\n (((i) & 0x40ll) ? '1' : '0'), \\\n (((i) & 0x20ll) ? '1' : '0'), \\\n (((i) & 0x10ll) ? '1' : '0'), \\\n (((i) & 0x08ll) ? '1' : '0'), \\\n (((i) & 0x04ll) ? '1' : '0'), \\\n (((i) & 0x02ll) ? '1' : '0'), \\\n (((i) & 0x01ll) ? '1' : '0')\n\n#define PRINTF_BINARY_PATTERN_INT16 \\\n PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_PATTERN_INT8\n#define PRINTF_BYTE_TO_BINARY_INT16(i) \\\n PRINTF_BYTE_TO_BINARY_INT8((i) >> 8), PRINTF_BYTE_TO_BINARY_INT8(i)\n#define PRINTF_BINARY_PATTERN_INT32 \\\n PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_PATTERN_INT16\n#define PRINTF_BYTE_TO_BINARY_INT32(i) \\\n PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)\n#define PRINTF_BINARY_PATTERN_INT64 \\\n PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_PATTERN_INT32\n#define PRINTF_BYTE_TO_BINARY_INT64(i) \\\n PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)\n/* --- end macros --- */\n\n#include <stdio.h>\nint main() {\n long long int flag = 1648646756487983144ll;\n printf(\"My Flag \"\n PRINTF_BINARY_PATTERN_INT64 \"\\n\",\n PRINTF_BYTE_TO_BINARY_INT64(flag));\n return 0;\n}\n My Flag 0001011011100001001010110111110101111000100100001111000000101000\n My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000\n" }, { "answer_id": 25502488, "author": "andre.barata", "author_id": 2536704, "author_profile": "https://Stackoverflow.com/users/2536704", "pm_score": 2, "selected": false, "text": "void printb(unsigned int v) {\n unsigned int i, s = 1<<((sizeof(v)<<3)-1); // s = only most significant bit at 1\n for (i = s; i; i>>=1) printf(\"%d\", v & i || 0 );\n}\n" }, { "answer_id": 26154541, "author": "SeattleOrBayArea", "author_id": 927370, "author_profile": "https://Stackoverflow.com/users/927370", "pm_score": 2, "selected": false, "text": "void\nprintStringAsBinary(char * input)\n{\n char * temp = input;\n int i = 7, j =0;;\n int inputLen = strlen(input);\n\n /* Go over the string, check first bit..bit by bit and print 1 or 0\n **/\n\n for (j = 0; j < inputLen; j++) {\n printf(\"\\n\");\n while (i>=0) {\n if (*temp & (1 << i)) {\n printf(\"1\");\n } else {\n printf(\"0\");\n }\n i--;\n }\n temp = temp+1;\n i = 7;\n printf(\"\\n\");\n }\n}\n" }, { "answer_id": 26970214, "author": "GutiMac", "author_id": 4211031, "author_profile": "https://Stackoverflow.com/users/4211031", "pm_score": 0, "selected": false, "text": "void binario(int num) {\n for(int i=0;i<32;i++){\n (num&(1<i))? printf(\"1\"):\n printf(\"0\");\n } \n printf(\"\\n\");\n}\n" }, { "answer_id": 27627015, "author": "danijar", "author_id": 1079110, "author_profile": "https://Stackoverflow.com/users/1079110", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n\nvoid print_binary(unsigned int number)\n{\n if (number >> 1) {\n print_binary(number >> 1);\n }\n putc((number & 1) ? '1' : '0', stdout);\n}\n 0b" }, { "answer_id": 28796910, "author": "kapil", "author_id": 3888438, "author_profile": "https://Stackoverflow.com/users/3888438", "pm_score": 3, "selected": false, "text": "void bin(int n)\n{\n /* Step 1 */\n if (n > 1)\n bin(n/2);\n /* Step 2 */\n printf(\"%d\", n % 2);\n}\n" }, { "answer_id": 31660310, "author": "luart", "author_id": 1814353, "author_profile": "https://Stackoverflow.com/users/1814353", "pm_score": 2, "selected": false, "text": "#include <bitset>\nMyIntegralType num = 10;\nprint(\"%s\\n\",\n std::bitset<sizeof(num) * 8>(num).to_string().insert(0, \"0b\").c_str()\n); // prints \"0b1010\\n\"\n std::cout << std::bitset<sizeof(num) * 8>(num);" }, { "answer_id": 34641674, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 4, "selected": false, "text": "printf() \"%b\" printf() printf() fprintf() sprintf() vsprintf() \"%s\" printf() #include <assert.h>\n#include <limits.h>\n#define TO_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)\n\n// v--compound literal--v\n#define TO_BASE(x, b) my_to_base((char [TO_BASE_N]){\"\"}, (x), (b))\n\n// Tailor the details of the conversion function as needed\n// This one does not display unneeded leading zeros\n// Use return value, not `buf`\nchar *my_to_base(char buf[TO_BASE_N], unsigned i, int base) {\n assert(base >= 2 && base <= 36);\n char *s = &buf[TO_BASE_N - 1];\n *s = '\\0';\n do {\n s--;\n *s = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[i % base];\n i /= base;\n } while (i);\n\n // Could employ memmove here to move the used buffer to the beginning\n // size_t len = &buf[TO_BASE_N] - s;\n // memmove(buf, s, len);\n\n return s;\n}\n\n#include <stdio.h>\nint main(void) {\n int ip1 = 0x01020304;\n int ip2 = 0x05060708;\n printf(\"%s %s\\n\", TO_BASE(ip1, 16), TO_BASE(ip2, 16));\n printf(\"%s %s\\n\", TO_BASE(ip1, 2), TO_BASE(ip2, 2));\n puts(TO_BASE(ip1, 8));\n puts(TO_BASE(ip1, 36));\n return 0;\n}\n 1020304 5060708\n1000000100000001100000100 101000001100000011100001000\n100401404\nA2F44\n" }, { "answer_id": 34688422, "author": "Grzegorz Szpetkowski", "author_id": 586873, "author_profile": "https://Stackoverflow.com/users/586873", "pm_score": 0, "selected": false, "text": "const char* toBinaryString(unsigned long num)\n{\n static char buffer[CHAR_BIT*sizeof(num)+1];\n char* pBuffer = &buffer[sizeof(buffer)-1];\n\n do *--pBuffer = '0' + (num & 1);\n while (num >>= 1);\n return pBuffer;\n}\n NUL buffer unsigned long long num CHAR_BIT <limits.h> int main(void)\n{\n printf(\">>>%20s<<<\\n\", toBinaryString(1));\n printf(\">>>%-20s<<<\\n\", toBinaryString(254));\n return 0;\n}\n >>> 1<<<\n>>>11111110 <<<\n" }, { "answer_id": 36270476, "author": "SarahGaidi", "author_id": 3559270, "author_profile": "https://Stackoverflow.com/users/3559270", "pm_score": 2, "selected": false, "text": "long unsigned int i;\nfor(i = 0u; i < sizeof(integer) * CHAR_BIT; i++) {\n if(integer & LONG_MIN)\n printf(\"1\");\n else\n printf(\"0\");\n integer <<= 1;\n}\nprintf(\"\\n\");\n" }, { "answer_id": 39401342, "author": "Geyslan G. Bem", "author_id": 2776344, "author_profile": "https://Stackoverflow.com/users/2776344", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <limits.h>\n\n#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n#define for_endian(size) for (int i = 0; i < size; ++i)\n#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n#define for_endian(size) for (int i = size - 1; i >= 0; --i)\n#else\n#error \"Endianness not detected\"\n#endif\n\n#define printb(value) \\\n({ \\\n typeof(value) _v = value; \\\n __printb((typeof(_v) *) &_v, sizeof(_v)); \\\n})\n\n#define MSB_MASK 1 << (CHAR_BIT - 1)\n\nvoid __printb(void *value, size_t size)\n{\n unsigned char uc;\n unsigned char bits[CHAR_BIT + 1];\n\n bits[CHAR_BIT] = '\\0';\n for_endian(size) {\n uc = ((unsigned char *) value)[i];\n memset(bits, '0', CHAR_BIT);\n for (int j = 0; uc && j < CHAR_BIT; ++j) {\n if (uc & MSB_MASK)\n bits[j] = '1';\n uc <<= 1;\n }\n printf(\"%s \", bits);\n }\n printf(\"\\n\");\n}\n\nint main(void)\n{\n uint8_t c1 = 0xff, c2 = 0x44;\n uint8_t c3 = c1 + c2;\n\n printb(c1);\n printb((char) 0xff);\n printb((short) 0xff);\n printb(0xff);\n printb(c2);\n printb(0x44);\n printb(0x4411ff01);\n printb((uint16_t) c3);\n printb('A');\n printf(\"\\n\");\n\n return 0;\n}\n $ ./printb \n11111111 \n11111111 \n00000000 11111111 \n00000000 00000000 00000000 11111111 \n01000100 \n00000000 00000000 00000000 01000100 \n01000100 00010001 11111111 00000001 \n00000000 01000011 \n00000000 00000000 00000000 01000001 \n" }, { "answer_id": 42247968, "author": "Jan Turoň", "author_id": 343721, "author_profile": "https://Stackoverflow.com/users/343721", "pm_score": 1, "selected": false, "text": "sprintf const char* binary(int n) {\n static const char binnums[16][5] = { \"0000\",\"0001\",\"0010\",\"0011\",\n \"0100\",\"0101\",\"0110\",\"0111\",\"1000\",\"1001\",\"1010\",\"1011\",\"1100\",\"1101\",\"1110\",\"1111\" };\n static const char* hexnums = \"0123456789abcdef\";\n static char inbuffer[16], outbuffer[4*16];\n const char *i;\n sprintf(inbuffer,\"%x\",n); // hexadecimal n -> inbuffer\n for(i=inbuffer; *i!=0; ++i) { // for each hexadecimal cipher\n int d = strchr(hexnums,*i) - hexnums; // store its decimal value to d\n char* o = outbuffer+(i-inbuffer)*4; // shift four characters in outbuffer\n sprintf(o,\"%s\",binnums[d]); // place binary value of d there\n }\n return strchr(outbuffer,'1'); // omit leading zeros\n}\n\nputs(binary(42)); // outputs 101010\n" }, { "answer_id": 45041802, "author": "Kresimir", "author_id": 1127700, "author_profile": "https://Stackoverflow.com/users/1127700", "pm_score": 2, "selected": false, "text": "void print_binary(int number, int num_digits) {\n int digit;\n for(digit = num_digits - 1; digit >= 0; digit--) {\n printf(\"%c\", number & (1 << digit) ? '1' : '0');\n }\n}\n" }, { "answer_id": 45238104, "author": "Et7f3XIV", "author_id": 7227940, "author_profile": "https://Stackoverflow.com/users/7227940", "pm_score": 2, "selected": false, "text": "int8 16 32 64 INT8 /* --- PRINTF_BYTE_TO_BINARY macro's --- */\n#define PRINTF_BINARY_SEPARATOR\n#define PRINTF_BINARY_PATTERN_INT8 \"%c%c%c%c%c%c%c%c\"\n#define PRINTF_BYTE_TO_BINARY_INT8(i) \\\n (((i) & 0x80ll) ? '1' : '0'), \\\n (((i) & 0x40ll) ? '1' : '0'), \\\n (((i) & 0x20ll) ? '1' : '0'), \\\n (((i) & 0x10ll) ? '1' : '0'), \\\n (((i) & 0x08ll) ? '1' : '0'), \\\n (((i) & 0x04ll) ? '1' : '0'), \\\n (((i) & 0x02ll) ? '1' : '0'), \\\n (((i) & 0x01ll) ? '1' : '0')\n\n#define PRINTF_BINARY_PATTERN_INT16 \\\n PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT8\n#define PRINTF_BYTE_TO_BINARY_INT16(i) \\\n PRINTF_BYTE_TO_BINARY_INT8((i) >> 8), PRINTF_BYTE_TO_BINARY_INT8(i)\n#define PRINTF_BINARY_PATTERN_INT32 \\\n PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT16\n#define PRINTF_BYTE_TO_BINARY_INT32(i) \\\n PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)\n#define PRINTF_BINARY_PATTERN_INT64 \\\n PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT32\n#define PRINTF_BYTE_TO_BINARY_INT64(i) \\\n PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)\n/* --- end macros --- */\n\n#include <stdio.h>\nint main() {\n long long int flag = 1648646756487983144ll;\n printf(\"My Flag \"\n PRINTF_BINARY_PATTERN_INT64 \"\\n\",\n PRINTF_BYTE_TO_BINARY_INT64(flag));\n return 0;\n}\n My Flag 0001011011100001001010110111110101111000100100001111000000101000\n #define PRINTF_BINARY_SEPARATOR #define PRINTF_BINARY_SEPARATOR \",\" #define PRINTF_BINARY_SEPARATOR \" \" My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000\n My Flag 00010110 11100001 00101011 01111101 01111000 10010000 11110000 00101000\n" }, { "answer_id": 46193398, "author": "kapilddit", "author_id": 555911, "author_profile": "https://Stackoverflow.com/users/555911", "pm_score": 0, "selected": false, "text": "void conbin(int num){ \n if(num != 0)\n {\n conbin(num >> 1); \n if (num & 1){\n printf(\"1\");\n }\n else{\n printf(\"0\");\n }\n }\n }\n" }, { "answer_id": 48274667, "author": "Akhil", "author_id": 1000676, "author_profile": "https://Stackoverflow.com/users/1000676", "pm_score": 1, "selected": false, "text": "void DisplayBinary(int n)\n{\n int arr[8];\n int top =-1;\n while (n)\n {\n if (n & 1)\n arr[++top] = 1;\n else\n arr[++top] = 0;\n\n n >>= 1;\n }\n for (int i = top ; i > -1;i--)\n {\n printf(\"%d\",arr[i]);\n }\n printf(\"\\n\");\n}\n" }, { "answer_id": 49854917, "author": "Rassoul", "author_id": 3153052, "author_profile": "https://Stackoverflow.com/users/3153052", "pm_score": 2, "selected": false, "text": "void DisplayBinary(unsigned int n)\n{\n int l = sizeof(n) * 8;\n for (int i = l - 1 ; i >= 0; i--) {\n printf(\"%x\", (n & (1 << i)) >> i);\n }\n}\n" }, { "answer_id": 50310562, "author": "малин чекуров", "author_id": 9721071, "author_profile": "https://Stackoverflow.com/users/9721071", "pm_score": 3, "selected": false, "text": "void\nprint_binary(unsigned int n)\n{\n unsigned int mask = 0;\n /* this grotesque hack creates a bit pattern 1000... */\n /* regardless of the size of an unsigned int */\n mask = ~mask ^ (~mask >> 1);\n\n for(; mask != 0; mask >>= 1) {\n putchar((n & mask) ? '1' : '0');\n }\n\n}\n" }, { "answer_id": 51721063, "author": "Esann ", "author_id": 8623025, "author_profile": "https://Stackoverflow.com/users/8623025", "pm_score": 1, "selected": false, "text": "display_binary(int n)\n{\n long int arr[32];\n int arr_counter=0;\n while(n>=1)\n {\n arr[arr_counter++]=n%2;\n n/=2;\n }\n for(int i=arr_counter-1;i>=0;i--)\n {\n printf(\"%d\",arr[i]);\n }\n}\n" }, { "answer_id": 53850409, "author": "Robotbugs", "author_id": 986059, "author_profile": "https://Stackoverflow.com/users/986059", "pm_score": 4, "selected": false, "text": "void printbits(my_integer_type x)\n{\n for(int i=sizeof(x)<<3; i; i--)\n putchar('0'+((x>>(i-1))&1));\n}\n #define printbits_n(x,n) for (int i=n;i;i--,putchar('0'|(x>>i)&1))\n#define printbits_32(x) printbits_n(x,32)\n char *int_to_bitstring_alloc(int x, int count)\n{\n count = count<1 ? sizeof(x)*8 : count;\n char *pstr = malloc(count+1);\n for(int i = 0; i<count; i++)\n pstr[i] = '0' | ((x>>(count-1-i))&1);\n pstr[count]=0;\n return pstr;\n}\n\n#define BITSIZEOF(x) (sizeof(x)*8)\n\nchar *int_to_bitstring_static(int x, int count)\n{\n static char bitbuf[BITSIZEOF(x)+1];\n count = (count<1 || count>BITSIZEOF(x)) ? BITSIZEOF(x) : count;\n for(int i = 0; i<count; i++)\n bitbuf[i] = '0' | ((x>>(count-1-i))&1);\n bitbuf[count]=0;\n return bitbuf;\n}\n // memory allocated string returned which needs to be freed\nchar *pstr = int_to_bitstring_alloc(0x97e50ae6, 17);\nprintf(\"bits = 0b%s\\n\", pstr);\nfree(pstr);\n\n// no free needed but you need to copy the string to save it somewhere else\nchar *pstr2 = int_to_bitstring_static(0x97e50ae6, 17);\nprintf(\"bits = 0b%s\\n\", pstr2);\n" }, { "answer_id": 59489894, "author": "brunoais", "author_id": 551625, "author_profile": "https://Stackoverflow.com/users/551625", "pm_score": 0, "selected": false, "text": "putchar() printf() puts() print_binary_size() -O1 gcc inline void print_binary_sized(unsigned int number, unsigned int digits) {\n static char ZERO = '0';\n int digitsLeft = digits;\n \n do{\n putchar(ZERO + ((number >> digitsLeft) & 1));\n }while(digitsLeft--);\n }\n\n void print_binary(unsigned int number) {\n int digitsLeft = sizeof(number) * 8;\n \n while((~(number >> digitsLeft) & 1) && digitsLeft){\n digitsLeft--;\n }\n print_binary_sized(number, digitsLeft);\n }\n" }, { "answer_id": 62120014, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 0, "selected": false, "text": "// m specifies how many of the low bits are shown.\n// Replace m with sizeof(n) below for all bits and\n// remove it from the parameter list if you like.\n\nvoid print_binary(unsigned long n, unsigned long m) {\n static char show[3] = \"01\";\n unsigned long mask = 1ULL << (m-1);\n while(mask) {\n putchar(show[!!(n&mask)]); mask >>= 1;\n }\n putchar('\\n');\n}\n" }, { "answer_id": 62265806, "author": "NoComprende", "author_id": 6386071, "author_profile": "https://Stackoverflow.com/users/6386071", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdint.h>\n\nint binary(uint8_t i,int bigEndian)\n{\n int j=0,m = bigEndian ? 1 : 10000000;\n while (i)\n {\n j+=m*(i%2);\n if (bigEndian) m*=10; else m/=10;\n i >>= 1;\n }\n return j;\n}\n\nint main()\n{\n char buf[]=\"ABCDEF\";\n printf(\"\\nbig endian = \");\n for (int i=0; i<5; i++) printf(\"%08d \",binary(buf[i],1));\n printf(\"\\nwee endian = \");\n for (int i=0; i<5; i++) printf(\"%08d \",binary(buf[i],0));\n getchar();\n return 0;\n}\n big endian = 01000001 01000010 01000011 01000100 01000101 01000110\nwee endian = 10000010 01000010 11000010 00100010 10100010 01100010\n" }, { "answer_id": 62265841, "author": "Cosmo Sterin", "author_id": 5825820, "author_profile": "https://Stackoverflow.com/users/5825820", "pm_score": 1, "selected": false, "text": "float float_var = 9.4;\nSHOW_BITS(float_var);\n Variable 'float_var': 01000001 00010110 01100110 01100110 struct {int a; float b; double c;} struct_var = {1,1.1,1.2};\nSHOW_BITS(struct_var);\n Variable `struct_var`: 00111111 11110011 00110011 00110011 00110011 00110011 00110011 00110011 00111111 10001100 11001100 11001101 00000000 00000000 00000000 00000001\n #define SHOW_BITS(a) ({ \\\n printf(\"Variable `%s`: \", #a);\\\n show_bits(&a, sizeof(a));\\\n})\n\nvoid show_uchar(unsigned char a)\n{\n for(int i = 7; i >= 0; i-= 1) \n printf(\"%d\", ((a >> i) & 1));\n}\n\nvoid show_bits(void* a, size_t s)\n{\n unsigned char* p = (unsigned char*) a;\n for(int i = s-1; i >= 0 ; i -= 1) {\n show_uchar(p[i]);\n printf(\" \");\n }\n printf(\"\\n\");\n}\n" }, { "answer_id": 66298184, "author": "skyfire", "author_id": 6302316, "author_profile": "https://Stackoverflow.com/users/6302316", "pm_score": 1, "selected": false, "text": "void print_bits (uintmax_t n)\n{\n for (size_t i = 8 * sizeof (int); i-- != 0;)\n {\n char c;\n if ((n & (1UL << i)) != 0)\n c = '1';\n else\n c = '0';\n\n printf (\"%c\", c);\n\n }\n}\n" }, { "answer_id": 66680811, "author": "D.Deriso", "author_id": 1438550, "author_profile": "https://Stackoverflow.com/users/1438550", "pm_score": 0, "selected": false, "text": "// Based on https://stackoverflow.com/a/112956/1438550\n\n#include <stdio.h>\n#include <stdint.h>\n\nconst char *int_to_binary_str(int x, int N_bits){\n static char b[512];\n char *p = b;\n b[0] = '\\0';\n\n for(int i=(N_bits-1); i>=0; i--){\n *p++ = (x & (1<<i)) ? '1' : '0';\n if(!(i%4)) *p++ = ' ';\n }\n return b;\n}\n\nint main() {\n for(int i=31; i>=0; i--){\n printf(\"0x%08X %s \\n\", (1<<i), int_to_binary_str((1<<i), 32));\n }\n return 0;\n}\n Run:\ngcc -pthread -Wformat=0 -lm -o main main.c; ./main\n\nOutput:\n0x80000000 1000 0000 0000 0000 0000 0000 0000 0000 \n0x40000000 0100 0000 0000 0000 0000 0000 0000 0000 \n0x20000000 0010 0000 0000 0000 0000 0000 0000 0000 \n0x10000000 0001 0000 0000 0000 0000 0000 0000 0000 \n0x08000000 0000 1000 0000 0000 0000 0000 0000 0000 \n0x04000000 0000 0100 0000 0000 0000 0000 0000 0000 \n0x02000000 0000 0010 0000 0000 0000 0000 0000 0000 \n0x01000000 0000 0001 0000 0000 0000 0000 0000 0000 \n0x00800000 0000 0000 1000 0000 0000 0000 0000 0000 \n0x00400000 0000 0000 0100 0000 0000 0000 0000 0000 \n0x00200000 0000 0000 0010 0000 0000 0000 0000 0000 \n0x00100000 0000 0000 0001 0000 0000 0000 0000 0000 \n0x00080000 0000 0000 0000 1000 0000 0000 0000 0000 \n0x00040000 0000 0000 0000 0100 0000 0000 0000 0000 \n0x00020000 0000 0000 0000 0010 0000 0000 0000 0000 \n0x00010000 0000 0000 0000 0001 0000 0000 0000 0000 \n0x00008000 0000 0000 0000 0000 1000 0000 0000 0000 \n0x00004000 0000 0000 0000 0000 0100 0000 0000 0000 \n0x00002000 0000 0000 0000 0000 0010 0000 0000 0000 \n0x00001000 0000 0000 0000 0000 0001 0000 0000 0000 \n0x00000800 0000 0000 0000 0000 0000 1000 0000 0000 \n0x00000400 0000 0000 0000 0000 0000 0100 0000 0000 \n0x00000200 0000 0000 0000 0000 0000 0010 0000 0000 \n0x00000100 0000 0000 0000 0000 0000 0001 0000 0000 \n0x00000080 0000 0000 0000 0000 0000 0000 1000 0000 \n0x00000040 0000 0000 0000 0000 0000 0000 0100 0000 \n0x00000020 0000 0000 0000 0000 0000 0000 0010 0000 \n0x00000010 0000 0000 0000 0000 0000 0000 0001 0000 \n0x00000008 0000 0000 0000 0000 0000 0000 0000 1000 \n0x00000004 0000 0000 0000 0000 0000 0000 0000 0100 \n0x00000002 0000 0000 0000 0000 0000 0000 0000 0010 \n0x00000001 0000 0000 0000 0000 0000 0000 0000 0001 \n" }, { "answer_id": 70930112, "author": "roylewilliam", "author_id": 8423241, "author_profile": "https://Stackoverflow.com/users/8423241", "pm_score": 0, "selected": false, "text": "#include <stdint.h>\n#include <stdio.h>\n\n// Prints the binary representation of any unsigned integer\n// When running, pass 1 to first_call\nvoid printf_binary(unsigned int number, int first_call)\n{\n if (first_call)\n {\n printf(\"The binary representation of %d is [\", number);\n }\n if (number >> 1)\n {\n printf_binary(number >> 1, 0);\n putc((number & 1) ? '1' : '0', stdout);\n }\n else \n {\n putc((number & 1) ? '1' : '0', stdout);\n }\n if (first_call)\n {\n printf(\"]\\n\");\n }\n}\n" }, { "answer_id": 70993946, "author": "Kalcifer", "author_id": 7934600, "author_profile": "https://Stackoverflow.com/users/7934600", "pm_score": 4, "selected": false, "text": "%b" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8959/" ]
111,933
<p>I know what Hungarian refers to - giving information about a variable, parameter, or type as a prefix to its name. Everyone seems to be rabidly against it, even though in some cases it seems to be a good idea. If I feel that useful information is being imparted, why shouldn't I put it right there where it's available?</p> <p>See also: <a href="https://stackoverflow.com/questions/5428/do-people-use-the-hungarian-naming-conventions-in-the-real-world">Do people use the Hungarian naming conventions in the real world?</a> </p>
[ { "answer_id": 111972, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 8, "selected": true, "text": "type kind" }, { "answer_id": 112029, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "if (bVar)" }, { "answer_id": 112264, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 1, "selected": false, "text": "public string stringUniqueKey = \"ABC-12345\";\n public int intAge = 20;\n" }, { "answer_id": 112446, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 3, "selected": false, "text": "LRESULT CALLBACK WindowProc(HWND hwnd,\n UINT uMsg,\n WPARAM wParam,\n LPARAM lParam);\n" }, { "answer_id": 114485, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 7, "selected": false, "text": "strong typedef std::string unsafe_string; unsafe_string" }, { "answer_id": 114563, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 3, "selected": false, "text": "* l for local\n* a for argument\n* m for member\n* g for global\n* etc\n" }, { "answer_id": 124897, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 3, "selected": false, "text": "___str___() foo = 12\n print \"The current value of foo is %s\" % foo\n %s % foo.___str___() foo float(foo) $files_count $file_name" }, { "answer_id": 326901, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<asp:Label ID=\"lblFirstName\" runat=\"server\" Text=\"First Name\" />\n<asp:TextBox ID=\"txtFirstName\" runat=\"server\" />\n<asp:RequiredFieldValidator ID=\"rfvFirstName\" runat=\"server\" ... />\n" }, { "answer_id": 6853278, "author": "Adam Wuerl", "author_id": 539145, "author_profile": "https://Stackoverflow.com/users/539145", "pm_score": 3, "selected": false, "text": "frcGravityEarthMars = G * massEarth * massMars / norm(posEarth - posMars)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
111,934
<p>I want to create some text in a canvas:</p> <pre><code>myText = self.canvas.create_text(5, 5, anchor=NW, text=&quot;TEST&quot;) </code></pre> <p>Now how do I find the width and height of <code>myText</code>?</p>
[ { "answer_id": 111974, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 5, "selected": true, "text": "bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)\nwidth = bounds[2] - bounds[0]\nheight = bounds[3] - bounds[1]\n" }, { "answer_id": 35139726, "author": "user3754203", "author_id": 3754203, "author_profile": "https://Stackoverflow.com/users/3754203", "pm_score": 2, "selected": false, "text": "width = myText.winfo_width() \nheight = myText.winfo_height()\n" }, { "answer_id": 72682436, "author": "Ninja Adober Gab", "author_id": 18438874, "author_profile": "https://Stackoverflow.com/users/18438874", "pm_score": 0, "selected": false, "text": "def Height(Canvas, Object):\n Height = Canvas.bbox(Object)\n\n return Height[3] - Height[1]\ndef Width(Canvas, Object):\n Width = Canvas.bbox(Object)\n\n return Width[2] - Width[0]\ndef Position(Canvas, Object, X1=False, X2=False, Y1=False, Y2=False):\n Position = Canvas.bbox(Object)\n if X1 == True:\n return Position[0]\n if X2 == True:\n return Position[2]\n if Y1 == True:\n return Position[1]\n if Y2 == True:\n return Position[3]\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
[ { "answer_id": 111988, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 8, "selected": false, "text": "import urllib2\nopener = urllib2.build_opener(urllib2.HTTPHandler)\nrequest = urllib2.Request('http://example.org', data='your_put_data')\nrequest.add_header('Content-Type', 'your/contenttype')\nrequest.get_method = lambda: 'PUT'\nurl = opener.open(request)\n" }, { "answer_id": 3919484, "author": "Spooles", "author_id": 182750, "author_profile": "https://Stackoverflow.com/users/182750", "pm_score": 6, "selected": false, "text": "import httplib\nconnection = httplib.HTTPConnection('1.2.3.4:1234')\nbody_content = 'BODY CONTENT GOES HERE'\nconnection.request('PUT', '/url/path/to/put/to', body_content)\nresult = connection.getresponse()\n# Now result.status and result.reason contains interesting stuff\n" }, { "answer_id": 8259648, "author": "John Carter", "author_id": 459082, "author_profile": "https://Stackoverflow.com/users/459082", "pm_score": 9, "selected": true, "text": "payload = {'username': 'bob', 'email': 'bob@bob.com'}\n>>> r = requests.put(\"http://somedomain.org/endpoint\", data=payload)\n r.status_code\n r.content\n" }, { "answer_id": 26045274, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 4, "selected": false, "text": "pip install requests\n import requests\nimport json\nurl = 'https://api.github.com/some/endpoint'\npayload = {'some': 'data'}\n\n# Create your header as required\nheaders = {\"content-type\": \"application/json\", \"Authorization\": \"<auth-key>\" }\n\nr = requests.put(url, data=json.dumps(payload), headers=headers)\n" }, { "answer_id": 44781372, "author": "Wilfred Hughes", "author_id": 509706, "author_profile": "https://Stackoverflow.com/users/509706", "pm_score": 2, "selected": false, "text": "urllib2.Request import urllib2\n\nclass RequestWithMethod(urllib2.Request):\n def __init__(self, *args, **kwargs):\n self._method = kwargs.pop('method', None)\n urllib2.Request.__init__(self, *args, **kwargs)\n\n def get_method(self):\n return self._method if self._method else super(RequestWithMethod, self).get_method()\n\n\ndef put_request(url, data):\n opener = urllib2.build_opener(urllib2.HTTPHandler)\n request = RequestWithMethod(url, method='PUT', data=data)\n return opener.open(request)\n" }, { "answer_id": 48144049, "author": "anthony sottile", "author_id": 812183, "author_profile": "https://Stackoverflow.com/users/812183", "pm_score": 3, "selected": false, "text": "urllib.request.Request method=... req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')\nurllib.request.urlopen(req)\n" }, { "answer_id": 59418081, "author": "Adam Erickson", "author_id": 2058131, "author_profile": "https://Stackoverflow.com/users/2058131", "pm_score": 0, "selected": false, "text": "requests import requests\n\npayload = {'username': 'bob', 'email': 'bob@bob.com'}\n\ntry:\n response = requests.put(url=\"http://somedomain.org/endpoint\", data=payload)\n response.raise_for_status()\nexcept requests.exceptions.RequestException as e:\n print(e)\n raise\n" }, { "answer_id": 63219845, "author": "Ransaka Ravihara", "author_id": 11745014, "author_profile": "https://Stackoverflow.com/users/11745014", "pm_score": 0, "selected": false, "text": "urllib3 >>> import urllib3\n>>> http = urllib3.PoolManager()\n>>> from urllib.parse import urlencode\n>>> encoded_args = urlencode({\"name\":\"Zion\",\"salary\":\"1123\",\"age\":\"23\"})\n>>> url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args\n>>> r = http.request('PUT', url)\n>>> import json\n>>> json.loads(r.data.decode('utf-8'))\n{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}\n requests >>> import requests\n>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})\n>>> r.status_code\n200\n" }, { "answer_id": 66382115, "author": "SuperNova", "author_id": 3464971, "author_profile": "https://Stackoverflow.com/users/3464971", "pm_score": 1, "selected": false, "text": "requests.request import requests\n\nurl = \"https://www.example/com/some/url/\"\npayload=\"{\\\"param1\\\": 1, \\\"param1\\\": 2}\"\nheaders = {\n 'Authorization': '....',\n 'Content-Type': 'application/json'\n}\n\nresponse = requests.request(\"PUT\", url, headers=headers, data=payload)\n\nprint(response.text)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
[ { "answer_id": 111966, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 8, "selected": true, "text": "ftp.nlst(dir) files = []\n\ntry:\n files = ftp.nlst()\nexcept ftplib.error_perm as resp:\n if str(resp) == \"550 No files found\":\n print \"No files in this directory\"\n else:\n raise\n\nfor f in files:\n print f\n" }, { "answer_id": 111978, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 2, "selected": false, "text": "LIST ls DIR nlst NLST" }, { "answer_id": 8474838, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 5, "selected": false, "text": "import ftplib\nf = ftplib.FTP()\nf.connect(\"localhost\")\nf.login()\nls = []\nf.retrlines('MLSD', ls.append)\nfor entry in ls:\n print entry\n modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests\nmodify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2\nmodify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd\nmodify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart\n...\n" }, { "answer_id": 24090402, "author": "Steve Saporta", "author_id": 2108698, "author_profile": "https://Stackoverflow.com/users/2108698", "pm_score": 1, "selected": false, "text": "class FtpDir:\n def parse_dir_line(self, line):\n words = line.split()\n self.filename = words[8]\n self.size = int(words[4])\n t = words[7].split(':')\n ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]\n self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')\n" }, { "answer_id": 43818506, "author": "Jeeva", "author_id": 4737293, "author_profile": "https://Stackoverflow.com/users/4737293", "pm_score": 0, "selected": false, "text": ">>> from ftplib import FTP_TLS\n>>> ftps = FTP_TLS('ftp.python.org')\n>>> ftps.login() # login anonymously before securing control \nchannel\n>>> ftps.prot_p() # switch to secure data connection\n>>> ftps.retrlines('LIST') # list directory content securely\ntotal 9\ndrwxr-xr-x 8 root wheel 1024 Jan 3 1994 .\ndrwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..\ndrwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin\ndrwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc\nd-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming\ndrwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib\ndrwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub\ndrwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr\n-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg\n" }, { "answer_id": 43830703, "author": "MTS", "author_id": 7853455, "author_profile": "https://Stackoverflow.com/users/7853455", "pm_score": 0, "selected": false, "text": "elif command == 'ls':\n print(\"directory of \", ftp.pwd())\n data = []\n ftp.dir(data.append)\n\n for line in data:\n x = line.split(\".\")\n formats=[\"gz\", \"zip\", \"rar\", \"tar\", \"bz2\", \"xz\"]\n if x[-1] in formats:\n print (\"-\", line)\n" }, { "answer_id": 45684176, "author": "chill_turner", "author_id": 2639868, "author_profile": "https://Stackoverflow.com/users/2639868", "pm_score": 3, "selected": false, "text": "ftp.dir(dir_list.append) strip() split() ftp = FTP('sick.domain.bro')\nftp.login()\nftp.cwd('path/to/data')\n\ndir_list = []\nftp.dir(dir_list.append)\n\n# main thing is identifing which char marks start of good stuff\n# '-rw-r--r-- 1 ppsrt ppsrt 545498 Jul 23 12:07 FILENAME.FOO\n# ^ (that is line[29])\n\nfor line in dir_list:\n print line[29:].strip().split(' ') # got yerself an array there bud!\n # EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
111,983
<p>If you are creating a 1d array in Python, is there any benefit to using the NumPy package?</p>
[ { "answer_id": 43865968, "author": "nivniv", "author_id": 736211, "author_profile": "https://Stackoverflow.com/users/736211", "pm_score": 3, "selected": false, "text": "import numpy as np\nfrom array import array\n\n# Fixed size numpy array\ndef np_fixed(n):\n q = np.empty(n)\n for i in range(n):\n q[i] = i\n return q\n\n# Resize with np.resize\ndef np_class_resize(isize, n):\n q = np.empty(isize)\n for i in range(n):\n if i>=q.shape[0]:\n q = np.resize(q, q.shape[0]*2) \n q[i] = i\n return q \n\n# Resize with the numpy.array method\ndef np_method_resize(isize, n):\n q = np.empty(isize)\n for i in range(n):\n if i>=q.shape[0]:\n q.resize(q.shape[0]*2)\n q[i] = i\n return q\n\n# Array.array append\ndef arr(n):\n q = array('d')\n for i in range(n):\n q.append(i)\n return q\n\nisize = 1000\nn = 10000000\n %timeit -r 10 a = np_fixed(n)\n%timeit -r 10 a = np_class_resize(isize, n)\n%timeit -r 10 a = np_method_resize(isize, n)\n%timeit -r 10 a = arr(n)\n\n1 loop, best of 10: 868 ms per loop\n1 loop, best of 10: 2.03 s per loop\n1 loop, best of 10: 2.02 s per loop\n1 loop, best of 10: 1.89 s per loop\n" }, { "answer_id": 67131799, "author": "Alok Nayak", "author_id": 1756427, "author_profile": "https://Stackoverflow.com/users/1756427", "pm_score": -1, "selected": false, "text": "import sys\nimport numpy as np\nfrom array import array\n\ndef getsizeof_deep(obj, seen=None):\n \"\"\"Recursively finds size of objects\"\"\"\n size = sys.getsizeof(obj)\n if seen is None:\n seen = set()\n obj_id = id(obj)\n if obj_id in seen:\n return 0\n # Important mark as seen *before* entering recursion to gracefully handle\n # self-referential objects\n seen.add(obj_id)\n if isinstance(obj, dict):\n size += sum([getsizeof_deep(v, seen) for v in obj.values()])\n size += sum([getsizeof_deep(k, seen) for k in obj.keys()])\n elif hasattr(obj, '__dict__'):\n size += getsizeof_deep(obj.__dict__, seen)\n elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):\n size += sum([getsizeof_deep(i, seen) for i in obj])\n\n return size\n\nprint(\"size per element for list, tuple, numpy array, array.array:===============\")\nfor i in range(1, 100, 5):\n aa = list(range(i))\n n = len(aa)\n list_size = getsizeof_deep(aa)\n tup_aa = tuple(aa)\n tup_size = getsizeof_deep(tup_aa)\n nparr = np.array(aa, dtype='uint32')\n np_size = getsizeof_deep(nparr)\n arr = array('I', aa)#4 byte unsigned integer(in ubuntu)\n arr_size = getsizeof_deep(arr)\n print('number of element:%s, list %.2f, tuple %.2f, np.array %.2f, arr.array %.2f' % \\\n (len(aa), list_size/n, tup_size/n, np_size/n, arr_size/n))\n size per element for list, tuple, numpy array, array.array:===============\n\nnumber of element:1, list 88.00, tuple 72.00, np.array 136.00, arr.array 92.00\nnumber of element:6, list 44.67, tuple 42.00, np.array 49.33, arr.array 42.00\nnumber of element:11, list 40.73, tuple 39.27, np.array 41.45, arr.array 37.45\nnumber of element:16, list 39.25, tuple 38.25, np.array 38.50, arr.array 35.75\nnumber of element:21, list 38.48, tuple 37.71, np.array 36.95, arr.array 34.86\nnumber of element:26, list 38.00, tuple 37.38, np.array 36.00, arr.array 34.31\nnumber of element:31, list 37.68, tuple 37.16, np.array 35.35, arr.array 33.94\nnumber of element:36, list 37.44, tuple 37.00, np.array 34.89, arr.array 33.67\nnumber of element:41, list 37.27, tuple 36.88, np.array 34.54, arr.array 33.46\nnumber of element:46, list 37.13, tuple 36.78, np.array 34.26, arr.array 33.30\nnumber of element:51, list 37.02, tuple 36.71, np.array 34.04, arr.array 33.18\nnumber of element:56, list 36.93, tuple 36.64, np.array 33.86, arr.array 33.07\nnumber of element:61, list 36.85, tuple 36.59, np.array 33.70, arr.array 32.98\nnumber of element:66, list 36.79, tuple 36.55, np.array 33.58, arr.array 32.91\nnumber of element:71, list 36.73, tuple 36.51, np.array 33.46, arr.array 32.85\nnumber of element:76, list 36.68, tuple 36.47, np.array 33.37, arr.array 32.79\nnumber of element:81, list 36.64, tuple 36.44, np.array 33.28, arr.array 32.74\nnumber of element:86, list 36.60, tuple 36.42, np.array 33.21, arr.array 32.70\nnumber of element:91, list 36.57, tuple 36.40, np.array 33.14, arr.array 32.66\nnumber of element:96, list 36.54, tuple 36.38, np.array 33.08, arr.array 32.62\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
111,995
<p>Is there a way to separate a C# class into a header that contains the class definition and then an actual .cs file that contains the implementation? I suppose one can do this by creating an interface, but that doesn't seem right. I just want a file where I can just see the class design, and not all the detail. It's easy enough to do in C++, but I haven't seen it done with C#.</p> <p>Thanks in advance.</p>
[ { "answer_id": 112230, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 1, "selected": false, "text": "interface public interface IFoo\n{\n int DoFoo();\n}\n public class Foo : IFoo\n{\n public int DoFoo()\n {\n return 1;\n }\n}\n" }, { "answer_id": 113151, "author": "Jon", "author_id": 20188, "author_profile": "https://Stackoverflow.com/users/20188", "pm_score": 1, "selected": false, "text": "public sealed class Cache : IEnumerable\n{\n // Fields\n private CacheInternal _cacheInternal;\n public static readonly DateTime NoAbsoluteExpiration;\n public static readonly TimeSpan NoSlidingExpiration;\n\n // Methods\n static Cache();\n [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]\n public Cache();\n internal Cache(int dummy);\n public object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);\n public object Get(string key);\n internal object Get(string key, CacheGetOptions getOptions);\n public IDictionaryEnumerator GetEnumerator();\n public void Insert(string key, object value);\n public void Insert(string key, object value, CacheDependency dependencies);\n public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);\n public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);\n public object Remove(string key);\n internal void SetCacheInternal(CacheInternal cacheInternal);\n IEnumerator IEnumerable.GetEnumerator();\n\n // Properties\n public int Count { get; }\n public long EffectivePercentagePhysicalMemoryLimit { get; }\n public long EffectivePrivateBytesLimit { get; }\n public object this[string key] { get; set; }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20062/" ]
112,010
<p>How to enable inno-db support on installed instance of MySql?</p> <p>I have installed mysql-5.0.67-win32. 'InnoDB' is 'DISABLED' when executing 'show engines'. According to documentation MySql is compiled with support of inno-db (From doc: A value of DISABLED occurs either because the server was started with an option that disables the engine, or because not all options required to enable it were given.)</p> <p>In my.ini I commented line with 'skip-innodb'. This didn't help. All other inno-db related variables remain unchanged.</p> <p>I have performed some unusual action before I experienced described situation. I have mysql-4.0.17-win installed. I uninstall it and after this installed mysql-5.0.67-win32. In installation wizard I chose MyISAM support only (as far as I understand I disabled inno-db support in such way. When I tried to reinstall with support of inno-db I had problems of using my previous database 'mysql' with account information).</p> <p>MySQL documentation says that I should use mysqldump to export data and after this to import exported data in process of upgrade. I tried to do so, but when importing data I obtained message about syntax error (I think that it is connected with some incompatibilities of 4-th and 5-th version of mysql)</p>
[ { "answer_id": 112042, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 2, "selected": false, "text": "#*** INNODB Specific options ***\ninnodb_data_home_dir=\"C:/mysqldata/\"\n#skip-innodb\ninnodb_additional_mem_pool_size=120M\ninnodb_flush_log_at_trx_commit=1\ninnodb_log_buffer_size=16M\ninnodb_buffer_pool_size=10M\ninnodb_log_file_size=2M\ninnodb_thread_concurrency=8\n" }, { "answer_id": 112333, "author": "daremon", "author_id": 6346, "author_profile": "https://Stackoverflow.com/users/6346", "pm_score": 1, "selected": false, "text": "mysql --help" }, { "answer_id": 122492, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 1, "selected": true, "text": "mysqlcheck --all-databases --auto-repair" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13441/" ]
112,036
<p>I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp" /&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ trace (rightAxisGrp.selection); trace (rightAxisGrp.selection.data.name); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" dataField="left" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" dataField="right" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:dataProvider&gt; &lt;mx:Array&gt; &lt;mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Sambirano Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Simmons' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Pygmy Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Goodman's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Jolly's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Claire's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Lokobe Mouse Lemur" /&gt; &lt;mx:Object left="true" right="true" name="Bongolava Mouse Lemur" /&gt; &lt;/mx:Array&gt; &lt;/mx:dataProvider&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre> <hr> <p><em>UPDATED</em> (thanks bill!)</p> <p>Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.utils.ObjectProxy; import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection = new ArrayCollection (); private function selectItem (selObject:Object, property:String) : void { for each (var obj:ObjectProxy in myData) { obj[property] = (obj.name === selObject.name); } readingsGrid.invalidateDisplayList (); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (leftAxisGrp.selectedValue, 'left'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (rightAxisGrp.selectedValue, 'right'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" dataProvider="{myData}" sortExpertMode="true" height="150" width="400" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn id="leftCol" headerText="L" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" buttonMode="true" value="{data}" selected="{data.left}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn id="rightCol" headerText="R" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" buttonMode="true" value="{data}" selected="{data.right}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:creationComplete&gt; &lt;![CDATA[ myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" })); myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" })); ]]&gt; &lt;/mx:creationComplete&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre>
[ { "answer_id": 115926, "author": "bill d", "author_id": 1798, "author_profile": "https://Stackoverflow.com/users/1798", "pm_score": 2, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application layout=\"absolute\"\n xmlns:my=\"*\"\n xmlns:mx=\"http://www.adobe.com/2006/mxml\">\n <mx:RadioButtonGroup id=\"leftAxisGrp\"\n change=\"selectItem(leftAxisGrp.selectedValue, 'left');\"/>\n <mx:RadioButtonGroup id=\"rightAxisGrp\"\n change=\"selectItem(rightAxisGrp.selectedValue, 'right');\">\n </mx:RadioButtonGroup>\n <mx:AdvancedDataGrid\n id=\"readingsGrid\"\n designViewDataType=\"flat\"\n height=\"150\" width=\"400\"\n sortExpertMode=\"true\"\n selectable=\"false\"\n dataProvider=\"{adgData.object}\">\n <mx:columns>\n <mx:AdvancedDataGridColumn\n headerText=\"L\" width=\"25\" paddingLeft=\"6\"\n sortable=\"false\">\n <mx:itemRenderer>\n <mx:Component>\n <mx:RadioButton groupName=\"leftAxisGrp\" \n value=\"{data}\" selected=\"{data.left}\"/>\n </mx:Component>\n </mx:itemRenderer>\n </mx:AdvancedDataGridColumn>\n <mx:AdvancedDataGridColumn\n headerText=\"R\" width=\"25\" paddingLeft=\"6\"\n sortable=\"false\">\n <mx:itemRenderer>\n <mx:Component>\n <mx:RadioButton groupName=\"rightAxisGrp\"\n value=\"{data}\" selected=\"{data.right}\"/>\n </mx:Component>\n </mx:itemRenderer>\n </mx:AdvancedDataGridColumn>\n <mx:AdvancedDataGridColumn headerText=\"\" dataField=\"name\" />\n </mx:columns>\n </mx:AdvancedDataGrid>\n <mx:Model id=\"adgData\">\n <root>\n <object left=\"false\" right=\"false\" name=\"Reddish-gray Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Golden-brown Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Northern Rufous Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Sambirano Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Simmons' Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Pygmy Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Brown Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Madame Berthe's Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Goodman's Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Jolly's Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Mittermeier's Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Claire's Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Danfoss' Mouse Lemur\" />\n <object left=\"false\" right=\"false\" name=\"Lokobe Mouse Lemur\" />\n <object left=\"true\" right=\"true\" name=\"Bongolava Mouse Lemur\" />\n </root>\n </mx:Model>\n <mx:Script>\n <![CDATA[\n private function selectItem(selObject:Object, property:String) : void {\n for each(var obj:Object in adgData.object) {\n obj[property] = (obj === selObject);\n }\n readingsGrid.invalidateDisplayList();\n }\n ]]>\n </mx:Script>\n</mx:Application>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7536/" ]
112,055
<p>I'm looking at a batch file which defines the following variables:</p> <pre><code>set _SCRIPT_DRIVE=%~d0 set _SCRIPT_PATH=%~p0 </code></pre> <ul> <li>What do <code>%~d0</code> or <code>%~p0</code> actually mean?</li> <li>Is there a set of well-known values for things like current directory, drive, parameters to a script?</li> <li>Are there any other similar shortcuts I could use?</li> </ul>
[ { "answer_id": 112074, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "%~d0 %~p0" }, { "answer_id": 112120, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 7, "selected": false, "text": "%~I - expands %I removing any surrounding quotes (\"\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n FOR /?" }, { "answer_id": 112135, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 10, "selected": true, "text": "% %0 %1 %2 ~d ~p ~n ~dp %~dp0 ~t ~z" }, { "answer_id": 12484802, "author": "Clewaks", "author_id": 1515947, "author_profile": "https://Stackoverflow.com/users/1515947", "pm_score": 6, "selected": false, "text": "~ expands the given variable\nd gets the drive letter only\n0 is the argument you are referencing\n %~1 - expands %1 removing any surrounding quotes (\")\n%~f1 - expands %1 to a fully qualified path name\n%~d1 - expands %1 to a drive letter only\n%~p1 - expands %1 to a path only\n%~n1 - expands %1 to a file name only\n%~x1 - expands %1 to a file extension only\n%~s1 - expanded path contains short names only\n%~a1 - expands %1 to file attributes\n%~t1 - expands %1 to date/time of file\n%~z1 - expands %1 to size of file\n%~$PATH:1 - searches the directories listed in the PATH\n environment variable and expands %1 to the fully\n qualified name of the first one found. If the\n environment variable name is not defined or the\n file is not found by the search, then this\n modifier expands to the empty string \n\n%~dp1 - expands %1 to a drive letter and path only\n%~nx1 - expands %1 to a file name and extension only\n%~dp$PATH:1 - searches the directories listed in the PATH\n environment variable for %1 and expands to the\n drive letter and path of the first one found.\n%~ftza1 - expands %1 to a DIR like output line\n" }, { "answer_id": 13843928, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 2, "selected": false, "text": "@ECHO off\nSET \"PATH=%~dp0;%PATH%\"\nECHO %PATH%\nECHO.\nCALL :testargs \"these are days\" \"when the brave endure\"\nGOTO :pauseit\n:testargs\nSET ARGS=%~1;%~2;%1;%2\nECHO %ARGS%\nECHO.\nexit /B 0\n:pauseit\npause\n" }, { "answer_id": 24362536, "author": "Marvin Thobejane", "author_id": 1358924, "author_profile": "https://Stackoverflow.com/users/1358924", "pm_score": 4, "selected": false, "text": "%~d0 cd %~dp0 cd /d %~dp0" }, { "answer_id": 31941357, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 3, "selected": false, "text": "%0 c:\\test.bat @echo %0\n@pause\n \"C:\\test.bat\"\n %0 test.bat %0 c:\\>test.bat\ntest.bat\n test %0 c:\\>test\ntest\n tEsT c:\\>tEsT\ntEsT\n \"test\" %0 c:\\>\"test\"\n\"test\"\n \"C:\\test.bat\" c:\\>\"C:\\test.bat\"\n\"C:\\test.bat\"\n %0 c:\\some_folder>/../teST.bAt\n/../teST.bAt\n %~0 %~0 %0" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
112,064
<p>The word seems to get used in a number of contexts. The best I can figure is that they mean a variable that can't change. Isn't that what constants/finals (darn you Java!) are for?</p>
[ { "answer_id": 46055481, "author": "void", "author_id": 7863149, "author_profile": "https://Stackoverflow.com/users/7863149", "pm_score": 4, "selected": false, "text": "count sum // invariant:\n// we have read count grades so far, and\n// sum is the sum of the first count grades\n int count=0;\ndouble sum=0,x=0;\nwhile (cin >> x) {\n++count;\nsum+=x;\n}\n cin x count sum = sum + x while(cin>>x){\n }\n // we have read count grades so far, and\n ++count; while(cin>>x){\n ++count; \n }\n // sum is the sum of the first count grades\n x sum sum sum+=x cin>>x while(cin>>x){\n ++count; \n sum+=x;\n }\n // invariant:\n// we have read count grades so far, and\n// sum is the sum of the first count grades\n while(cin>>x){\n ++count; \n sum+=x;\n }\n" }, { "answer_id": 59839695, "author": "truthadjustr", "author_id": 2856202, "author_profile": "https://Stackoverflow.com/users/2856202", "pm_score": 4, "selected": false, "text": "pi pi" }, { "answer_id": 64788342, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 2, "selected": false, "text": "Class Invariant Invariant isBalanced isBalanced" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
112,085
<p>Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:</p> <pre><code>struct MY_STRUCT { int n1; int n2; }; class CMyStruct : public MY_STRUCT { public: CMyStruct() { memset(this, 0, sizeof(MY_STRUCT)); } }; </code></pre> <p>This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous <strong>cbSize</strong> member.</p> <p>Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice?</p>
[ { "answer_id": 112100, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": true, "text": "class CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct() { n1 = 0 ; n2 = 0 ; }\n};\n" }, { "answer_id": 112110, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "vtable memset(static_cast<MY_STRUCT*>(this), 0, sizeof(MY_STRUCT));\n memset" }, { "answer_id": 112116, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "CMyStruct::CMyStruct(MyStruct &)\n" }, { "answer_id": 112126, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 4, "selected": false, "text": "MY_STRUCT foo = { 0 };\n" }, { "answer_id": 112166, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "\nstruct MY_STRUCT\n{\n int n1;\n int n2;\n\n // Provide a default implementation...\n virtual int add() {return n1 + n2;} \n};\n" }, { "answer_id": 112353, "author": "Thanatopsis", "author_id": 15936, "author_profile": "https://Stackoverflow.com/users/15936", "pm_score": 1, "selected": false, "text": "struct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nclass CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct()\n {\n // whatever\n }\n void* new(size_t size)\n {\n // dangerous\n return memset(malloc(size),0,size);\n // better\n if (void *p = malloc(size))\n {\n return (memset(p, 0, size));\n }\n else\n {\n throw bad_alloc();\n }\n }\n void delete(void *p, size_t size)\n {\n free(p);\n }\n\n};\n" }, { "answer_id": 113943, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "struct A {\n int i;\n};\n\nclass B : public A { // 'B' is not a POD\npublic:\n B ();\n\nprivate:\n int j;\n};\n [ int i ][ int j ]\n [ int j ][ int i ]\n memset(static_cast<MY_STRUCT*>(this), 0, sizeof(MY_STRUCT));\n struct A {\n char c1;\n};\n\nstruct B {\n char c2;\n char c3;\n char c4;\n int i;\n};\n\nclass C : public A, public B\n{\npublic:\n C () \n : c1 (10);\n {\n memset(static_cast<B*>(this), 0, sizeof(B)); \n }\n};\n [ char c1 ] [ char c2, char c3, char c4, int i ]\n" }, { "answer_id": 115878, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "template <typename STR>\nclass CStructWrapper\n{\nprivate:\n STR MyStruct;\n\npublic:\n CStructWrapper() { STR temp = {}; MyStruct = temp;}\n CStructWrapper(const STR &myStruct) : MyStruct(myStruct) {}\n\n operator STR &() { return MyStruct; }\n operator const STR &() const { return MyStruct; }\n\n STR *GetPointer() { return &MyStruct; }\n};\n\nCStructWrapper<MY_STRUCT> myStruct;\nCStructWrapper<ANOTHER_STRUCT> anotherStruct;\n struct MY_STRUCT2\n{\n int n1;\n std::string s1;\n};\n\nCStructWrapper<MY_STRUCT2> myStruct2; // n1 is set to 0, s1 is set to \"\";\n" }, { "answer_id": 116794, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 0, "selected": false, "text": "STARTUPINFO si = {\n sizeof si, /*cb*/\n 0, /*lpReserved*/\n 0, /*lpDesktop*/\n \"my window\" /*lpTitle*/\n};\n" }, { "answer_id": 1312950, "author": "jwhitlock", "author_id": 10612, "author_profile": "https://Stackoverflow.com/users/10612", "pm_score": 1, "selected": false, "text": "struct MY_STRUCT\n{\n int n1;\n int n2;\n MY_STRUCT(): n1(0), n2(0) {}\n};\n" }, { "answer_id": 1315024, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "struct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nclass CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct():MY_STRUCT() { }\n};\n memset memset" }, { "answer_id": 1623268, "author": "grob", "author_id": 196454, "author_profile": "https://Stackoverflow.com/users/196454", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\n#define MY_STRUCT(x) MY_STRUCT x = {0}\n\nstruct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nint main(int argc, char *argv[])\n{\n MY_STRUCT(s);\n\n printf(\"n1(%d),n2(%d)\\n\", s.n1, s.n2);\n\n return 0;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
112,093
<p>I have a simple list I am using for a horizontal menu:</p> <pre><code>&lt;ul&gt; &lt;h1&gt;Menu&lt;/h1&gt; &lt;li&gt; &lt;a href="/" class="selected"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="/Home"&gt;Forum&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.</p> <p>Hope this makes sense.</p>
[ { "answer_id": 112106, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 5, "selected": true, "text": "display: block;\n" }, { "answer_id": 112114, "author": "Josh Hunt", "author_id": 2592, "author_profile": "https://Stackoverflow.com/users/2592", "pm_score": 2, "selected": false, "text": ".selected {\n display: block;\n width: 100%;\n background: #BEBEBE;\n}\n" }, { "answer_id": 112115, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<li> <a>" }, { "answer_id": 112150, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<a> a { display: block; } <a> <li>" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
112,112
<p>In terms of quick dynamically typed languages, I'm really starting to like Javascript, as I use it a lot for web projects, especially because it uses the same syntax as Actionscript (flash).</p> <p>It would be an ideal language for shell scripting, making it easier to move code from the front and back end of a site, and less of the strange syntax of python.</p> <p>Is there a good, javascript interpreter that is easy to install (I know there's one based on java, but that would mean installing all the java stuff to use), </p>
[ { "answer_id": 112122, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 1, "selected": false, "text": "scons sample=shell shell ./shell file.js" }, { "answer_id": 112128, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": true, "text": "cscript wscript" }, { "answer_id": 112141, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 4, "selected": false, "text": "$ sudo apt-get install spidermonkey\n$ js myfile.js\noutput\n$ js\njs> var f = function(){};\njs> f();\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20073/" ]
112,154
<p>I currently have a Java SAX parser that is extracting some info from a 30GB XML file. </p> <p>Presently it is:</p> <ul> <li>reading each XML node</li> <li>storing it into a string object, </li> <li>running some regexex on the string</li> <li>storing the results to the database</li> </ul> <p>For several million elements. I'm running this on a computer with 16GB of memory, but the memory is not being fully utilized. </p> <p>Is there a simple way to dynamically 'buffer' about 10gb worth of data from the input file? </p> <p>I suspect I could manually take a 'producer' 'consumer' multithreaded version of this (loading the objects on one side, using them and discarding on the other), but damnit, XML is ancient now, are there no efficient libraries to crunch em?</p>
[ { "answer_id": 112363, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 3, "selected": true, "text": "BufferedInputStream" }, { "answer_id": 112629, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 1, "selected": false, "text": "public void add(Object o) {\n super.add(o);\n if(size() > YOUR_DEFINED_THRESHOLD) {\n flushObjects();\n }\n}\n\nYOUR_DEFINED_THRESHOLD\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6545/" ]
112,158
<p>On my team, we usually do string concatentation like this:</p> <pre><code>var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("&lt;a href='").append(url).append("'&gt;click here&lt;/a&gt;"); </code></pre> <p>Obviously the following is much more readable:</p> <pre><code>var url = // some dynamically generated URL var sb = "&lt;a href='" + url + "'&gt;click here&lt;/a&gt;"; </code></pre> <p>But the JS experts claim that the <code>+</code> operator is less performant than <code>StringBuffer.append()</code>. Is this really true?</p>
[ { "answer_id": 112171, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 4, "selected": false, "text": "var s = [\"<a href='\", url, \"'>click here</a>\"].join(\"\");\n" }, { "answer_id": 112185, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 5, "selected": false, "text": "var buffer = [\"<a href='\", url, \"'>click here</a>\"];\nbuffer.push(\"More stuff\");\nalert(buffer.join(\"\"));\n" }, { "answer_id": 112223, "author": "amix", "author_id": 20081, "author_profile": "https://Stackoverflow.com/users/20081", "pm_score": 3, "selected": false, "text": "\"<a href='\" + url + \"'>click here</a>\";\n [\"<a href='\", url, \"'>click here</a>\"].join(\"\");\n" }, { "answer_id": 6970699, "author": "jasonc65", "author_id": 729005, "author_profile": "https://Stackoverflow.com/users/729005", "pm_score": 2, "selected": false, "text": "function href(url,txt) {\n return \"<a href='\" +url+ \"'>\" +txt+ \"</a>\"\n}\n\nfunction li(txt) {\n return \"<li>\" +txt+ \"</li>\"\n}\n\nfunction ul(arr) {\n return \"<ul>\" + arr.map(li).join(\"\") + \"</ul>\"\n}\n\ndocument.write(\n ul(\n [\n href(\"http://url1\",\"link1\"),\n href(\"http://url2\",\"link2\"),\n href(\"http://url3\",\"link3\")\n ]\n )\n)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
112,169
<p>For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this:</p> <pre><code>ShellExecute( hwnd, _T("open"), _T("http://www.winability.com/home/"), NULL, NULL, SW_NORMAL ); </code></pre> <p>It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page.</p> <p>Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?)</p> <p>EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks! </p>
[ { "answer_id": 112213, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 3, "selected": true, "text": "HINSTANCE GotoURL(LPCTSTR url, int showcmd)\n{\n TCHAR key[MAX_PATH + MAX_PATH];\n\n // First try ShellExecute()\n HINSTANCE result = 0;\n\n CString strURL = url;\n\n if ( strURL.Find(\".htm\") <0 && strURL.Find(\"http\") <0 )\n result = ShellExecute(NULL, _T(\"open\"), url, NULL, NULL, showcmd);\n\n // If it failed, get the .htm regkey and lookup the program\n if ((UINT)result <= HINSTANCE_ERROR) {\n\n if (GetRegKey(HKEY_CLASSES_ROOT, _T(\".htm\"), key) == ERROR_SUCCESS) {\n lstrcat(key, _T(\"\\\\shell\\\\open\\\\command\"));\n\n if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {\n TCHAR *pos;\n pos = _tcsstr(key, _T(\"\\\"%1\\\"\"));\n if (pos == NULL) { // No quotes found\n pos = strstr(key, _T(\"%1\")); // Check for %1, without quotes\n if (pos == NULL) // No parameter at all...\n pos = key+lstrlen(key)-1;\n else\n *pos = '\\0'; // Remove the parameter\n }\n else\n *pos = '\\0'; // Remove the parameter\n\n lstrcat(pos, _T(\" \\\"\"));\n lstrcat(pos, url);\n lstrcat(pos, _T(\"\\\"\"));\n result = (HINSTANCE) WinExec(key,showcmd);\n }\n }\n }\n\n return result;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ]
112,190
<p><code>My ISP</code> account requires that I send a username &amp; password for outbound <code>SMTP</code> mail. </p> <p>How do I get <code>PHP</code> to use this when executing <code>php.mail()?</code> The <code>php.ini</code> file only contains entries for the server <code>(SMTP= )</code> and <code>From: (sendmail_from= )</code>.</p>
[ { "answer_id": 112305, "author": "daremon", "author_id": 6346, "author_profile": "https://Stackoverflow.com/users/6346", "pm_score": 6, "selected": true, "text": "mail()" }, { "answer_id": 6941390, "author": "blavla", "author_id": 138844, "author_profile": "https://Stackoverflow.com/users/138844", "pm_score": 4, "selected": false, "text": "[mail function]\n; For Win32 only.\nSMTP = mail.yourserver.com\nsmtp_port = 25\nauth_username = smtp-username\nauth_password = smtp-password\nsendmail_from = you@yourserver.com\n" }, { "answer_id": 9642876, "author": "B Seven", "author_id": 336920, "author_profile": "https://Stackoverflow.com/users/336920", "pm_score": 3, "selected": false, "text": "<?php\n $message = \"test message body\";\n $result = mail('recipient@some-domain.com', 'message subject', $message);\n echo \"result: $result\";\n?>\n" }, { "answer_id": 9689896, "author": "sugunan", "author_id": 1101100, "author_profile": "https://Stackoverflow.com/users/1101100", "pm_score": 5, "selected": false, "text": "SMTP = smtp.example.com\nsmtp_port = 25\nusername = info@example.com\npassword = yourmailpassord\nsendmail_from = info@example.com\n" }, { "answer_id": 21891895, "author": "Henrik Rosvall", "author_id": 1974332, "author_profile": "https://Stackoverflow.com/users/1974332", "pm_score": 4, "selected": false, "text": "sendmail C:\\wamp\\ sendmail sendmail.exe libeay32.dll ssleay32.dll sendmail.ini C:\\wamp\\sendmail\\sendmail.ini smtp_server=smtp.gmail.com\nsmtp_port=465\nauth_username=user@gmail.com\nauth_password=your_password\n" }, { "answer_id": 31084190, "author": "Jay Sudo", "author_id": 5054971, "author_profile": "https://Stackoverflow.com/users/5054971", "pm_score": 3, "selected": false, "text": "/etc/postfix/main.cf #Relay config\nrelayhost = smtp.server.net\nsmtp_use_tls=yes\nsmtp_sasl_auth_enable=yes\nsmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd\nsmtp_tls_CAfile = /etc/postfix/cacert.pem\nsmtp_sasl_security_options = noanonymous\n /etc/postfix/sasl_passwd smtp.server.net username:password\n /usr/sbin/postmap sasl_passwd service postfix reload sendmail -t -i" }, { "answer_id": 49418191, "author": "Codedreamer", "author_id": 5659868, "author_profile": "https://Stackoverflow.com/users/5659868", "pm_score": 2, "selected": false, "text": "composer require phpmailer/phpmailer\n # use namespace\nuse PHPMailer\\PHPMailer\\PHPMailer;\n\n# require php mailer\nrequire_once \"../vendor/autoload.php\";\n\n//PHPMailer Object\n$mail = new PHPMailer;\n\n//From email address and name\n$mail->From = \"from@yourdomain.com\";\n$mail->FromName = \"Full Name\";\n\n//To address and name\n$mail->addAddress(\"recepient1@example.com\", \"Recepient Name\");\n$mail->addAddress(\"recepient1@example.com\"); //Recipient name is optional\n\n//Address to which recipient will reply\n$mail->addReplyTo(\"reply@yourdomain.com\", \"Reply\");\n\n//CC and BCC\n$mail->addCC(\"cc@example.com\");\n$mail->addBCC(\"bcc@example.com\");\n\n//Send HTML or Plain Text email\n$mail->isHTML(true);\n\n$mail->Subject = \"Subject Text\";\n$mail->Body = \"<i>Mail body in HTML</i>\";\n$mail->AltBody = \"This is the plain text version of the email content\";\n\nif(!$mail->send()) \n{\n echo \"Mailer Error: \" . $mail->ErrorInfo;\n} \nelse \n{\n echo \"Message has been sent successfully\";\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
112,197
<p>I want to create a hidden field and create a link in one helper and then output both to my erb.</p> <pre><code>&lt;%= my_cool_helper "something", form %&gt; </code></pre> <p>Should out put the results of</p> <pre><code>link_to "something", a_path form.hidden_field "something".tableize, :value =&gt; "something" </code></pre> <p>What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.</p>
[ { "answer_id": 112210, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 4, "selected": false, "text": "def my_cool_helper(name, form)\n out = capture { link_to name, a_path }\n out << capture { form.hidden_field name.tableize, value => 'something' }\nend\n" }, { "answer_id": 112211, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "link_to link_to( \"something\", something_path ) + #NOTE THE PLUS FOR STRING CONCAT\n form.hidden_field('something'.tableize, :value=>'something')\n render :partial" }, { "answer_id": 35012017, "author": "Jay_Pandya", "author_id": 5101365, "author_profile": "https://Stackoverflow.com/users/5101365", "pm_score": 2, "selected": false, "text": "concat +" }, { "answer_id": 59817311, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 2, "selected": false, "text": "safe_join + safe_join( [\n link_to( \"something\", something_path ),\n form.hidden_field( \"something\".tableize, value: \"something\" )\n] )\n +" }, { "answer_id": 64621458, "author": "estani", "author_id": 1182464, "author_profile": "https://Stackoverflow.com/users/1182464", "pm_score": 1, "selected": false, "text": "def output_siblings\n div1 = tag.div 'some content'\n div2 = tag.div 'other content'\n\n div1 + div2\nend\n" }, { "answer_id": 68521973, "author": "Clay Shentrup", "author_id": 8925319, "author_profile": "https://Stackoverflow.com/users/8925319", "pm_score": 0, "selected": false, "text": "def format_paragraphs(text)\n text.split(/\\r?\\n/).sum do |paragraph|\n tag.p(paragraph)\n end\nend\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
112,224
<p>I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.</p> <blockquote> <blockquote> <p>RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?</p> </blockquote> </blockquote> <p>I mean like the desktop or firefox, not something within my project.</p>
[ { "answer_id": 112593, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": " protected override void WndProc(ref Message m)\n {\n if (m.Msg == (int)WM_NCHITTEST)\n m.Result = (IntPtr)HTTRANSPARENT;\n else\n base.WndProc(ref m);\n }\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
112,234
<p>Let's say that I have two arrays (in Java),</p> <p>int[] numbers; and int[] colors;</p> <p>Each ith element of numbers corresponds to its ith element in colors. Ex, numbers = {4,2,1} colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.</p> <p>I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.</p> <p>Ex. numbers = {1,2,4}; colors = {0x01,0x24,0x11};</p> <p>What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.</p> <p><strong>Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?</strong></p>
[ { "answer_id": 112254, "author": "Frank Pape", "author_id": 10367, "author_profile": "https://Stackoverflow.com/users/10367", "pm_score": 3, "selected": false, "text": "class Color implements Comparable {\n private int number;\n private int color;\n\n // (snip ctor, setters, etc.)\n\n public int getNumber() {\n return number;\n }\n public int getColor() {\n return color;\n }\n\n public int compareTo(Color other) {\n if (this.getNumber() == other.getNumber) {\n return 0;\n } else if (this.getNumber() > other.getNumber) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n" }, { "answer_id": 112258, "author": "finrod", "author_id": 8295, "author_profile": "https://Stackoverflow.com/users/8295", "pm_score": 2, "selected": false, "text": "extra = [0,1,...,numbers.length-1]\n" }, { "answer_id": 112259, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 4, "selected": false, "text": "Integer[] idx = new Integer[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i; \nArrays.sort(idx, new Comparator<Integer>() {\n public int compare(Integer i1, Integer i2) { \n return Double.compare(numbers[i1], numbers[i2]);\n } \n});\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n Integer int" }, { "answer_id": 112299, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "int ptr[] = { 1, 2, 3 };\n for (int i = 0; i < ptr.length; i++)\n{\n printf(\"%d %d\\n\", numbers[ptr[i]], colors[ptr[i]]);\n}\n" }, { "answer_id": 118259, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 2, "selected": false, "text": " \n import java.util.*;\n\npublic class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n\n\n public class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n" }, { "answer_id": 36692597, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 1, "selected": false, "text": "@tovare int[] idx = new int[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i;\nfinal boolean isStableSort = false;\nPrimitive.sort(idx,\n (i1, i2) -> Double.compare(numbers[i1], numbers[i2]),\n isStableSort);\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n" }, { "answer_id": 45503395, "author": "Tung Ha", "author_id": 8416517, "author_profile": "https://Stackoverflow.com/users/8416517", "pm_score": 1, "selected": false, "text": "/**\n * work only for array of different numbers\n */\nprivate void sortPairArray(int[] numbers, int[] colors) {\n int[] tmpNumbers = Arrays.copyOf(numbers, numbers.length);\n int[] tmpColors = Arrays.copyOf(colors, colors.length);\n Arrays.sort(numbers);\n for (int i = 0; i < tmpNumbers.length; i++) {\n int number = tmpNumbers[i];\n int index = Arrays.binarySearch(numbers, number); // surely this will be found\n colors[index] = tmpColors[i];\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16773/" ]
112,235
<p>There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?</p> <p>I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.</p> <p>I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.</p>
[ { "answer_id": 112254, "author": "Frank Pape", "author_id": 10367, "author_profile": "https://Stackoverflow.com/users/10367", "pm_score": 3, "selected": false, "text": "class Color implements Comparable {\n private int number;\n private int color;\n\n // (snip ctor, setters, etc.)\n\n public int getNumber() {\n return number;\n }\n public int getColor() {\n return color;\n }\n\n public int compareTo(Color other) {\n if (this.getNumber() == other.getNumber) {\n return 0;\n } else if (this.getNumber() > other.getNumber) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n" }, { "answer_id": 112258, "author": "finrod", "author_id": 8295, "author_profile": "https://Stackoverflow.com/users/8295", "pm_score": 2, "selected": false, "text": "extra = [0,1,...,numbers.length-1]\n" }, { "answer_id": 112259, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 4, "selected": false, "text": "Integer[] idx = new Integer[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i; \nArrays.sort(idx, new Comparator<Integer>() {\n public int compare(Integer i1, Integer i2) { \n return Double.compare(numbers[i1], numbers[i2]);\n } \n});\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n Integer int" }, { "answer_id": 112299, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "int ptr[] = { 1, 2, 3 };\n for (int i = 0; i < ptr.length; i++)\n{\n printf(\"%d %d\\n\", numbers[ptr[i]], colors[ptr[i]]);\n}\n" }, { "answer_id": 118259, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 2, "selected": false, "text": " \n import java.util.*;\n\npublic class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n\n\n public class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n" }, { "answer_id": 36692597, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 1, "selected": false, "text": "@tovare int[] idx = new int[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i;\nfinal boolean isStableSort = false;\nPrimitive.sort(idx,\n (i1, i2) -> Double.compare(numbers[i1], numbers[i2]),\n isStableSort);\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n" }, { "answer_id": 45503395, "author": "Tung Ha", "author_id": 8416517, "author_profile": "https://Stackoverflow.com/users/8416517", "pm_score": 1, "selected": false, "text": "/**\n * work only for array of different numbers\n */\nprivate void sortPairArray(int[] numbers, int[] colors) {\n int[] tmpNumbers = Arrays.copyOf(numbers, numbers.length);\n int[] tmpColors = Arrays.copyOf(colors, colors.length);\n Arrays.sort(numbers);\n for (int i = 0; i < tmpNumbers.length; i++) {\n int number = tmpNumbers[i];\n int index = Arrays.binarySearch(numbers, number); // surely this will be found\n colors[index] = tmpColors[i];\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
112,249
<p>I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.</p> <p>Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.</p> <p>An update table set replicated=0;</p> <p>is not possible:</p> <ul> <li>It takes very much time</li> <li>It duplicates the size of the tabel because of MVCC</li> <li>It is done in one transaction: It either fails or goes through.</li> </ul> <p>I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.</p> <p>Several other problems: Doing an </p> <pre><code>update set replicated=0 where id &gt;10000 and id&lt;20000 </code></pre> <p>is also bad: It does a sequential scan all over the whole table which is too slow. If it weren't doing that, it would still be slow because it would be too many seeks.</p> <p>What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.</p> <p>Strangely, an</p> <pre><code>UPDATE table SET replicated=0 WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000) </code></pre> <p>is also slow, although it should be a good thing: Go through the table in DISK-order...</p> <p>(Note that in that case there was also an index that covered this)</p> <p>(An update LIMIT like Mysql is unavailable for PostgresQL)</p> <p>BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible It's PostgresQL 7.4 unfortunately.</p> <p>The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.</p> <p>The database itself only contains 5 tables, one is a very large one. But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!</p> <p>Any ideas?</p>
[ { "answer_id": 112315, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 2, "selected": false, "text": "CREATE TABLE bar AS SELECT everything, but, copied, 0 FROM foo lock ;\ncreate a new table, bar;\nswap tables so that all writes go to bar;\nunlock;\ncreate table baz as select from foo;\ndrop foo;\ncreate the index on baz;\nlock;\ninsert into baz from bar;\nswap tables;\nunlock;\ndrop bar;\n" }, { "answer_id": 113993, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 1, "selected": false, "text": "// write all ids to temporary file in disk order \n// no where clause will ensure disk order\n$file = tmpfile();\nfor $id, $replicated in query(\"select id, replicated from table\") {\n if ( $replicated<>0 ) {\n write($file,&$id,sizeof($id));\n }\n}\n\n// prepare an update query\nquery(\"prepare set_replicated_0(bigint) as\n update table set replicated=0 where id=?\");\n\n// reread this file, launch prepared query and every 1000000 updates commit\n// and vacuum a table\nrewind($file);\n$counter = 0;\nquery(\"start transaction\");\nwhile read($file,&$id,sizeof($id)) {\n query(\"execute set_replicated_0($id)\");\n $counter++;\n if ( $counter % 1000000 == 0 ) {\n query(\"commit\");\n query(\"vacuum table\");\n query(\"start transaction\");\n }\n}\nquery(\"commit\");\nquery(\"vacuum table\");\nclose($file);\n" }, { "answer_id": 116712, "author": "Grant Johnson", "author_id": 12518, "author_profile": "https://Stackoverflow.com/users/12518", "pm_score": 2, "selected": false, "text": "drop index replication_flag;\nupdate big_table set replicated=0;\ncreate index replication_flag on big_table btree(ID) WHERE replicated=0;\nvacuum full analyze big_table;\n" }, { "answer_id": 2369953, "author": "norlan V", "author_id": 285142, "author_profile": "https://Stackoverflow.com/users/285142", "pm_score": 0, "selected": false, "text": "UPDATE table1 SET name = table2.value\nFROM table2 \nWHERE table1.id = table2.id;\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20088/" ]
112,277
<p>Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:</p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt; int n &gt; struct factorial { enum { ret = factorial&lt; n - 1 &gt;::ret * n }; }; template&lt;&gt; struct factorial&lt; 0 &gt; { enum { ret = 1 }; }; int main() { cout &lt;&lt; "7! = " &lt;&lt; factorial&lt; 7 &gt;::ret &lt;&lt; endl; // 5040 return 0; } </code></pre> <p>If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?</p>
[ { "answer_id": 112302, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 8, "selected": true, "text": "NullType EmptyType" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
112,320
<p>I am a fan of <a href="https://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming">static metaprogramming in C++</a>. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it?</p>
[ { "answer_id": 112328, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 5, "selected": false, "text": "Object" }, { "answer_id": 112334, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "Class<T>" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
112,396
<p>I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> and <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>) to a remote location over SSH many times in an hour.</p> <p>One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?</p>
[ { "answer_id": 112409, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 12, "selected": true, "text": "$ ssh-keygen -p\n $ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n ~/.bash_history -f keyfile -P -N ~/.ssh/id_rsa" }, { "answer_id": 112618, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 6, "selected": false, "text": "if [ -f ~/.agent.env ] ; then\n . ~/.agent.env > /dev/null\n if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then\n echo \"Stale agent file found. Spawning new agent… \"\n eval `ssh-agent | tee ~/.agent.env`\n ssh-add\n fi \nelse\n echo \"Starting ssh-agent\"\n eval `ssh-agent | tee ~/.agent.env`\n ssh-add\nfi\n ssh-copy-id -i ~/.ssh/id_dsa.pub username@host\n" }, { "answer_id": 50703802, "author": "Karan", "author_id": 9898576, "author_profile": "https://Stackoverflow.com/users/9898576", "pm_score": 7, "selected": false, "text": "$ ssh-keygen -p $ ssh-keygen -p" }, { "answer_id": 57749743, "author": "bbaassssiiee", "author_id": 571517, "author_profile": "https://Stackoverflow.com/users/571517", "pm_score": 3, "selected": false, "text": "ssh-keygen -K\n ~/.ssh/config UseKeychain yes\n" }, { "answer_id": 58052425, "author": "ccalvert", "author_id": 253576, "author_profile": "https://Stackoverflow.com/users/253576", "pm_score": 5, "selected": false, "text": "p f ssh-keygen -p -f <name-of-private-key> ssh-keygen -p -f id_rsa ssh-keygen -p -f id_rsa\nEnter old passphrase: \nKey has comment 'bcuser@pl1909'\nEnter new passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved with the new passphrase.\n ssh-keygen -p -f id_rsa\nKey has comment 'charlie@elf-path'\nEnter new passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved with the new passphrase.\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14191/" ]
112,412
<p>I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly.</p> <p>I have done some research on the subject and have come to the conclusion that there are several options:</p> <ol> <li>Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do.</li> <li>Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc.</li> <li>Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11.</li> </ol> <p>Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt.</p> <p>Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer.</p> <p>Similar method used to Option (2), but users on the thread are not contactable:<br> <a href="http://www.codeguru.com/forum/archive/index.php/t-284051.html" rel="nofollow noreferrer">http://www.codeguru.com/forum/archive/index.php/t-284051.html</a><br> (also, I have my doubts about the necessity of an intermediary batch file)</p> <p>Out of date explanation to my question:<br> <a href="http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html" rel="nofollow noreferrer">http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html</a></p> <p>Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file:<br> <a href="http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit" rel="nofollow noreferrer">http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit</a></p> <p>I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much.</p>
[ { "answer_id": 2403173, "author": "Sam Harwell", "author_id": 138304, "author_profile": "https://Stackoverflow.com/users/138304", "pm_score": 3, "selected": true, "text": "(x86) C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\VCProjectDefaults\\masm.rules\n *.inc" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20110/" ]
112,433
<p>In a C++ project I'm working on, I have a <em>flag</em> kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:</p> <ul> <li>new record</li> <li>deleted record</li> <li>modified record</li> <li>existing record</li> </ul> <p>Now, for each record I wish to keep this attribute, so I could use an enum:</p> <pre><code>enum { xNew, xDeleted, xModified, xExisting } </code></pre> <p>However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: </p> <pre><code>showRecords(xNew | xDeleted); </code></pre> <p>So, it seems I have three possible appoaches:</p> <pre><code>#define X_NEW 0x01 #define X_DELETED 0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08 </code></pre> <p>or</p> <pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; </code></pre> <p>or </p> <pre><code>namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8; } </code></pre> <p>Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with <code>enum</code> I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With <code>const</code> I think I also lose type safety since a random <code>uint8</code> could get in by mistake.</p> <p>Is there some other cleaner way?</p> <p>If not, what would you use and why?</p> <p>P.S. The rest of the code is rather clean modern C++ without <code>#define</code>s, and I have used namespaces and templates in few spaces, so those aren't out of question either.</p>
[ { "answer_id": 112475, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": false, "text": "typedef std::bitset<4> RecordType;\n static const RecordType xNew(1);\nstatic const RecordType xDeleted(2);\nstatic const RecordType xModified(4);\nstatic const RecordType xExisting(8);\n RecordType rt = whatever; // unsigned long or RecordType expression\nrt |= xNew; // set \nrt &= ~xDeleted; // clear \nif ((rt & xModified) != 0) ... // test\n" }, { "answer_id": 112500, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 2, "selected": false, "text": "struct RecordFlag {\n unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;\n};\n" }, { "answer_id": 112529, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;\n" }, { "answer_id": 112591, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "struct RecordFlag {\n unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;\n};\n namespace RecordType {\n static const uint8 xNew = 1;\n static const uint8 xDeleted = 2;\n static const uint8 xModified = 4;\n static const uint8 xExisting = 8;\n}\n namespace RecordType {\n const uint8 xNew = 1;\n const uint8 xDeleted = 2;\n const uint8 xModified = 4;\n const uint8 xExisting = 8;\n}\n typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;\n enum RecordType { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;\n\nvoid doSomething(RecordType p_eMyEnum)\n{\n if(p_eMyEnum == xNew)\n {\n // etc.\n }\n}\n namespace RecordType {\n enum Value { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;\n}\n\nvoid doSomething(RecordType::Value p_eMyEnum)\n{\n if(p_eMyEnum == RecordType::xNew)\n {\n // etc.\n }\n}\n // Header.hpp\nnamespace RecordType {\n extern const uint8 xNew ;\n extern const uint8 xDeleted ;\n extern const uint8 xModified ;\n extern const uint8 xExisting ;\n}\n // Source.hpp\nnamespace RecordType {\n const uint8 xNew = 1;\n const uint8 xDeleted = 2;\n const uint8 xModified = 4;\n const uint8 xExisting = 8;\n}\n" }, { "answer_id": 112838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#define X_NEW (1 << 0)\n#define X_DELETED (1 << 1)\n#define X_MODIFIED (1 << 2)\n#define X_EXISTING (1 << 3)\n" }, { "answer_id": 113560, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 8, "selected": true, "text": "namespace RecordType {\n enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8,\n xInvalid = 16 };\n typedef int 0xDEADBEEF inline bool IsValidState( TRecordType v) {\n switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; }\n return false;\n}\n\n inline bool IsValidMask( TRecordType v) {\n return v >= xNew && v < xInvalid ;\n}\n using using RecordType ::TRecordType ;\n void showRecords(TRecordType mask) {\n assert(RecordType::IsValidMask(mask));\n // do stuff;\n}\n\nvoid wombleRecord(TRecord rec, TRecordType state) {\n assert(RecordType::IsValidState(state));\n if (RecordType ::xNew) {\n // ...\n} in runtime\n\nTRecordType updateRecord(TRecord rec, TRecordType newstate) {\n assert(RecordType::IsValidState(newstate));\n //...\n if (! access_was_successful) return RecordType ::xInvalid;\n return newstate;\n}\n" }, { "answer_id": 11847029, "author": "Tony Delroy", "author_id": 410767, "author_profile": "https://Stackoverflow.com/users/410767", "pm_score": 2, "selected": false, "text": "// signed defines\n#define X_NEW 0x01u\n#define X_NEW (unsigned(0x01)) // if you find this more readable...\n struct X\n{\n RecordType recordType : 4; // use exactly 4 bits...\n RecordType recordType2 : 4; // use another 4 bits, typically in the same byte\n // of course, the overall record size may still be padded...\n};\n RecordType operator|(RecordType lhs, RecordType rhs)\n{\n return RecordType((unsigned)lhs | (unsigned)rhs);\n}\n enum RecordType { New, Deleted, Modified, Existing };\n\nshowRecords([](RecordType r) { return r == New || r == Deleted; });\n uint8_t" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
112,439
<p>If you had read my other <a href="https://stackoverflow.com/questions/111700/6502-cpu-emulation">question</a>, you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise.</p> <p>The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine.</p> <p>My current test loop is this:</p> <pre><code> // Just loop infinitely. while (1 == 1) { CPU.ClockCyclesBeforeNext--; if (CPU.ClockCyclesBeforeNext &lt;= 0) { // Find out how many clock cycles this instruction will take CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles; // Run the instruction CPU.ExecuteInstruction(CPU.Memory[CPU.PC]); // Debugging Info CPU.DumpDebug(); Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength); // Move to next instruction CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength; } } </code></pre> <p>As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast.</p> <p>The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up.</p> <p>Any ideas?</p>
[ { "answer_id": 827720, "author": "Jason Fritcher", "author_id": 56038, "author_profile": "https://Stackoverflow.com/users/56038", "pm_score": 4, "selected": false, "text": "int execute_run_loop( int cycles )\n{\n int n = 0;\n while( n < cycles )\n {\n /* Returns number of cycles executed */\n n += execute_next_opcode();\n }\n\n return n;\n}\n" }, { "answer_id": 1393529, "author": "David Gardner", "author_id": 86080, "author_profile": "https://Stackoverflow.com/users/86080", "pm_score": 3, "selected": false, "text": "cycles = clock speed in Hz / required frames-per-second\n" }, { "answer_id": 31866088, "author": "Jay", "author_id": 390720, "author_profile": "https://Stackoverflow.com/users/390720", "pm_score": 0, "selected": false, "text": " #region Copyright\n/*\nThis file came from Managed Media Aggregation, You can always find the latest version @ https://net7mma.codeplex.com/\n\n Julius.Friedman@gmail.com / (SR. Software Engineer ASTI Transportation Inc. http://www.asti-trans.com)\n\nPermission is hereby granted, free of charge, \n * to any person obtaining a copy of this software and associated documentation files (the \"Software\"), \n * to deal in the Software without restriction, \n * including without limitation the rights to :\n * use, \n * copy, \n * modify, \n * merge, \n * publish, \n * distribute, \n * sublicense, \n * and/or sell copies of the Software, \n * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * \n * JuliusFriedman@gmail.com should be contacted for further details.\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n * \n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, \n * ARISING FROM, \n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n * \n * v//\n */\n#endregion\nnamespace Media.Concepts.Classes\n{\n //Windows.Media.Clock has a fairly complex but complete API\n\n /// <summary>\n /// Provides a clock with a given offset and calendar.\n /// </summary>\n public class Clock : Media.Common.BaseDisposable\n {\n static bool GC = false;\n\n #region Fields\n\n /// <summary>\n /// Indicates when the clock was created\n /// </summary>\n public readonly System.DateTimeOffset Created;\n\n /// <summary>\n /// The calendar system of the clock\n /// </summary>\n public readonly System.Globalization.Calendar Calendar;\n\n /// <summary>\n /// The amount of ticks which occur per update of the <see cref=\"System.Environment.TickCount\"/> member.\n /// </summary>\n public readonly long TicksPerUpdate;\n\n /// <summary>\n /// The amount of instructions which occured when synchronizing with the system clock.\n /// </summary>\n public readonly long InstructionsPerClockUpdate;\n\n #endregion\n\n #region Properties\n\n /// <summary>\n /// The TimeZone offset of the clock from UTC\n /// </summary>\n public System.TimeSpan Offset { get { return Created.Offset; } }\n\n /// <summary>\n /// The average amount of operations per tick.\n /// </summary>\n public long AverageOperationsPerTick { get { return InstructionsPerClockUpdate / TicksPerUpdate; } }\n\n /// <summary>\n /// The <see cref=\"System.TimeSpan\"/> which represents <see cref=\"TicksPerUpdate\"/> as an amount of time.\n /// </summary>\n public System.TimeSpan SystemClockResolution { get { return System.TimeSpan.FromTicks(TicksPerUpdate); } }\n\n /// <summary>\n /// Return the current system time in the TimeZone offset of this clock\n /// </summary>\n public System.DateTimeOffset Now { get { return System.DateTimeOffset.Now.ToOffset(Offset).Add(new System.TimeSpan((long)(AverageOperationsPerTick / System.TimeSpan.TicksPerMillisecond))); } }\n\n /// <summary>\n /// Return the current system time in the TimeZone offset of this clock converter to UniversalTime.\n /// </summary>\n public System.DateTimeOffset UtcNow { get { return Now.ToUniversalTime(); } }\n\n //public bool IsUtc { get { return Offset == System.TimeSpan.Zero; } }\n\n //public bool IsDaylightSavingTime { get { return Created.LocalDateTime.IsDaylightSavingTime(); } }\n\n #endregion\n\n #region Constructor\n\n /// <summary>\n /// Creates a clock using the system's current timezone and calendar.\n /// The system clock is profiled to determine it's accuracy\n /// <see cref=\"System.DateTimeOffset.Now.Offset\"/>\n /// <see cref=\"System.Globalization.CultureInfo.CurrentCulture.Calendar\"/>\n /// </summary>\n public Clock(bool shouldDispose = true)\n : this(System.DateTimeOffset.Now.Offset, System.Globalization.CultureInfo.CurrentCulture.Calendar, shouldDispose)\n {\n try { if (false == GC && System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.NoGCRegion) GC = System.GC.TryStartNoGCRegion(0); }\n catch { }\n finally\n {\n\n System.Threading.Thread.BeginCriticalRegion();\n\n //Sample the TickCount\n long ticksStart = System.Environment.TickCount,\n ticksEnd;\n\n //Continually sample the TickCount. while the value has not changed increment InstructionsPerClockUpdate\n while ((ticksEnd = System.Environment.TickCount) == ticksStart) ++InstructionsPerClockUpdate; //+= 4; Read,Assign,Compare,Increment\n\n //How many ticks occur per update of TickCount\n TicksPerUpdate = ticksEnd - ticksStart;\n\n System.Threading.Thread.EndCriticalRegion();\n }\n }\n\n /// <summary>\n /// Constructs a new clock using the given TimeZone offset and Calendar system\n /// </summary>\n /// <param name=\"timeZoneOffset\"></param>\n /// <param name=\"calendar\"></param>\n /// <param name=\"shouldDispose\">Indicates if the instace should be diposed when Dispose is called.</param>\n public Clock(System.TimeSpan timeZoneOffset, System.Globalization.Calendar calendar, bool shouldDispose = true)\n {\n //Allow disposal\n ShouldDispose = shouldDispose;\n\n Calendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;\n\n Created = new System.DateTimeOffset(System.DateTime.Now, timeZoneOffset);\n }\n\n #endregion\n\n #region Overrides\n\n public override void Dispose()\n {\n\n if (false == ShouldDispose) return;\n\n base.Dispose();\n\n try\n {\n if (System.Runtime.GCSettings.LatencyMode == System.Runtime.GCLatencyMode.NoGCRegion)\n {\n System.GC.EndNoGCRegion();\n\n GC = false;\n }\n }\n catch { }\n }\n\n #endregion\n\n //Methods or statics for OperationCountToTimeSpan? (Estimate)\n public void NanoSleep(int nanos)\n {\n Clock.NanoSleep((long)nanos);\n }\n\n public static void NanoSleep(long nanos)\n {\n System.Threading.Thread.BeginCriticalRegion(); \n\n NanoSleep(ref nanos); \n\n System.Threading.Thread.EndCriticalRegion();\n }\n\n static void NanoSleep(ref long nanos)\n {\n try\n {\n unchecked\n {\n while (Common.Binary.Clamp(--nanos, 0, 1) >= 2)\n { \n /* if(--nanos % 2 == 0) */\n NanoSleep(long.MinValue); //nanos -= 1 + (ops / (ulong)AverageOperationsPerTick);// *10;\n }\n }\n }\n catch\n {\n return;\n }\n }\n }\n}\n Timer /// <summary>\n/// Provides a Timer implementation which can be used across all platforms and does not rely on the existing Timer implementation.\n/// </summary>\npublic class Timer : Common.BaseDisposable\n{\n readonly System.Threading.Thread m_Counter; // m_Consumer, m_Producer\n\n internal System.TimeSpan m_Frequency;\n\n internal ulong m_Ops = 0, m_Ticks = 0;\n\n bool m_Enabled;\n\n internal System.DateTimeOffset m_Started;\n\n public delegate void TickEvent(ref long ticks);\n\n public event TickEvent Tick;\n\n public bool Enabled { get { return m_Enabled; } set { m_Enabled = value; } }\n\n public System.TimeSpan Frequency { get { return m_Frequency; } }\n\n internal ulong m_Bias;\n\n //\n\n //Could just use a single int, 32 bits is more than enough.\n\n //uint m_Flags;\n\n //\n\n readonly internal Clock m_Clock = new Clock();\n\n readonly internal System.Collections.Generic.Queue<long> Producer;\n\n void Count()\n {\n\n System.Threading.Thread Event = new System.Threading.Thread(new System.Threading.ThreadStart(() =>\n {\n System.Threading.Thread.BeginCriticalRegion();\n long sample;\n AfterSample:\n try\n {\n Top:\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;\n\n while (m_Enabled && Producer.Count >= 1)\n {\n sample = Producer.Dequeue();\n\n Tick(ref sample);\n }\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n\n if (false == m_Enabled) return;\n\n while (m_Enabled && Producer.Count == 0) if(m_Counter.IsAlive) m_Counter.Join(0); //++m_Ops;\n\n goto Top;\n }\n catch { if (false == m_Enabled) return; goto AfterSample; }\n finally { System.Threading.Thread.EndCriticalRegion(); }\n }))\n {\n IsBackground = false,\n Priority = System.Threading.ThreadPriority.AboveNormal\n };\n\n Event.TrySetApartmentState(System.Threading.ApartmentState.MTA);\n\n Event.Start();\n\n Approximate:\n\n ulong approximate = (ulong)Common.Binary.Clamp((m_Clock.AverageOperationsPerTick / (Frequency.Ticks + 1)), 1, ulong.MaxValue);\n\n try\n {\n m_Started = m_Clock.Now;\n\n System.Threading.Thread.BeginCriticalRegion();\n\n unchecked\n {\n Start:\n\n if (IsDisposed) return;\n\n switch (++m_Ops)\n {\n default:\n {\n if (m_Bias + ++m_Ops >= approximate)\n {\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;\n\n Producer.Enqueue((long)m_Ticks++);\n\n ulong x = ++m_Ops / approximate;\n\n while (1 > --x /*&& Producer.Count <= m_Frequency.Ticks*/) Producer.Enqueue((long)++m_Ticks);\n\n m_Ops = (++m_Ops * m_Ticks) - (m_Bias = ++m_Ops / approximate);\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n }\n\n if(Event != null) Event.Join(m_Frequency);\n\n goto Start;\n }\n }\n }\n }\n catch (System.Threading.ThreadAbortException) { if (m_Enabled) goto Approximate; System.Threading.Thread.ResetAbort(); }\n catch (System.OutOfMemoryException) { if ((ulong)Producer.Count > approximate) Producer.Clear(); if (m_Enabled) goto Approximate; }\n catch { if (m_Enabled) goto Approximate; }\n finally\n {\n Event = null;\n\n System.Threading.Thread.EndCriticalRegion();\n }\n }\n\n public Timer(System.TimeSpan frequency)\n {\n Producer = new System.Collections.Generic.Queue<long>((int)(m_Frequency = frequency).Ticks * 10);\n\n m_Counter = new System.Threading.Thread(new System.Threading.ThreadStart(Count))\n {\n IsBackground = false,\n Priority = System.Threading.ThreadPriority.AboveNormal\n };\n\n m_Counter.TrySetApartmentState(System.Threading.ApartmentState.MTA);\n\n Tick = delegate { m_Ops += 1 + m_Bias; };\n }\n\n public void Start()\n {\n if (m_Enabled) return;\n\n m_Enabled = true;\n\n m_Counter.Start();\n\n var p = System.Threading.Thread.CurrentThread.Priority;\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n\n while (m_Ops == 0) m_Counter.Join(0); //m_Clock.NanoSleep(0);\n\n System.Threading.Thread.CurrentThread.Priority = p;\n\n }\n\n public void Stop()\n {\n m_Enabled = false;\n }\n\n void Change(System.TimeSpan interval, System.TimeSpan dueTime)\n {\n m_Enabled = false;\n\n m_Frequency = interval;\n\n m_Enabled = true;\n }\n\n delegate void ElapsedEvent(object sender, object args);\n\n public override void Dispose()\n {\n if (IsDisposed) return; \n\n base.Dispose();\n\n Stop();\n\n try { m_Counter.Abort(m_Frequency); }\n catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); }\n catch { }\n\n Tick = null;\n\n //Producer.Clear();\n }\n\n}\n /// <summary>\n/// Provides a completely managed implementation of <see cref=\"System.Diagnostics.Stopwatch\"/> which expresses time in the same units as <see cref=\"System.TimeSpan\"/>.\n/// </summary>\npublic class Stopwatch : Common.BaseDisposable\n{\n internal Timer Timer;\n\n long Units;\n\n public bool Enabled { get { return Timer != null && Timer.Enabled; } }\n\n public double ElapsedMicroseconds { get { return Units * Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(Timer.Frequency); } }\n\n public double ElapsedMilliseconds { get { return Units * Timer.Frequency.TotalMilliseconds; } }\n\n public double ElapsedSeconds { get { return Units * Timer.Frequency.TotalSeconds; } }\n\n //public System.TimeSpan Elapsed { get { return System.TimeSpan.FromMilliseconds(ElapsedMilliseconds / System.TimeSpan.TicksPerMillisecond); } }\n\n public System.TimeSpan Elapsed\n {\n get\n {\n switch (Units)\n {\n case 0: return System.TimeSpan.Zero;\n default:\n {\n System.TimeSpan taken = System.DateTime.UtcNow - Timer.m_Started;\n\n return taken.Add(new System.TimeSpan(Units * Timer.Frequency.Ticks));\n\n //System.TimeSpan additional = new System.TimeSpan(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, 0, Timer.Frequency.Ticks));\n\n //return taken.Add(additional);\n }\n }\n\n\n\n //////The maximum amount of times the timer can elapse in the given frequency\n ////double maxCount = (taken.TotalMilliseconds / Timer.Frequency.TotalMilliseconds) / ElapsedMilliseconds;\n\n ////if (Units > maxCount)\n ////{\n //// //How many more times the event was fired than needed\n //// double overage = (maxCount - Units);\n\n //// additional = new System.TimeSpan(System.Convert.ToInt64(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));\n\n //// //return taken.Add(new System.TimeSpan((long)Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));\n ////}\n //////return taken.Add(new System.TimeSpan(Units));\n\n\n }\n }\n\n public void Start()\n {\n if (Enabled) return;\n\n Units = 0;\n\n //Create a Timer that will elapse every OneTick //`OneMicrosecond`\n Timer = new Timer(Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);\n\n //Handle the event by incrementing count\n Timer.Tick += Count;\n\n Timer.Start();\n }\n\n public void Stop()\n {\n if (false == Enabled) return;\n\n Timer.Stop();\n\n Timer.Dispose(); \n }\n\n void Count(ref long count) { ++Units; }\n}\n public abstract class Bus : Common.CommonDisposable\n {\n public readonly Timer Clock = new Timer(Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);\n\n public Bus() : base(false) { Clock.Start(); }\n }\n\n public class ClockedBus : Bus\n {\n long FrequencyHz, Maximum, End;\n\n readonly Queue<byte[]> Input = new Queue<byte[]>(), Output = new Queue<byte[]>();\n\n readonly double m_Bias;\n\n public ClockedBus(long frequencyHz, double bias = 1.5)\n {\n m_Bias = bias;\n\n cache = Clock.m_Clock.InstructionsPerClockUpdate / 1000;\n\n SetFrequency(frequencyHz);\n\n Clock.Tick += Clock_Tick;\n\n Clock.Start();\n }\n\n public void SetFrequency(long frequencyHz)\n {\n FrequencyHz = frequencyHz;\n\n //Clock.m_Frequency = new TimeSpan(Clock.m_Clock.InstructionsPerClockUpdate / 1000); \n\n //Maximum = System.TimeSpan.TicksPerSecond / Clock.m_Clock.InstructionsPerClockUpdate;\n\n //Maximum = Clock.m_Clock.InstructionsPerClockUpdate / System.TimeSpan.TicksPerSecond;\n\n Maximum = cache / (cache / FrequencyHz);\n\n Maximum *= System.TimeSpan.TicksPerSecond;\n\n Maximum = (cache / FrequencyHz);\n\n End = Maximum * 2;\n\n Clock.m_Frequency = new TimeSpan(Maximum);\n\n if (cache < frequencyHz * m_Bias) throw new Exception(\"Cannot obtain stable clock\");\n\n Clock.Producer.Clear();\n }\n\n public override void Dispose()\n {\n ShouldDispose = true;\n\n Clock.Tick -= Clock_Tick;\n\n Clock.Stop();\n\n Clock.Dispose();\n\n base.Dispose();\n }\n\n ~ClockedBus() { Dispose(); }\n\n long sample = 0, steps = 0, count = 0, avg = 0, cache = 1;\n\n void Clock_Tick(ref long ticks)\n {\n if (ShouldDispose == false && false == IsDisposed)\n {\n //Console.WriteLine(\"@ops=>\" + Clock.m_Ops + \" @ticks=>\" + Clock.m_Ticks + \" @Lticks=>\" + ticks + \"@=>\" + Clock.m_Clock.Now.TimeOfDay + \"@=>\" + (Clock.m_Clock.Now - Clock.m_Clock.Created));\n\n steps = sample;\n\n sample = ticks;\n\n ++count;\n\n System.ConsoleColor f = System.Console.ForegroundColor;\n\n if (count <= Maximum)\n {\n System.Console.BackgroundColor = ConsoleColor.Yellow;\n\n System.Console.ForegroundColor = ConsoleColor.Green;\n\n Console.WriteLine(\"count=> \" + count + \"@=>\" + Clock.m_Clock.Now.TimeOfDay + \"@=>\" + (Clock.m_Clock.Now - Clock.m_Clock.Created) + \" - \" + DateTime.UtcNow.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n avg = Maximum / count;\n\n if (Clock.m_Clock.InstructionsPerClockUpdate / count > Maximum)\n {\n System.Console.ForegroundColor = ConsoleColor.Red;\n\n Console.WriteLine(\"---- Over InstructionsPerClockUpdate ----\" + FrequencyHz);\n }\n }\n else if (count >= End)\n {\n System.Console.BackgroundColor = ConsoleColor.Black;\n\n System.Console.ForegroundColor = ConsoleColor.Blue;\n\n avg = Maximum / count;\n\n Console.WriteLine(\"avg=> \" + avg + \"@=>\" + FrequencyHz);\n\n count = 0;\n }\n }\n }\n\n //Read, Write at Frequency\n\n }\npublic class VirtualScreen\n {\n TimeSpan RefreshRate; \n bool VerticalSync; \n int Width, Height; \n Common.MemorySegment DisplayMemory, BackBuffer, DisplayBuffer;\n }\n StopWatch internal class StopWatchTests\n {\n public void TestForOneMicrosecond()\n {\n System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>> l = new System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>>();\n\n //Create a Timer that will elapse every `OneMicrosecond`\n for (int i = 0; i <= 250; ++i) using (Media.Concepts.Classes.Stopwatch sw = new Media.Concepts.Classes.Stopwatch())\n {\n var started = System.DateTime.UtcNow;\n\n System.Console.WriteLine(\"Started: \" + started.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n //Define some amount of time\n System.TimeSpan sleepTime = Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneMicrosecond;\n\n System.Diagnostics.Stopwatch testSw = new System.Diagnostics.Stopwatch();\n\n //Start\n testSw.Start();\n\n //Start\n sw.Start();\n\n while (testSw.Elapsed.Ticks < sleepTime.Ticks - (Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick + Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick).Ticks)\n sw.Timer.m_Clock.NanoSleep(0); //System.Threading.Thread.SpinWait(0);\n\n //Sleep the desired amount\n //System.Threading.Thread.Sleep(sleepTime);\n\n //Stop\n testSw.Stop();\n\n //Stop\n sw.Stop();\n\n var finished = System.DateTime.UtcNow;\n\n var taken = finished - started;\n\n var cc = System.Console.ForegroundColor;\n\n System.Console.WriteLine(\"Finished: \" + finished.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n System.Console.WriteLine(\"Sleep Time: \" + sleepTime.ToString());\n\n System.Console.WriteLine(\"Real Taken Total: \" + taken.ToString());\n\n if (taken > sleepTime) \n {\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n System.Console.WriteLine(\"Missed by: \" + (taken - sleepTime));\n }\n else\n {\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n System.Console.WriteLine(\"Still have: \" + (sleepTime - taken));\n }\n\n System.Console.ForegroundColor = cc;\n\n System.Console.WriteLine(\"Real Taken msec Total: \" + taken.TotalMilliseconds.ToString());\n\n System.Console.WriteLine(\"Real Taken sec Total: \" + taken.TotalSeconds.ToString());\n\n System.Console.WriteLine(\"Real Taken μs Total: \" + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(taken).ToString());\n\n System.Console.WriteLine(\"Managed Taken Total: \" + sw.Elapsed.ToString());\n\n System.Console.WriteLine(\"Diagnostic Taken Total: \" + testSw.Elapsed.ToString());\n\n System.Console.WriteLine(\"Diagnostic Elapsed Seconds Total: \" + ((testSw.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency)));\n\n //Write the rough amount of time taken in micro seconds\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedMicroseconds + \"μs\");\n\n //Write the rough amount of time taken in micro seconds\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(testSw.Elapsed) + \"μs\");\n\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedMilliseconds);\n\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + testSw.ElapsedMilliseconds);\n\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedSeconds);\n\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + testSw.Elapsed.TotalSeconds);\n\n if (sw.Elapsed < testSw.Elapsed)\n {\n System.Console.WriteLine(\"Faster than Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));\n }\n else if (sw.Elapsed > testSw.Elapsed)\n {\n System.Console.WriteLine(\"Slower than Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(false, sw.Elapsed, testSw.Elapsed));\n }\n else\n {\n System.Console.WriteLine(\"Equal to Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));\n }\n }\n\n int w = 0, f = 0;\n\n var cc2 = System.Console.ForegroundColor;\n\n foreach (var t in l)\n {\n if (t.Item1)\n {\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n ++w; System.Console.WriteLine(\"Faster than Diagnostic StopWatch by: \" + (t.Item3 - t.Item2));\n }\n else\n {\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n ++f; System.Console.WriteLine(\"Slower than Diagnostic StopWatch by: \" + (t.Item2 - t.Item3));\n }\n }\n\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n System.Console.WriteLine(\"Wins = \" + w);\n\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n System.Console.WriteLine(\"Loss = \" + f);\n\n System.Console.ForegroundColor = cc2;\n }\n }\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
112,440
<p>I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!</p> <pre><code> &lt;SCRIPT language=JavaScript&gt; &lt;!-- function newImage(arg) { var rslt = new Image(); rslt.src = arg; return rslt; } function changeImages(a, b) { a.src = b; } newImage("\/_layouts\/images\/icon1.gif"); newImage("\/_layouts\/images\/icon2.gif"); // --&gt; &lt;/SCRIPT&gt; </code></pre> <p>The error I am getting is when clicking on a drop down context menu on a page, for this line:</p> <pre><code>newImage("\/_layouts\/images\/icon1.gif"); </code></pre> <blockquote> <p>The object doesn't accept this property or method Code: 0</p> </blockquote> <p>I really don't see what could happen... Any tips on what may be happening here?</p>
[ { "answer_id": 112449, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\nfunction newImage(arg) {\n var rslt = new Image();\n rslt.src = arg;\n return rslt;\n}\nfunction changeImages(a, b) {\n a.src = b;\n}\nnewImage(\"/_layouts/images/icon1.gif\");\nnewImage(\"/_layouts/images/icon2.gif\");\n</script>\n" }, { "answer_id": 112452, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n" }, { "answer_id": 112453, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n <script language=JavaScript>\n" }, { "answer_id": 112461, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "newImage(\"/_layouts/images/icon1.gif\");\nnewImage(\"/_layouts/images/icon2.gif\");\n" }, { "answer_id": 112783, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 0, "selected": false, "text": "function changeImages(a, b) {\n a.src = b.src;\n}\n" }, { "answer_id": 902837, "author": "Ballsacian1", "author_id": 100658, "author_profile": "https://Stackoverflow.com/users/100658", "pm_score": 0, "selected": false, "text": "<!-- // --> <script type=\"text/javascript\">\n<![CDATA[\n]]>\n</script>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ]
112,482
<p>For <code>&lt;script&gt;</code> HTML tags, what is the technical difference between <code>lang=Javascript</code> and <code>type=text/javascript</code>?</p> <p>I usually use both, because I've always assumed that older browsers need one or the other.</p>
[ { "answer_id": 112511, "author": "Ali", "author_id": 8689, "author_profile": "https://Stackoverflow.com/users/8689", "pm_score": 2, "selected": false, "text": "<script language=\"\">" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
[ { "answer_id": 112505, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "QGraphicsItem" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
112,503
<p>Given an array of <strong>n</strong> Objects, let's say it is an <strong>array of strings</strong>, and it has the following values:</p> <pre><code>foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd"; </code></pre> <p>What do I have to do to delete/remove all the strings/objects equal to <strong>"a"</strong> in the array?</p>
[ { "answer_id": 112507, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 4, "selected": false, "text": "List Arrays.asList() remove() toArray()" }, { "answer_id": 112542, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 8, "selected": true, "text": "List<String> list = new ArrayList<String>(Arrays.asList(array));\nlist.removeAll(Arrays.asList(\"a\"));\narray = list.toArray(array);\n Arrays.asList Collections.singleton asList Arrays.asList(\"a\", \"b\", \"c\") array = list.toArray(new String[0]);\n private static final String[] EMPTY_STRING_ARRAY = new String[0];\n List<String> list = new ArrayList<>();\nCollections.addAll(list, array);\nlist.removeAll(Arrays.asList(\"a\"));\narray = list.toArray(EMPTY_STRING_ARRAY);\n new array = list.toArray(new String[list.size()]);\n size()" }, { "answer_id": 114671, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 2, "selected": false, "text": "boolean [] deleteItem = new boolean[arr.length];\nint size=0;\nfor(int i=0;i<arr.length;i==){\n if(arr[i].equals(\"a\")){\n deleteItem[i]=true;\n }\n else{\n deleteItem[i]=false;\n size++;\n }\n}\nString[] newArr=new String[size];\nint index=0;\nfor(int i=0;i<arr.length;i++){\n if(!deleteItem[i]){\n newArr[index++]=arr[i];\n }\n}\n" }, { "answer_id": 114720, "author": "AngelOfCake", "author_id": 1732, "author_profile": "https://Stackoverflow.com/users/1732", "pm_score": 0, "selected": false, "text": "String foo[] = {\"a\",\"cc\",\"a\",\"dd\"},\nremove = \"a\";\nboolean gaps[] = new boolean[foo.length];\nint newlength = 0;\n\nfor (int c = 0; c<foo.length; c++)\n{\n if (foo[c].equals(remove))\n {\n gaps[c] = true;\n newlength++;\n }\n else \n gaps[c] = false;\n\n System.out.println(foo[c]);\n}\n\nString newString[] = new String[newlength];\n\nSystem.out.println(\"\");\n\nfor (int c1=0, c2=0; c1<foo.length; c1++)\n{\n if (!gaps[c1])\n {\n newString[c2] = foo[c1];\n System.out.println(newString[c2]);\n c2++;\n }\n}\n" }, { "answer_id": 117345, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 1, "selected": false, "text": "array = list.toArray(array);\n String[] array = new String[] { \"a\", \"bc\" ,\"dc\" ,\"a\", \"ef\" };\n\n System.out.println(Arrays.toString(array));\n\n Set<String> asSet = new HashSet<String>(Arrays.asList(array));\n asSet.remove(\"a\");\n array = asSet.toArray(new String[] {});\n\n System.out.println(Arrays.toString(array));\n [a, bc, dc, a, ef]\n[dc, ef, bc]\n [a, bc, dc, a, ef]\n[bc, dc, ef, null, ef]\n String[] array = new String[] { \"a\", \"bc\" ,\"dc\" ,\"a\", \"ef\" };\n\n System.out.println(Arrays.toString(array));\n\n List<String> list = new ArrayList<String>(Arrays.asList(array));\n list.removeAll(Arrays.asList(\"a\"));\n array = list.toArray(array); \n\n System.out.println(Arrays.toString(array));\n" }, { "answer_id": 119463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "int i, j;\nfor (i = j = 0; j < foo.length; ++j)\n if (!\"a\".equals(foo[j])) foo[i++] = foo[j];\nfoo = Arrays.copyOf(foo, i);\n" }, { "answer_id": 4899240, "author": "bugs_", "author_id": 603314, "author_profile": "https://Stackoverflow.com/users/603314", "pm_score": 3, "selected": false, "text": "org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)\n" }, { "answer_id": 17488208, "author": "DDSports", "author_id": 1489005, "author_profile": "https://Stackoverflow.com/users/1489005", "pm_score": 2, "selected": false, "text": "ArrayList ArrayList List.toArray() List.toArray(new String[] {}) List.toArray(new String[0])" }, { "answer_id": 20301033, "author": "Andre", "author_id": 1755797, "author_profile": "https://Stackoverflow.com/users/1755797", "pm_score": 1, "selected": false, "text": "public class DeleteElementFromArray {\npublic static String foo[] = {\"a\",\"cc\",\"a\",\"dd\"};\npublic static String search = \"a\";\n\n\npublic static void main(String[] args) {\n long stop = 0;\n long time = 0;\n long start = 0;\n System.out.println(\"Searched value in Array is: \"+search);\n System.out.println(\"foo length before is: \"+foo.length);\n for(int i=0;i<foo.length;i++){ System.out.println(\"foo[\"+i+\"] = \"+foo[i]);}\n System.out.println(\"==============================================================\");\n start = System.nanoTime();\n foo = removeElementfromArray(search, foo);\n stop = System.nanoTime();\n time = stop - start;\n System.out.println(\"Equal search took in nano seconds = \"+time);\n System.out.println(\"==========================================================\");\n for(int i=0;i<foo.length;i++){ System.out.println(\"foo[\"+i+\"] = \"+foo[i]);}\n}\npublic static String[] removeElementfromArray( String toSearchfor, String arr[] ){\n int i = 0;\n int t = 0;\n String tmp1[] = new String[arr.length]; \n for(;i<arr.length;i++){\n if(arr[i] == toSearchfor){ \n i++;\n }\n tmp1[t] = arr[i];\n t++;\n } \n String tmp2[] = new String[arr.length-t]; \n System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);\n arr = tmp2; tmp1 = null; tmp2 = null;\n return arr;\n}\n" }, { "answer_id": 21368866, "author": "Ali", "author_id": 2671085, "author_profile": "https://Stackoverflow.com/users/2671085", "pm_score": 3, "selected": false, "text": "ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));\na.remove(i);\nstrings = new String[a.size()];\na.toArray(strings);\n" }, { "answer_id": 23188826, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 5, "selected": false, "text": "String[] filteredArray = Arrays.stream(array)\n .filter(e -> !e.equals(foo)).toArray(String[]::new);\n" }, { "answer_id": 30151240, "author": "Alex Salauyou", "author_id": 3459206, "author_profile": "https://Stackoverflow.com/users/3459206", "pm_score": 3, "selected": false, "text": "List a int... r public int removeItems(Object[] a, int... r) {\n int shift = 0; \n for (int i = 0; i < a.length; i++) { \n if (shift < r.length && i == r[shift]) // i-th item needs to be removed\n shift++; // increment `shift`\n else \n a[i - shift] = a[i]; // move i-th item `shift` positions left\n }\n for (int i = a.length - shift; i < a.length; i++)\n a[i] = null; // replace remaining items by nulls\n\n return a.length - shift; // return new \"length\"\n} \n String[] a = {\"0\", \"1\", \"2\", \"3\", \"4\"};\nremoveItems(a, 0, 3, 4); // remove 0-th, 3-rd and 4-th items\nSystem.out.println(Arrays.asList(a)); // [1, 2, null, null, null]\n removeItems()" }, { "answer_id": 37767505, "author": "PauLy", "author_id": 1681312, "author_profile": "https://Stackoverflow.com/users/1681312", "pm_score": 0, "selected": false, "text": "if(i == 0){\n System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );\n }else{\n System.arraycopy(edges, 0, copyEdge, 0, i );\n System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );\n }\n" }, { "answer_id": 53383108, "author": "Ebin Joy", "author_id": 5845024, "author_profile": "https://Stackoverflow.com/users/5845024", "pm_score": 2, "selected": false, "text": " int[] array = {5,6,51,4,3,2};\n for(int i = 2; i < array.length -1; i++){\n array[i] = array[i + 1];\n }\n" }, { "answer_id": 56652685, "author": "Orlando Reyes", "author_id": 6234849, "author_profile": "https://Stackoverflow.com/users/6234849", "pm_score": -1, "selected": false, "text": "class clearname{\ndef parts\ndef tv\npublic def str = ''\nString name\nclearname(String name){\n this.name = name\n this.parts = this.name.split(\" \")\n this.tv = this.parts.size()\n}\npublic String cleared(){\n\n int i\n int k\n int j=0 \n for(i=0;i<tv;i++){\n for(k=0;k<tv;k++){\n if(this.parts[k] == this.parts[i] && k!=i){\n this.parts[k] = '';\n j++\n }\n }\n }\n def str = ''\n for(i=0;i<tv;i++){\n if(this.parts[i]!='')\n\n this.str += this.parts[i].trim()+' '\n } \n return this.str \n}}\n\n\n\nreturn new clearname(name).cleared()\n" }, { "answer_id": 57382985, "author": "milevyo", "author_id": 4487286, "author_profile": "https://Stackoverflow.com/users/4487286", "pm_score": 0, "selected": false, "text": "foo.drop(n) indexOf Integer indexOf(String[] arr, String value){\n for(Integer i = 0 ; i < arr.length; i++ )\n if(arr[i] == value)\n return i; // return the index of the element\n return -1 // otherwise -1\n}\n\nwhile (true) {\n Integer i;\n i = indexOf(foo,\"a\")\n if (i == -1) break;\n foo[i] = foo[0]; // preserve foo[0]\n foo.drop(1);\n}\n" }, { "answer_id": 66347083, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 0, "selected": false, "text": "boolean[] done = {false};\nString[] arr = Arrays.stream( foo ).filter( e ->\n ! (! done[0] && Objects.equals( e, item ) && (done[0] = true) ))\n .toArray(String[]::new);\n null" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358/" ]
112,517
<p>I have the following enum:</p> <pre><code>public enum Status implements StringEnum{ ONLINE("on"),OFFLINE("off"); private String status = null; private Status(String status) { this.status = status; } public String toString() { return this.status; } public static Status find(String value) { for(Status status : Status.values()) { if(status.toString().equals(value)) { return status; } } throw new IllegalArgumentException("Unknown value: " + value ); } } </code></pre> <p>Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?</p> <p>Thanks.</p>
[ { "answer_id": 112554, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "toString java.lang.Object enum" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
112,523
<p>Are there any libraries (3rd party or built-in) in <code>PHP</code> to calculate text diffs?</p>
[ { "answer_id": 112574, "author": "Mathew Byrne", "author_id": 10942, "author_profile": "https://Stackoverflow.com/users/10942", "pm_score": 2, "selected": false, "text": "$diff = `diff $file1 $file2`;\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <hr> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
[ { "answer_id": 112540, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 1, "selected": false, "text": "var words = from word in dictionary\n where word.key.StartsWith(\"bla-bla-bla\");\n select word;\n" }, { "answer_id": 112556, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 2, "selected": false, "text": "def main(script, name):\n for word in open(\"/usr/share/dict/words\"):\n if word.startswith(name):\n print word,\n\nif __name__ == \"__main__\":\n import sys\n main(*sys.argv)\n" }, { "answer_id": 112563, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 4, "selected": true, "text": "#!/bin/bash\necho -n \"Enter a word: \"\nread input\ngrep \"^$input\" /usr/share/dict/words\n" }, { "answer_id": 112587, "author": "user19745", "author_id": 19745, "author_profile": "https://Stackoverflow.com/users/19745", "pm_score": 3, "selected": false, "text": "egrep `read input && echo ^$input` /usr/share/dict/words\n my_input = raw_input(\"Enter beginning of word: \")\nmy_words = open(\"/usr/share/dict/words\").readlines()\nmy_found_words = [x for x in my_words if x[0:len(my_input)] == my_input]\n" }, { "answer_id": 112598, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "from itertools import takewhile, islice\nimport bisect\n\ndef prefixes(words, pfx):\n return list(\n takewhile(lambda x: x.startswith(pfx), \n islice(words, \n bisect.bisect_right(words, pfx), \n len(words)))\n" }, { "answer_id": 114002, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 0, "selected": false, "text": "\"SELECT word FROM dict WHERE word LIKE \"user_entry%\"\n" }, { "answer_id": 306465, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 0, "selected": false, "text": "import bisect\nwords = sorted(map(str.strip, open('/usr/share/dict/words')))\ndef lookup(prefix):\n return words[bisect.bisect_left(words, prefix):bisect.bisect_right(words, prefix+'~')]\n\n>>> lookup('abdicat')\n['abdicate', 'abdication', 'abdicative', 'abdicator']\n" }, { "answer_id": 308443, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "# set your list of words, whatever the source\nwords_list = ('cat', 'dog', 'banana')\n# get the word from the user inpuit\nuser_word = raw_input(\"Enter a word:\\n\")\n# create an generator, so your output is flexible and store almost nothing in memory\nword_generator = (word for word in words_list if word.startswith(user_word))\n\n# now you in, you can make anything you want with it \n# here we just list it :\n\nfor word in word_generator :\n print word\n" }, { "answer_id": 53864726, "author": "Mattias", "author_id": 8265788, "author_profile": "https://Stackoverflow.com/users/8265788", "pm_score": 0, "selected": false, "text": "df = pd.read_csv('dictionary.csv')\nmatching_words = df[0].loc[df[0].str.startswith(user_entry)] \n" }, { "answer_id": 53868147, "author": "Nitwit", "author_id": 7958330, "author_profile": "https://Stackoverflow.com/users/7958330", "pm_score": 2, "selected": false, "text": "str.startswith() dictionary = ['apple', 'abdicate', 'orange', 'abdomen', 'abduct', 'banana']\nuser_input = input('Enter something: ')\nfor word in dictionary:\n if word.startswith(user_input):\n print(word)\n Enter something: abd\nabdicate\nabdomen\nabduct\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
112,551
<p>I have a table that contains tasks and I want to give these an explicit ordering based on the priority of the task. The only way I can think to do this is via an <strong>unique</strong> int column that indexes where the task is in term of the priority (i.e. 1 is top 1000 is low).</p> <p>The problem is that say I wanted to update task and set its priority to a lower value , I would have to update all the other rows between its current value and its new value.</p> <p><strong>Can anyone suggest a better way of implementing this?</strong></p>
[ { "answer_id": 112576, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 4, "selected": true, "text": "newPri = task1Pri + (task2Pri - task1Pri)/2" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
112,564
<p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
[ { "answer_id": 112659, "author": "alif", "author_id": 12650, "author_profile": "https://Stackoverflow.com/users/12650", "pm_score": 2, "selected": false, "text": ">>> import genshi.output\n>>> genshi.output.DocType('html')\n('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd')\n [1] genshi.builder.__doc__\n" }, { "answer_id": 112860, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "genshi.builder.tag genshi.builder.tag genshi.builder builder.tag from itertools import chain\nfrom genshi.core import DOCTYPE, Stream\nfrom genshi.output import DocType\nfrom genshi.builder import tag as t\n\n# Build the page using `genshi.builder.tag`\npage = t.html (t.head (t.title (\"Hello world!\")), t.body (t.div (\"Body text\")))\n\n# Convert the page element into a stream\nstream = page.generate ()\n\n# Chain the page stream with a stream containing only an HTML4 doctype declaration\nstream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))\n\n# Convert the stream to text using the \"html\" renderer (could also be xml, xhtml, text, etc)\ntext = stream.render ('html')\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
112,582
<p>I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached: </p> <pre><code>#include&lt;stdio.h&gt; #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); while(arr[idx-1] != -1 &amp;&amp; idx &lt; MAX){ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); idx++; } /* Approach #2 */ do{ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); idx++; }while(arr[idx-1] != -1 &amp;&amp; idx &lt; MAX); // Main func continues here. } </code></pre> <p>Any advice would be much appreciated!</p> <p><strong>Update:</strong></p> <p>Now it works! thanks MUCH <strong>all</strong> of you guys for such instant responses. This is definitely a great community, it's helping me a lot.</p>
[ { "answer_id": 112586, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "arr[idx] <= MAX\n idx <= MAX\n" }, { "answer_id": 112594, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 1, "selected": false, "text": "int arr[MAX];\nfor ( .... && idx < MAX )\n" }, { "answer_id": 112595, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 2, "selected": true, "text": "arr[idx] <= MAX\n idx < MAX\n arr[idx-1] != -1\n" }, { "answer_id": 112599, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "arr[idx] <= MAX\n idx <= MAX\n } while ((arr[idx-1] != -1) && (idx-1 <= MAX));\n" }, { "answer_id": 112615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz\n printf(\"Enter elements, -1 to finish:\\n\");\n scanf(\"%d\", &arr[idx]);\n idx++; \n}\n" }, { "answer_id": 112626, "author": "RomanM", "author_id": 14587, "author_profile": "https://Stackoverflow.com/users/14587", "pm_score": 1, "selected": false, "text": "int cnt = MAX; // how many elements in the array, in this case MAX\nint * p = &arr[0]; // p is a pointer to an integer and is initialize to the address of the first\n // element of the array. So now *p is the same as arr[0] and p is same as &arr[0]\n\n// iterate over all elements. stop when cnt == 0\nwhile (cnt) {\n\n // do somthing\n scanf(\"%d\", *p); // remember that *p is same as arr[some index]\n if (*p == -1) // inspect element to see what user entered\n break;\n\n cnt --; // loop counter\n p++; // incrementing p to point to next element in the array\n}\n" }, { "answer_id": 112638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "scanf(\"%d\", &arr[idx]);\nif(arr[idx] == -1)\n break;\n" }, { "answer_id": 113017, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 2, "selected": false, "text": "/* Approach #3*/\nint i;\nint value;\n\nfor (i = 0; i < MAX; ++i)\n{\n printf(\"Enter elements, -1 to finish:\\n\");\n scanf(\"%d\", &value);\n if (value == -1) break;\n arr[i] = value;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
112,601
<p>I want to select the topmost element in a document that has a given namespace (prefix).</p> <p>More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element. </p>
[ { "answer_id": 112602, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 2, "selected": false, "text": "/html:html/html:body/node()|/foo:*\n" }, { "answer_id": 113095, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 4, "selected": true, "text": "//*[in-scope-prefixes(.)='html']\n //*[namespace-uri()='http://www.w3c.org/1999/xhtml']\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
112,603
<p>I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.</p> <p>This frame is opened, and then closed.</p> <p>Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.</p> <p>What does this mean? Why is it hanging on to each instance of the frame?</p>
[ { "answer_id": 112720, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "java.awt.Window dispose()" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18445/" ]
112,612
<p>I am hosting <a href="http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference" rel="nofollow noreferrer">SpiderMonkey</a> in a current project and would like to have template functions generate some of the simple property get/set methods, eg:</p> <pre><code>template &lt;typename TClassImpl, int32 TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToInt32(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Used:</p> <pre><code>::JSPropertySpec Vec2::s_JsProps[] = { {"x", 1, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::x&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::x&gt;}, {"y", 2, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::y&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::y&gt;}, {0} }; </code></pre> <p>This works fine, however, if I add another member type:</p> <pre><code>template &lt;typename TClassImpl, JSObject* TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToObject(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Then Visual C++ 9 attempts to use the JSObject* wrapper for int32 members!</p> <pre><code>1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const ' 1&gt; Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* ' 1&gt; d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp' 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp' 1&gt; None of the functions with this name in scope match the target type </code></pre> <p>Surprisingly, parening JSObject* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject* PObject; ..., PObject TClassImpl::<em>mem>", void</em>, struct Undefined*, and double. Since the function usage is fully instantiated: "&amp;ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.</p> <p>Vec2 is just:</p> <pre><code>class Vec2 { public: int32 x, y; Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv); static ::JSClass s_JsClass; static ::JSPropertySpec s_JsProps[]; }; </code></pre> <p>JSPropertySpec is described in JSAPI link in OP, taken from header:</p> <pre><code>typedef JSBool (* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id, jsval *vp); ... struct JSPropertySpec { const char *name; int8 tinyid; uint8 flags; JSPropertyOp getter; JSPropertyOp setter; }; </code></pre>
[ { "answer_id": 112737, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": true, "text": "struct X\n{\n int i;\n void* p;\n};\n\ntemplate<int X::*P>\nvoid foo(X* t)\n{\n t->*P = 0;\n}\n\ntemplate<void* X::*P>\nvoid foo(X* t)\n{\n t->*P = 0;\n}\n\nint main()\n{\n X x;\n foo<&X::i>(&x);\n foo<&X::p>(&x);\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20135/" ]
112,613
<p>running <code>git instaweb</code> in my repository opens a page that says "403 Forbidden - No projects found". What am I missing?</p>
[ { "answer_id": 112753, "author": "jes5199", "author_id": 13195, "author_profile": "https://Stackoverflow.com/users/13195", "pm_score": 5, "selected": true, "text": "$projectroot instaweb $projectroot /etc/gitweb.conf" }, { "answer_id": 7829893, "author": "Kylo", "author_id": 1004272, "author_profile": "https://Stackoverflow.com/users/1004272", "pm_score": 0, "selected": false, "text": "vi .git/gitweb/gitweb.cgi # set DocumentRoot to <root>/.git/gitweb.cgi\nGITWEB_CONFIG=.git/gitweb lighttpd -f .git/gitweb/httpd.conf\n" }, { "answer_id": 15222474, "author": "Feng Wang", "author_id": 1475287, "author_profile": "https://Stackoverflow.com/users/1475287", "pm_score": 0, "selected": false, "text": "Options All ExecCGI FollowSymLinks Includes Indexes\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13195/" ]
112,625
<p>So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the other was simply a personal preference. Over time, I'm come to find that these two are not the same thing, even in a default implementation (see <a href="http://web.archive.org/web/20081205081158/http://blogs.msdn.com:80/jmstall/archive/2005/03/06/386064.aspx" rel="nofollow noreferrer">this</a> and <a href="http://web.archive.org/web/20090710210823/http://blogs.msdn.com:80/jmstall/archive/2005/03/12/394645.aspx" rel="nofollow noreferrer">this</a>). To further confuse the matter, each can be overridden/overloaded separately to have completely different meanings. </p> <p>Is this a good thing, what are the differences, and when/why should you use one over the other?</p>
[ { "answer_id": 112771, "author": "molasses", "author_id": 11293, "author_profile": "https://Stackoverflow.com/users/11293", "pm_score": 5, "selected": false, "text": "string x = \"hello\";\nstring y = String.Copy(x);\nstring z = \"hello\";\n x y (object)x == (object)y // false\nx.ReferenceEquals(y) // false\nx.ReferenceEquals(z) // true (because x and z are both constants they\n // will point to the same location in memory)\n x y x == y // true\nx == z // true\nx.Equals(y) // true\ny == \"hello\" // true\n == y == \"hello\" // false (y is not the same object as \"hello\")\n .equals() y.equals(\"hello\") // true\n" }, { "answer_id": 23553700, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 3, "selected": false, "text": "== Equals ReferenceEquals == Object Object.== ReferenceEquals == Equals ReferenceEquals == Equals(a, b) ReferenceEquals(a, b) == == == == == Equals" }, { "answer_id": 30297553, "author": "Sonu Rajpoot", "author_id": 3600880, "author_profile": "https://Stackoverflow.com/users/3600880", "pm_score": -1, "selected": false, "text": " static void Main()\n {\n string x = \" hello\";\n string y = \" hello\";\n string z = string.Copy(x);\n if (x == y)\n {\n Console.WriteLine(\"== Operator\");\n }\n if(x.Equals(y))\n {\n Console.WriteLine(\"Equals() Function Call\");\n }\n if (x == z)\n {\n Console.WriteLine(\"== Operator while coping a string to another.\");\n }\n if (x.Equals(y))\n {\n Console.WriteLine(\"Equals() Function Call while coping a string to another.\");\n }\n }\n == Operator\n Equals() Function Call\n == Operator while coping a string to another.\n Equals() Function Call while coping a string to another.\n" }, { "answer_id": 32106633, "author": "ps2goat", "author_id": 2084315, "author_profile": "https://Stackoverflow.com/users/2084315", "pm_score": 3, "selected": false, "text": " Object a = null;\n Object b = new Object();\n\n // Ex 1\n Console.WriteLine(a == b);\n // Ex 2\n Console.WriteLine(b == a);\n\n // Ex 3 \n Console.WriteLine(b.Equals(a));\n // Ex 4\n Console.WriteLine(a.Equals(b));\n == b a null == .Equals()" }, { "answer_id": 54892972, "author": "Andrew Rondeau", "author_id": 1711103, "author_profile": "https://Stackoverflow.com/users/1711103", "pm_score": 1, "selected": false, "text": "var aaa1 = \"aaa\";\nvar aaa2 = $\"{'a'}{'a'}{'a'}\";\nvar bbb = \"bbb\";\n\n// False because aaa1 and aaa2 are completely different objects with different locations in RAM\nConsole.WriteLine($\"Object.ReferenceEquals(aaa1, aaa2): {Object.ReferenceEquals(aaa1, aaa2)}\");\n\n// True because aaa1 and aaa2 are completely interchangable\nConsole.WriteLine($\"aaa1 == aaa2: {aaa1 == aaa2}\"); // True\nConsole.WriteLine($\"aaa1.Equals(aaa2): {aaa1.Equals(aaa2)}\"); // True\nConsole.WriteLine($\"aaa1 == bbb: {aaa1 == bbb}\"); // False\nConsole.WriteLine($\"aaa1.Equals(bbb): {aaa1.Equals(bbb)}\"); // False\n\n// Won't compile\n// This is why string can override ==, you can not modify a string object once it is allocated\n//aaa1[0] = 'd';\n\n// aaaUpdated and aaa1 point to the same exact object in RAM\nvar aaaUpdated = aaa1;\nConsole.WriteLine($\"Object.ReferenceEquals(aaa1, aaaUpdated): {Object.ReferenceEquals(aaa1, aaaUpdated)}\"); // True\n\n// aaaUpdated is a new string, aaa1 is unmodified\naaaUpdated += 'c';\nConsole.WriteLine($\"Object.ReferenceEquals(aaa1, aaaUpdated): {Object.ReferenceEquals(aaa1, aaaUpdated)}\"); // False\n\nvar aaaBuilder1 = new StringBuilder(\"aaa\");\nvar aaaBuilder2 = new StringBuilder(\"aaa\");\n\n// False, because both string builders are different objects\nConsole.WriteLine($\"Object.ReferenceEquals(aaaBuider1, aaaBuider2): {Object.ReferenceEquals(aaa1, aaa2)}\");\n\n// Even though both string builders have the same contents, they are not interchangable\n// Thus, == is false\nConsole.WriteLine($\"aaaBuider1 == aaaBuilder2: {aaaBuilder1 == aaaBuilder2}\");\n\n// But, because they both have \"aaa\" at this exact moment in time, Equals returns true\nConsole.WriteLine($\"aaaBuider1.Equals(aaaBuilder2): {aaaBuilder1.Equals(aaaBuilder2)}\");\n\n// Modifying the contents of the string builders changes the strings, and thus\n// Equals returns false\naaaBuilder1.Append('e');\naaaBuilder2.Append('f');\nConsole.WriteLine($\"aaaBuider1.Equals(aaaBuilder2): {aaaBuilder1.Equals(aaaBuilder2)}\");\n // Hold the current user object in a variable\nvar originalUser = database.GetUser(123);\n\n// Update the user’s name\ndatabase.UpdateUserName(123, user.Name + \"son\");\n\nvar updatedUser = database.GetUser(123);\n\nConsole.WriteLine(originalUser.Id == updatedUser.Id); // True, both objects refer to the same entity\nConsole.WriteLine(Object.Equals(originalUser, updatedUser); // False, the name property is different\n var originalUser = new User() { Name = \"George\" };\nvar updatedUser = new User() { Name = \"George\" };\n\nConsole.WriteLine(Object.Equals(originalUser, updatedUser); // True, the objects have the same contents\nConsole.WriteLine(originalUser == updatedUser); // User doesn’t define ==, False\n\nupdatedUser.Name = \"Paul\";\n\nConsole.WriteLine(Object.Equals(originalUser, updatedUser); // False, the name property is different\n var originalUser = new User() { Name = \"George\" };\nvar updatedUser = new User() { Name = \"George\" };\nConsole.WriteLine(Object.Equals(originalUser, updatedUser); // True, the objects have the same contents\n\n// Does this change updatedUser? We don’t know\nDoSomethingWith(updatedUser);\n\n// Are the following equivalent?\n// SomeMethod(originalUser, updatedUser);\n// SomeMethod(updatedUser, originalUser);\n var originalImmutableUser = new ImmutableUser(name: \"George\");\nvar secondImmutableUser = new ImmutableUser(name: \"George\");\n\nConsole.WriteLine(Object.Equals(originalImmutableUser, secondImmutableUser); // True, the objects have the same contents\nConsole.WriteLine(originalImmutableUser == secondImmutableUser); // ImmutableUser defines ==, True\n\n// Won’t compile because ImmutableUser has no setters\nsecondImmutableUser.Name = \"Paul\";\n\n// But this does compile\nvar updatedImmutableUser = secondImmutableUser.SetName(\"Paul\"); // Returns a copy of secondImmutableUser with Name changed to Paul.\n\nConsole.WriteLine(object.ReferenceEquals(updatedImmutableUser, secondImmutableUser)); // False, because updatedImmutableUser is a different object in a different location in RAM\n\n// These two calls are equivalent because the internal state of an ImmutableUser can never change\nDoSomethingWith(originalImmutableUser, secondImmutableUser);\nDoSomethingWith(secondImmutableUser, originalImmutableUser);\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
112,643
<p>I know how to create a <code>SEL</code> at compile time using <code>@selector(MyMethodName:)</code> but what I want to do is create a selector dynamically from an <code>NSString</code>. Is this even possible?</p> <p>What I can do:</p> <pre><code>SEL selector = @selector(doWork:); [myobj respondsToSelector:selector]; </code></pre> <p>What I want to do: (pseudo code, this obviously doesn't work)</p> <pre><code>SEL selector = selectorFromString(@"doWork"); [myobj respondsToSelector:selector]; </code></pre> <p>I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time <code>@selector(myTarget:)</code> syntax.</p>
[ { "answer_id": 112680, "author": "Josh Gagnon", "author_id": 7944, "author_profile": "https://Stackoverflow.com/users/7944", "pm_score": 5, "selected": false, "text": "setWidthHeight = NSSelectorFromString(aBuffer);" }, { "answer_id": 21494661, "author": "Alex Gray", "author_id": 547214, "author_profile": "https://Stackoverflow.com/users/547214", "pm_score": 4, "selected": false, "text": "[self theMethod:(id)methodArg]; void (^impBlock)(id,id) = ^(id _self, id methodArg) { \n [_self doSomethingWith:methodArg]; \n};\n IMP SEL void(*impFunct)(id, SEL, id) = (void*) imp_implementationWithBlock(impBlock);\n \"v@:@\" class_addMethod(self.class, @selector(theMethod:), (IMP)impFunct, \"v@:@\");\n" }, { "answer_id": 22032339, "author": "Krypton", "author_id": 950983, "author_profile": "https://Stackoverflow.com/users/950983", "pm_score": 3, "selected": false, "text": "sel_registerName SEL selector = sel_registerName(\"doWork:\");\n[myobj respondsToSelector:selector];\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18590/" ]
112,664
<p>I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:</p> <pre><code>F:\Cygnus&gt;sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <hr> <p>a test</p> <p>(1 rows affected)</p> <pre><code>F:\Cygnus&gt; </code></pre> <p>====================================================</p> <p>From Cygwin:</p> <pre><code>$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <blockquote> <p>HResult 0x35, Level 16, State 1<br> Named Pipes Provider: Could not open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired.</p> </blockquote>
[ { "answer_id": 118071, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 4, "selected": true, "text": "sqlcmd -Q \"select 'a test'\" -S .\\\\SQLEXPRESS\n" }, { "answer_id": 29771028, "author": "Krzysztof Kuźnik", "author_id": 4814638, "author_profile": "https://Stackoverflow.com/users/4814638", "pm_score": 0, "selected": false, "text": "sqlcmd -Q \"select * from nice.dbo.TableName ac ORDER BY 1 DESC\" -S server_name\\\\db_name\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8670/" ]
112,695
<p>One of the many things that's been lacking from my <a href="https://stackoverflow.com/questions/61553/track-your-reputation">scraper service</a> that I set up last week are pretty URLs. Right now the user parameter is being passed into the script with <em>?u=</em>, which is a symptom of a lazy hack (which the script admittedly is). However, I've been thinking about redoing it and I'd like to get some feedback on the options available. Right now there are two pages, update and chart, that provide information to the user. Here are the two possibilities that I came up with. "1234" is the user ID number. For technical reasons the user name unfortunately cannot be used:</p> <ul> <li>http://&lt; tld >/update/1234</li> <li>http://&lt; tld >/chart/1234</li> </ul> <p>or</p> <ul> <li>http://&lt; tld >/1234/update</li> <li>http://&lt; tld >/1234/chart</li> </ul> <p>Option #1, conceptually, is calling update with the user ID. Option #2 is providing a verb to operate on a user ID.</p> <p>From a consistency standpoint, which makes more sense?</p> <hr> <p>Another option mentioned is</p> <ul> <li>http://&lt; tld >/user/1234/update</li> <li>http://&lt; tld >/user/1234/chart</li> </ul> <p>This provides room for pages not relating to a specific user. i.e.</p> <ul> <li>http://&lt; tld >/stats</li> </ul>
[ { "answer_id": 124021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " http://< tld >/update/1234\n http://< tld >/chart/1234\n Disallow /update/\n Disallow /chart/\n" }, { "answer_id": 136534, "author": "Andrew Ingram", "author_id": 15687, "author_profile": "https://Stackoverflow.com/users/15687", "pm_score": 0, "selected": false, "text": "http://< tld >/users/ <--- user list\nhttp://< tld >/users/1234/ <--- user profile, use overloaded POST on this to update.\nhttp://< tld >/users/1234/chart/ <--- user chart\n http://< tld >/user/ <--- user profile, use overloaded POST on this to update.\nhttp://< tld >/user/chart/ <--- user chart\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/" rel="noreferrer">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
[ { "answer_id": 112708, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": -1, "selected": false, "text": "python setup.py py2exe" }, { "answer_id": 112713, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": "--onefile" }, { "answer_id": 112716, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": -1, "selected": false, "text": "from distutils.core import setup\nimport py2exe\n\nsetup(console=['post-review'])\n" }, { "answer_id": 113014, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 7, "selected": false, "text": "bundle_files compressed from distutils.core import setup\nimport py2exe, sys, os\n\nsys.argv.append('py2exe')\n\nsetup(\n options = {'py2exe': {'bundle_files': 1, 'compressed': True}},\n windows = [{'script': \"single.py\"}],\n zipfile = None,\n)\n" }, { "answer_id": 333483, "author": "Philippe F", "author_id": 13618, "author_profile": "https://Stackoverflow.com/users/13618", "pm_score": 4, "selected": false, "text": "py2exe" }, { "answer_id": 6824876, "author": "Nor", "author_id": 862621, "author_profile": "https://Stackoverflow.com/users/862621", "pm_score": 3, "selected": false, "text": "exec \"setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\\\n 'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\\\n options={'py2exe': py2exe_options},\\\n zipfile = None )\" % (bitmap_string[:-1])\n from distutils.core import setup\nimport py2exe #@UnusedImport\nimport os\n\n#delete the old build drive\nos.system(\"rmdir /s /q dist\")\n\n#setup my option for single file output\npy2exe_options = dict( ascii=True, # Exclude encodings\n excludes=['_ssl', # Exclude _ssl\n 'pyreadline', 'difflib', 'doctest', 'locale',\n 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'], # Exclude standard library\n dll_excludes=['msvcr71.dll', 'w9xpopen.exe',\n 'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',\n 'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',\n 'API-MS-Win-Security-Base-L1-1-0.dll',\n 'KERNELBASE.dll',\n 'POWRPROF.dll',\n ],\n #compressed=None, # Compress library.zip\n bundle_files = 1,\n optimize = 2 \n )\n\n#storage for the images\nbitmap_string = '' \nresource_string = ''\nindex = 0\n\nprint \"compile image list\" \n\nfor image_name in os.listdir('images/'):\n if image_name.endswith('.jpg'):\n bitmap_string += \"( \" + str(index+1) + \",\" + \"'\" + 'images/' + image_name + \"'),\"\n resource_string += image_name + \" \"\n index += 1\n\nprint \"Starting build\\n\"\n\nexec \"setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\\\n 'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\\\n options={'py2exe': py2exe_options},\\\n zipfile = None )\" % (bitmap_string[:-1])\n\nprint \"Removing Trash\"\nos.system(\"rmdir /s /q build\")\nos.system(\"del /q *.pyc\")\nprint \"Build Complete\"\n def init(self):\n frame = self.env.frame\n use_resource_builtin = True\n if os.path.isdir(SPRITES_FOLDER):\n use_resource_builtin = False\n else:\n image_list = LoadResource(0, u'INDEX', 1).split(' ')\n\n for (model, file) in SPRITES.items():\n texture = POINTER(IDirect3DTexture9)()\n if use_resource_builtin: \n data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc) \n d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device, #Pointer to an IDirect3DDevice9 interface\n data, #Pointer to the file in memory\n len(data), #Size of the file in memory\n byref(texture)) #ppTexture\n else:\n d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable\n SPRITES_FOLDER + file,\n byref(texture)) \n self.model_sprites[model] = texture\n #else:\n # raise Exception(\"'sprites' folder is not present!\")\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
112,707
<p>Whenever I indent <code>HTML</code> in <code>PHP</code> mode, <code>emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)</code> pops up a frame and tells me to get <code>MUMODE</code> or <code>somesuch</code> extra add-on. I installed <code>PHP</code> Mode without a big hassle, but I don't know how to get this multi-mode rolling.<br> <hr> I'd like to know 2 things</p> <pre><code>How to install and configure multi-mode How to disable pop-ups in Emacs </code></pre>
[ { "answer_id": 112906, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": true, "text": "M-x nxhtml-mumamo\n" }, { "answer_id": 1661914, "author": "RichieHH", "author_id": 37370, "author_profile": "https://Stackoverflow.com/users/37370", "pm_score": 0, "selected": false, "text": "(require 'html-php)\n(add-to-list 'auto-mode-alist '(\"\\\\.php\\\\'\" . html-php-mode))\n" }, { "answer_id": 12271624, "author": "fxbois", "author_id": 894017, "author_profile": "https://Stackoverflow.com/users/894017", "pm_score": 1, "selected": false, "text": ".emacs (require 'web-mode)\n(add-to-list 'auto-mode-alist '(\"\\\\.phtml$\" . web-mode))\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
112,721
<p>I've got the following situation</p> <ul> <li>A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality</li> <li>Lot of nice javascript written using jQuery (for a separate application)</li> </ul> <p>I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc). </p> <p>What is my easiest option to bring the two together? Thanks!</p>
[ { "answer_id": 112746, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 5, "selected": true, "text": "jQuery.noConflict();\n jQuery('div.foo').doSomething()\n (function($) {\n...your code here...\n})(jQuery);\n" }, { "answer_id": 112811, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 2, "selected": false, "text": "jQuery.noConflict() jQuery.noConflict();\n\njQuery('div').hide();\n var $j = jQuery.noConflict();\n\n$j('div').hide();\n $ jQuery.noConflict();\n\n // Put all your code in your document ready area\n jQuery(document).ready(function($){\n // Do jQuery stuff using $\n $(\"div\").hide();\n });\n// Use Prototype with $(...), etc.\n$('someid').hide();\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
112,730
<p>I have a <code>n...n</code> structure for two tables, <strong><code>makes</code></strong> and <strong><code>models</code></strong>. So far no problem.</p> <p>In a third table (<strong><code>products</code></strong>) like:</p> <pre><code>id make_id model_id ... </code></pre> <p>My problem is creating a view for products of one specifi <strong><code>make</code></strong> inside my <code>ProductsController</code> containing just that's make models:</p> <p>I thought this could work:</p> <pre><code>var $uses = array('Make', 'Model'); $this-&gt;Make-&gt;id = 5; // My Make $this-&gt;Make-&gt;find(); // Returns only the make I want with it's Models (HABTM) $this-&gt;Model-&gt;find('list'); // Returns ALL models $this-&gt;Make-&gt;Model-&gt;find('list'); // Returns ALL models </code></pre> <p>So, If I want to use the <code>list</code> to pass to my view to create radio buttons I will have to do a <code>foreach()</code> in my <strong><code>make</code></strong> array to find all models titles and create a new array and send to the view via <code>$this-&gt;set()</code>.</p> <pre><code>$makeArray = $this-&gt;Make-&gt;find(); foreach ($makeArray['Model'] as $model) { $modelList[] = $model['title']; } $this-&gt;set('models', $models) </code></pre> <p>Is there any easier way to get that list without stressing the <strong><code>make</code></strong> Array. It will be a commom task to develops such scenarios in my application(s).</p> <p>Thanks in advance for any hint!</p>
[ { "answer_id": 112868, "author": "JayTee", "author_id": 20153, "author_profile": "https://Stackoverflow.com/users/20153", "pm_score": 1, "selected": false, "text": "SELECT * FROM makes, models, products WHERE make_id = 5\n SELECT models.title FROM models \nINNER JOIN products \n ON products.model_id = models.model_id \n AND products.make_id = 5\n" }, { "answer_id": 113678, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 0, "selected": false, "text": "$this->Product->find('all', array('conditions' => array('make_id' => 5)));\n" }, { "answer_id": 160990, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 1, "selected": false, "text": "$this->ModelB->find('first', array('conditions' => array('field' => $condition)));\narray(\n ['ModelB'] => array( ... ),\n ['ModelA'] => array(\n [0] => array(\n 'id' => 1\n )\n)\n SELECT model_a.id FROM model_b JOIN model_a WHERE model_b.field = xxx $this->ModelA->find('all', array('conditions' => array('id' => $model_a_ids)));\n SELECT model_a.* FROM model_a WHERE id IN (1, 2, 3) WHERE id IN (1, 2, 3) AND id IN (3, 4, 5) $this->Model->query() FROM model_as AS ModelA" }, { "answer_id": 508683, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 1, "selected": true, "text": "with with $habtm = \" ...\n 'with' => 'MakeModel',\n ... \";\n find" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
112,738
<p>Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? </p>
[ { "answer_id": 113134, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "bind template<class R, class F, class L> class bind_t\n{\npublic:\n\n typedef bind_t this_type;\n\n bind_t(F f, L const & l): f_(f), l_(l) {}\n\n#define BOOST_BIND_RETURN return\n#include <boost/bind/bind_template.hpp>\n#undef BOOST_BIND_RETURN\n\n};\n bind_template operator() result_type operator()()\n{\n list0 a;\n BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);\n}\n BOOST_BIND_RETURN return return l_(type...) template<class A1> result_type operator()(A1 & a1)\n{\n list1<A1 &> a(a1);\n BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);\n}\n listN operator() unwrap // unwrap\n\ntemplate<class F> inline F & unwrap(F * f, long)\n{\n return *f;\n}\n\ntemplate<class F> inline F & unwrap(reference_wrapper<F> * f, int)\n{\n return f->get();\n}\n\ntemplate<class F> inline F & unwrap(reference_wrapper<F> const * f, int)\n{\n return f->get();\n}\n F bind R L" }, { "answer_id": 1839773, "author": "Decoder", "author_id": 223820, "author_profile": "https://Stackoverflow.com/users/223820", "pm_score": 2, "selected": false, "text": "bind_t boost/bind/bind_template.hpp template<class R, class F, class L> \nclass bind_t\n{\n public:\n\n typedef bind_t this_type;\n\n bind_t(F f, L const & l): f_(f), l_(l) {}\n\n typedef typename result_traits<R, F>::type result_type;\n ...\n template<class A1> \n result_type operator()(A1 & a1)\n {\n list1<A1 &> a(a1);\n return l_(type<result_type>(), f_, a, 0);\n }\n private:\n F f_;\n L l_;\n\n};\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
112,739
<p>What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree). Java prefered, pseudocode okay.</p> <p>Thanks!</p>
[ { "answer_id": 112752, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 2, "selected": false, "text": "int TreeDepth(Node* p)\n{\n return (p == NULL) ? 0 : min(TreeDepth(p->LeftChild), TreeDepth(p->RightChild)) + 1;\n}\n" }, { "answer_id": 112882, "author": "Captain Segfault", "author_id": 18408, "author_profile": "https://Stackoverflow.com/users/18408", "pm_score": 0, "selected": false, "text": "TD(p) is\n 0 if p is NULL (empty tree special case)\n 1 if p is a leaf (p->left == NULL and p->right == NULL)\n min(TD(p->left), TD(p->right)) if p is not a leaf \n" }, { "answer_id": 41503818, "author": "mgibson", "author_id": 1986796, "author_profile": "https://Stackoverflow.com/users/1986796", "pm_score": 0, "selected": false, "text": "if(root==null){\n return 0; \n}\n\nreturn root.data+Math.min(findCheapestPathSimple(root.left), findCheapestPathSimple(root.right));\n" }, { "answer_id": 69400574, "author": "Intuiter", "author_id": 7642928, "author_profile": "https://Stackoverflow.com/users/7642928", "pm_score": 0, "selected": false, "text": "shortestPath(X)\nif X == NIL\n return 0\nelse if X.left == NIL and X.right == NIL //X is a leaf\n return 1\nelse\n if X.left == NIL\n return 1 + shortestPath(X.right)\n else if X.right == NIL\n return 1 + shortestPath(X.left)\n else\n return 1 + min(shortestPath(X.left), shortestPath(X.right))\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83819/" ]
112,768
<p>(ClientCookie is a module for (automatic) cookie-handling: <a href="http://wwwsearch.sourceforge.net/ClientCookie" rel="nofollow noreferrer">http://wwwsearch.sourceforge.net/ClientCookie</a>)</p> <pre><code># I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'}) # And I send it and read the page: page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data) output = page.read() </code></pre> <p>The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?</p> <p>Any help would be greatly appreciated! Thanks!</p>
[ { "answer_id": 112819, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "import cookielib\nimport logging\nimport sys\nimport urllib\nimport urllib2\n\ncookies = cookielib.LWPCookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))\nurllib2.install_opener(opener)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',\n 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',\n 'Accept-Language': 'en-gb,en;q=0.5',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',\n}\n\n# Fetch the login page to set initial cookies\nurllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))\n\n# Login so we can access the Off Topic forum\nlogin_headers = headers.copy()\nlogin_headers.update({\n 'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',\n 'Content-Type': 'application/x-www-form-urlencoded',\n})\nhtml = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',\n urllib.urlencode({\n 'referer': 'http://www.rllmukforum.com/index.php?',\n 'UserName': RLLMUK_USERNAME,\n 'PassWord': RLLMUK_PASSWORD,\n }),\n login_headers)).read()\nif 'The following errors were found' in html:\n logging.error('RLLMUK login failed')\n logging.info(html)\n sys.exit(1)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
112,770
<p>Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?</p>
[ { "answer_id": 112773, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "--relocate" }, { "answer_id": 113820, "author": "Mauli", "author_id": 917, "author_profile": "https://Stackoverflow.com/users/917", "pm_score": 5, "selected": true, "text": "svn switch --relocate \\\n http://svn.example.com/path/to/repository/path/within/repository \\\n http://svnnew.example.com/new/repository/path/within/repository\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20150/" ]
112,775
<p>Is it possible to have a <code>MySQLi prepared statement</code> within the <code>fetch()</code> call of a previous statement? If not, what's the best way around it?</p> <p>Example code:</p> <pre><code>if($stmt = $link-&gt;prepare("SELECT item FROM data WHERE id = ?")) { $stmt-&gt;bind_param("i", $id); $stmt-&gt;execute(); $stmt-&gt;bind_result($item); while( $stmt-&gt;fetch() ) { /* Other code here */ $itemSummary = $item + $magic; if($stmt2 = $link-&gt;prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) { $stmt2-&gt;bind_param("is", $itemID, $itemSummary); $stmt2-&gt;execute(); $stmt2-&gt;close(); } } } </code></pre>
[ { "answer_id": 1675327, "author": "peterbriers", "author_id": 202803, "author_profile": "https://Stackoverflow.com/users/202803", "pm_score": 2, "selected": false, "text": "store_result" }, { "answer_id": 11923140, "author": "Etherealone", "author_id": 1576556, "author_profile": "https://Stackoverflow.com/users/1576556", "pm_score": 4, "selected": false, "text": "if($stmt = $link->prepare(\"SELECT item FROM data WHERE id = ?\")) {\n $stmt->bind_param(\"i\", $id);\n $stmt->execute();\n $stmt->store_result(); // <-- this\n $stmt->bind_result($item);\n while( $stmt->fetch() ) {\n /* Other code here */\n $itemSummary = $item + $magic;\n if($stmt2 = $link->prepare(\"INSERT INTO summaries (itemID, summary) VALUES (?, ?)\")) {\n $stmt2->bind_param(\"is\", $itemID, $itemSummary);\n $stmt2->execute();\n $stmt2->store_result(); // <-- this\n /*DO WHATEVER WITH STMT2*/\n $stmt2->close();\n }\n }\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
112,780
<p>Okay, so I'm making a table right now for "Box Items".</p> <p>Now, a Box Item, depending on what it's being used for/the status of the item, may end up being related to a "Shipping" box or a "Returns" box.</p> <p>A Box Item may be defective:if it is, a flag will be set in the Box Item's row (IsDefective), and the Box Item will be put in a "Returns" box (with other items to be returned to that vendor). Otherwise, the Box Item will eventually be put into a "Shipping" box (with other items to be shipped). (Note that Shipping and Returns boxes have their own tables: there's not one common table for all boxes... though maybe I should consider doing that if possible as a third possibility?)</p> <p>Maybe I'm just not thinking clearly today, but I started questioning what should be done in this situation.</p> <p>My gut tells me that I should have a separate field for each possible relation, even if only one of the relations can happen at any given time, which would make the schema for Box Items look like:</p> <p>BoxItemID Description IsDefective ShippingBoxID ReturnBoxID etc...</p> <p>This would make the relations clear, but it seems wasteful (since only one of the relations will be used at any time). So then I thought I could have just one field for the BoxID, and determine which BoxID it's referring to (a Shipping or a Returns Box ID) based on the IsDefective field:</p> <p>BoxItemID Description IsDefective BoxID etc...</p> <p>This seems less wasteful, but doesn't sit right with me. The relation isn't obvious.</p> <p>So, I put it to you, database gurus of Stackoverflow. What would you do in this situation?</p> <p>EDIT: Thank you everyone for your input! It's given me a lot to think about. For one, I'm going to use an ORM next time I start a project like this. =) For two, since I'm not right now, I'll bite the four bytes and use two fields.</p> <p>Thanks everyone again!</p>
[ { "answer_id": 112790, "author": "Mark S.", "author_id": 13968, "author_profile": "https://Stackoverflow.com/users/13968", "pm_score": 1, "selected": false, "text": "BoxItem:\nBoxItemID, Description, IsDefective\n\nBox:\nBoxID, Description\n\nBoxItemMap:\nBoxID, BoxItemID, BoxItemType\n" }, { "answer_id": 112862, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 0, "selected": false, "text": "BoxTable:\nbox_id, box_descrip, box_status_id ...\n 1, Lovely Box, 1\n 2, Borked box, 2\n 3, Ugly Box, 3\n 4, Flammable Box, 4\n\n BoxStatus:\n box_status_id, box_status_name, box_type_id, ....\n 1,Shippable, 1\n 2,Return, 2\n 3,Ugly, 2\n 4,Dangerous,3\n\n BoxType:\n box_type_id, box_type_name, ...\n 1, Shipping box, ...\n 2, Return box, ....\n 3, Hazmat box, ...\n" }, { "answer_id": 113848, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "Box ShippingBox ReturnBox BoxItem Box" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3068/" ]
112,796
<p>Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window:</p> <pre><code>Variable Value Summary jsonDict 0x45c540 4 key/value pairs NSObject {...} isa 0xa06e0720 </code></pre> <p>I was expecting it to show me each element of the dictionary (similar to an array variable). </p>
[ { "answer_id": 112808, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 8, "selected": true, "text": "po NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];\n[dict setObject:@\"foo\" forKey:@\"bar\"];\n[dict setObject:@\"fiz\" forKey:@\"buz\"];\n (gdb) po dict\n{\n bar = foo;\n buz = fiz;\n}\n NSString" }, { "answer_id": 114063, "author": "Jens Ayton", "author_id": 6443, "author_profile": "https://Stackoverflow.com/users/6443", "pm_score": 5, "selected": false, "text": "-debugDescription -description NSDictionary -description -description NSObject" }, { "answer_id": 11029942, "author": "uranpro", "author_id": 519358, "author_profile": "https://Stackoverflow.com/users/519358", "pm_score": 3, "selected": false, "text": "NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];\n[dict setObject:@\"foo\" forKey:@\"bar\"];\n[dict setObject:@\"fiz\" forKey:@\"buz\"];\nCFShow(dict);\n {\n bar = foo;\n buz = fiz;\n}\n" }, { "answer_id": 13953946, "author": "user1873574", "author_id": 1873574, "author_profile": "https://Stackoverflow.com/users/1873574", "pm_score": 0, "selected": false, "text": "All Variables, Registers, Globals and Statics Print description of \"....\"" }, { "answer_id": 16114195, "author": "jkatzer", "author_id": 193292, "author_profile": "https://Stackoverflow.com/users/193292", "pm_score": 2, "selected": false, "text": "The elements of NSArray and NSDictionary objects can now be inspected in the Xcode debugger\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11292/" ]
112,802
<p>Does anyone know of an MD5/SHA1/etc routine that is easily used with GLib (i.e. you can give it a GIOChannel, etc)?</p>
[ { "answer_id": 112872, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 2, "selected": false, "text": "void get_channel_md5( GIOChannel* channel, unsigned char output[16] )\n{\n md5_context ctx;\n\n gint64 fileSize = <get file size somehow?>;\n gint64 filePos = 0ll;\n\n gsize bufferSize = g_io_channel_get_buffer_size( channel );\n void* buffer = malloc( bufferSize );\n\n md5_starts( &ctx );\n\n // hash buffer at a time: \n while ( filePos < fileSize )\n {\n gint64 size = fileSize - filePos;\n if ( size > bufferSize )\n size = bufferSize;\n\n g_io_channel_read( channel, buffer );\n md5_update( &ctx, buffer, (int)size );\n\n filePos += bufferSize;\n }\n\n free( buffer );\n\n md5_finish( &ctx, output );\n}\n" }, { "answer_id": 112886, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "GChecksum" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5728/" ]
112,812
<p>How do I access parameters passed into an Oracle Form via a URL. Eg given the url:</p> <blockquote> <p><a href="http://example.com/forms90/f90servlet?config=cust&amp;form=" rel="nofollow noreferrer">http://example.com/forms90/f90servlet?config=cust&amp;form=</a>'a_form'&amp;p1=something&amp;p2=else</p> </blockquote> <p>This will launch the 'a_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')</p> <p>Does anyone know how I can do this? (Or even if it is/isn't possible?</p> <p>Thanks</p>
[ { "answer_id": 113990, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": true, "text": "if :PARAMETER.p1 = 'something' then\n do_something;\nend if;\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505600/" ]
112,818
<p>I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.</p> <p>The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options. </p> <p>What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code. </p> <p>This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user. </p> <p>Any suggestions on the best way to get this to work would be much appreciated.</p>
[ { "answer_id": 113838, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 4, "selected": true, "text": "SPContext.Current.Web.CurrentUser.LoginName\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11703/" ]
112,831
<p>Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at least see where it fails in my code (instead of library/ built-in routines)?</p>
[ { "answer_id": 112888, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 0, "selected": false, "text": "__try{} __except{}" }, { "answer_id": 114526, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 0, "selected": false, "text": "drwtsn32 -i drwtsn32" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
112,839
<p>What is the best way to resolve a conflict when doing a <code>git svn rebase</code>, and the git branch you are on becomes "(no-branch)"?</p>
[ { "answer_id": 112853, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "git mergetool git rebase --continue git rebase --skip" }, { "answer_id": 112859, "author": "csexton", "author_id": 19839, "author_profile": "https://Stackoverflow.com/users/19839", "pm_score": 7, "selected": false, "text": "git svn rebase (no-branch) git status .dotest git rebase --abort\n git add [file] git rebase --continue git add git rebase --skip git rebase --abort --abort git svn rebase --continue git svn rebase" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19839/" ]
112,861
<p>According to the documentation the return value from a slot doesn't mean anything.<br> Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?</p> <hr> <p>Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.</p> <pre><code>case 7: message((*reinterpret_cast&lt; const QString(*)&gt;(_a[1])),(*reinterpret_cast&lt; int(*)&gt;(_a[2]))); break; case 8: { int _r = selectPart((*reinterpret_cast&lt; AppObject*(*)&gt;(_a[1])),(*reinterpret_cast&lt; int(*)&gt;(_a[2]))); if (_a[0]) *reinterpret_cast&lt; int*&gt;(_a[0]) = _r; } break; </code></pre>
[ { "answer_id": 112960, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 4, "selected": false, "text": "bool QAbstractItemDelegate::helpEvent \n QAbstractItemView::viewportEvent\n case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2])));\nif (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;\n" }, { "answer_id": 154091, "author": "Terence Simpson", "author_id": 22395, "author_profile": "https://Stackoverflow.com/users/22395", "pm_score": 4, "selected": false, "text": " class MyClass : public QObject {\n Q_OBJECT\npublic:\n MyClass(QObject* parent);\n void Something();\npublic Q_SLOTS:\n int Other();\n};\n\nvoid MyClass::Something() {\n int res = this->Other();\n ...\n}\n" }, { "answer_id": 4625945, "author": "Macke", "author_id": 72312, "author_profile": "https://Stackoverflow.com/users/72312", "pm_score": 3, "selected": false, "text": "QGenericReturnArgument invokeMethod QObject:s Qt::BlockingQueuedConnection" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
112,883
<p>I want to change the standard "3D" look of the standard asp.net checkbox to say solid 1px. If I try to apply the styling to the Border for example it does just that - draws the standard checkbox with a border around it - which is valid I guess.</p> <p>Anyway, is there a way to change how the actual textbox is styled?</p>
[ { "answer_id": 112898, "author": "Dexter", "author_id": 10717, "author_profile": "https://Stackoverflow.com/users/10717", "pm_score": 1, "selected": false, "text": "<span class=\"CheckBoxStyle\">\n <input id=\"ctl00_cphContent_cbCheckBox\" \n name=\"ctl00$cphContent$cbCheckBox\"\n type=\"checkbox\">\n</span>\n span.CheckBox input {\n /* Styles here */\n}\n" }, { "answer_id": 2622646, "author": "purdueduck", "author_id": 314582, "author_profile": "https://Stackoverflow.com/users/314582", "pm_score": 2, "selected": false, "text": " chkOrder.InputAttributes[\"class\"] = \"fancyCssClass\";\n" }, { "answer_id": 37448889, "author": "cymorg", "author_id": 2898269, "author_profile": "https://Stackoverflow.com/users/2898269", "pm_score": 2, "selected": false, "text": "<style>\n .checkbox .btn, .checkbox-inline .btn {\n padding-left: 2em;\n min-width: 8em;\n }\n .checkbox label, .checkbox-inline label {\n text-align: left;\n padding-left: 0.5em;\n }\n .checkbox input[type=\"checkbox\"]{\n float:none;\n }\n</style>\n\n\n<div class=\"form-group\">\n <div class=\"checkbox\">\n <label class=\"btn btn-default\">\n <asp:CheckBox ID=\"chk1\" runat=\"server\" Text=\"Required\" />\n </label>\n </div>\n</div>\n" }, { "answer_id": 49016311, "author": "dizad87", "author_id": 6630427, "author_profile": "https://Stackoverflow.com/users/6630427", "pm_score": 2, "selected": false, "text": " input[type='checkbox']:after \n{\n\n width: 9px;\n height: 9px;\n border-radius: 9px;\n top: -2px;\n left: -1px;\n position: relative;\n background-color: #3B8054;\n content: '';\n display: inline-block;\n visibility: visible;\n border: 3px solid #3B8054;\n transition: 0.5s ease;\n cursor: pointer;\n\n}\n\ninput[type='checkbox']:checked:after \n {\n background-color: #9DFF00;\n }\n" }, { "answer_id": 64825568, "author": "bgmCoder", "author_id": 1038866, "author_profile": "https://Stackoverflow.com/users/1038866", "pm_score": 0, "selected": false, "text": "::before runat=server <asp:ImageButton ID=\"mycheckbox\" CssClass=\"checkbox\" runat=\"server\" OnClick=\"checkbox_Click\" ImageUrl=\"unchecked.png\" />\n<span class=\"checkboxlabel\">I have read and promise to fulfill the <a href=\"/index.aspx\">rules and obligations</a></span>\n protected void checkbox_Click(object sender, ImageClickEventArgs e) {\n if (mycheckbox.ImageUrl == \"unchecked.png\") {\n mycheckbox.ImageUrl = \"checked.png\";\n //Do something if user checks the box\n } else {\n mycheckbox.ImageUrl = \"unchecked.png\";\n //Do something if the user unchecks the box\n }\n }\n <span> .checkboxlabel{\n vertical-align:middle;\n font-weight: bold;\n}\n.checkbox{\n height: 24px; /*height of the checkbox image*/\n vertical-align: middle;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
112,892
<p>How would retrieve all customer's birthdays for a given month in SQL? What about MySQL? I was thinking of using the following with SQL server.</p> <pre><code>select c.name from cust c where datename(m,c.birthdate) = datename(m,@suppliedDate) order by c.name </code></pre>
[ { "answer_id": 112900, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "SELECT c.name\nFROM cust c\nWHERE (\n MONTH(c.birthdate) = MONTH(@suppliedDate)\n AND DAY(c.birthdate) = DAY(@suppliedDate)\n) OR (\n MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29\n AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1\n AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0))\n)\n" }, { "answer_id": 113062, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 1, "selected": false, "text": "SELECT name\nFROM cust\nWHERE birthmonth = MONTH(NOW())\nORDER BY name;\n" }, { "answer_id": 113974, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": false, "text": "SELECT c.name\nFROM cust c\nWHERE datepart(m,c.birthdate) = @SuppliedMonth\n" }, { "answer_id": 58663183, "author": "ILIAS M. DOLAPO", "author_id": 9050759, "author_profile": "https://Stackoverflow.com/users/9050759", "pm_score": 0, "selected": false, "text": " SELECT * FROM tbl_Employee WHERE DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DOB), DOB) BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
112,897
<p>The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a <code>file &gt; 4GB</code>?</p> <pre><code>fpos_t currentpos; sok=fseek(fp,0,SEEK_END); assert(sok==0,"Seek error!"); fgetpos(fp,&amp;currentpos); m_filesize=currentpos; </code></pre>
[ { "answer_id": 112913, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "int fgetpos64 (FILE *stream, fpos64_t *position) fpos64_t _FILE_OFFSET_BITS == 64 fgetpos" }, { "answer_id": 112942, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "int64_t bigFileSize(const char *path)\n{\n struct stat64 S;\n\n if(-1 == stat64(path, &S))\n {\n printf(\"Error!\\r\\n\");\n return -1;\n }\n\n return S.st_size;\n}\n" }, { "answer_id": 3399458, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 3, "selected": false, "text": "-D_FILE_OFFSET_BITS=64 fseeko ftello off_t long off_t" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
112,932
<p>I really like <strong>Araxis</strong> Merge for a graphical DIFF program for the PC. I have no idea what's available for <strong>linux</strong>, though. We're running SUSE linux on our z800 mainframe. I'd be most grateful if I could get a few pointers to what programs everyone else likes.</p>
[ { "answer_id": 113328, "author": "Sridhar Iyer", "author_id": 13820, "author_profile": "https://Stackoverflow.com/users/13820", "pm_score": 6, "selected": false, "text": "vim -d file1 file2" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20158/" ]
112,946
<p>I'm using C++ and accessing a UNC path across the network. This path is slightly greater than MAX_PATH. So I cannot obtain a file handle.</p> <p>But if I run the program on the computer in question, the path is not greater than MAX_PATH. So I can get a file handle. If I rename the file to have less characters (minus length of computer name) I can access the file. </p> <p>Can this file be accessed across the network even know the computer name in the UNC path puts it over the MAX_PATH limit?</p>
[ { "answer_id": 112961, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "\\\\?\\ MAX_PATH \\\\?\\unc\\server\\share\\path\\file \\\\?\\unc\\" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
112,964
<p>Ubuntu has 8 run levels (0-6 and S), I want to add the run level 7.</p> <p>I have done the following:</p> <p>1.- Created the folder <strong>/etc/rc7.d/</strong>, which contains some symbolic links to <strong>/etc/init.d/</strong></p> <p>2.- Created the file <strong>/etc/event.d/rc7</strong> This is its content:</p> <pre><code># rc7 - runlevel 7 compatibility # # This task runs the old sysv-rc runlevel 7 ("multi-user") scripts. It # is usually started by the telinit compatibility wrapper. start on runlevel 7 stop on runlevel [!7] console output script set $(runlevel --set 7 || true) if [ "$1" != "unknown" ]; then PREVLEVEL=$1 RUNLEVEL=$2 export PREVLEVEL RUNLEVEL fi exec /etc/init.d/rc 7 end script </code></pre> <p>I thought that would be enough, but <strong>telinit 7</strong> still throws this error: <em>telinit: illegal runlevel: 7</em></p>
[ { "answer_id": 113026, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 0, "selected": false, "text": "/etc/inittab" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7852/" ]
112,970
<p>What's the difference between <code>file</code> and <code>open</code> in Python? When should I use which one? (Say I'm in 2.5)</p>
[ { "answer_id": 112980, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 8, "selected": true, "text": "open() file()" }, { "answer_id": 112982, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": false, "text": "open file open open" }, { "answer_id": 112989, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 5, "selected": false, "text": "file file file('myfile.txt') open file io" }, { "answer_id": 113050, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "file() open() file f = open(filename, 'r')\nfor line in f:\n process(line)\nf.close()\n class LoggingFile(file):\n def write(self, data):\n sys.stderr.write(\"Wrote %d bytes\\n\" % len(data))\n super(LoggingFile, self).write(data)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
112,977
<p>I want to implement Generics in my Page Class like :</p> <pre><code>Public Class MyClass(Of TheClass) Inherits System.Web.UI.Page </code></pre> <p>But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?</p>
[ { "answer_id": 113080, "author": "Costo", "author_id": 1130, "author_profile": "https://Stackoverflow.com/users/1130", "pm_score": 2, "selected": false, "text": "Partial Public Class MyPage\n Inherits MyGenericBasePage(Of MyType)\n\nEnd Class\n\nPublic Class MyGenericBasePage(Of T As New)\n Inherits System.Web.UI.Page\n\n Public Function MyGenericMethod() As T\n Return New T()\n End Function\n\nEnd Class\n\nPublic Class MyType\n\nEnd Class\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
112,983
<p>I want to display data like the following:</p> <pre><code> Title Subject Summary Date </code></pre> <p>So my <code>HTML</code> looks like:</p> <pre><code>&lt;div class="title"&gt;&lt;/div&gt; &lt;div class="subject"&gt;&lt;/div&gt; &lt;div class="summary"&gt;&lt;/div&gt; &lt;div class="date"&gt;&lt;/div&gt; </code></pre> <p>The problem is, all the text doesn't appear on a single line. I tried adding <code>display="block"</code> but that doesn't seem to work.</p> <p>What am I doing wrong here?</p> <p><strong>Important:</strong> In this instance I dont want to use a <code>table</code> element but stick with <code>div</code> tags.</p>
[ { "answer_id": 112997, "author": "Matthew Encinas", "author_id": 14433, "author_profile": "https://Stackoverflow.com/users/14433", "pm_score": 0, "selected": false, "text": "<ul class=\"headers\">\n <li>Title</li>\n <li>Subject</li>\n <li>Summary</li>\n <li>Date</li>\n</ul>\n" }, { "answer_id": 113021, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 3, "selected": false, "text": "div.title {\n width: 150 px;\n float: left;\n}\n" }, { "answer_id": 113034, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": false, "text": "<table>\n <tr>\n <th>Title</th>\n <th>Subject</th>\n <th>Summary</th>\n <th>Date</th>\n </tr>\n <!-- Data rows -->\n</table>\n" }, { "answer_id": 113119, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 2, "selected": false, "text": "display: table-* <div> display: block\n display: inline\n <table>" }, { "answer_id": 113161, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 0, "selected": false, "text": "whitespace:scroll whitespace:hidden" }, { "answer_id": 113905, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "<div class=\"title\">MyTitle</div><div class=\"subject\">MySubject</div><div class=\"Summary\">MySummary</div>\n div \n{\n display: inline;\n}\n div \n{\n width: 15%; /* size of each column : adapt */\n float: left; /* this make the block float at the left of the next one */\n}\n\ndiv.last_element /* last_element must be a class of the last div of your line */\n{\n clear: right; /* prevent your the next line to jump on the previous one */\n}\n" }, { "answer_id": 1769555, "author": "SamGoody", "author_id": 87520, "author_profile": "https://Stackoverflow.com/users/87520", "pm_score": 0, "selected": false, "text": "display:inline-block\n" }, { "answer_id": 1769638, "author": "Darren Walker", "author_id": 215335, "author_profile": "https://Stackoverflow.com/users/215335", "pm_score": 1, "selected": false, "text": "<ul>\n <li>\n heading 1\n <ul>\n <li>row 1 data</li>\n <li>row 2 data</li>\n <ul>\n </li>\n <li>\n heading 2\n <ul>\n <li>row 1 data</li>\n <li>row 2 data</li>\n <ul>\n </li>\n</ul>\n" }, { "answer_id": 12072406, "author": "Sanuj", "author_id": 1537696, "author_profile": "https://Stackoverflow.com/users/1537696", "pm_score": 0, "selected": false, "text": "display:block display:inline-block display:table display:table-cell display:table-row" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/112983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
113,024
<p>Im trying to put an html embed code for a flash video into the <code>rss feed</code>, which will then be parser by a parser <code>(magpie)</code> on my other site. How should I encode the embed code on one side, and then decode it on the other so I can insert clean html into the <code>DB</code> on the receiving server?</p>
[ { "answer_id": 10395520, "author": "vdboor", "author_id": 146289, "author_profile": "https://Stackoverflow.com/users/146289", "pm_score": 0, "selected": false, "text": "django.contrib.syndication" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]